80 lines
1.5 KiB
Go
80 lines
1.5 KiB
Go
package crypto
|
|
|
|
import (
|
|
"crypto/rand"
|
|
"crypto/rsa"
|
|
"crypto/sha1"
|
|
"crypto/sha256"
|
|
"crypto/x509"
|
|
"encoding/base64"
|
|
"encoding/hex"
|
|
"fmt"
|
|
"os"
|
|
)
|
|
|
|
func Unlock() {
|
|
LoadOrGenerateKey(false)
|
|
}
|
|
|
|
func RSAEncrypt(key *rsa.PublicKey, buf string) string {
|
|
secretMessage := []byte(buf)
|
|
|
|
rng := rand.Reader
|
|
|
|
ciphertext, err := rsa.EncryptPKCS1v15(rng, key, secretMessage)
|
|
if err != nil {
|
|
fmt.Fprintf(os.Stderr, "Error from encryption: %s\n", err)
|
|
return ""
|
|
}
|
|
|
|
return "RSA " + base64.StdEncoding.EncodeToString(ciphertext)
|
|
}
|
|
|
|
func (c *connection) rsaDecrypt(buf string) string {
|
|
return RSADecrypt(c.privateKey, buf)
|
|
}
|
|
|
|
func RSADecrypt(key *rsa.PrivateKey, buf string) string {
|
|
// Remove RSA Prefix
|
|
buf = buf[4:]
|
|
|
|
b, err := base64.StdEncoding.DecodeString(buf)
|
|
|
|
// crypto/rand.Reader is a good source of entropy for blinding the RSA
|
|
// operation.
|
|
rng := rand.Reader
|
|
|
|
plaintext, err := rsa.DecryptPKCS1v15(rng, key, b)
|
|
if err != nil {
|
|
fmt.Fprintf(os.Stderr, "Error from decryption: %s\n", err)
|
|
return ""
|
|
}
|
|
|
|
return string(plaintext)
|
|
}
|
|
|
|
func (c *connection) publicKeyBase64() string {
|
|
bytes, _ := x509.MarshalPKIXPublicKey(c.publicKey)
|
|
b64 := base64.StdEncoding.EncodeToString(bytes)
|
|
|
|
return b64
|
|
}
|
|
|
|
func (p *peer) publicKeyFingerprint() string {
|
|
h := sha256.New()
|
|
|
|
bytes, _ := x509.MarshalPKIXPublicKey(p.publicKey)
|
|
h.Write(bytes)
|
|
|
|
return hex.EncodeToString(h.Sum(nil))
|
|
}
|
|
|
|
func (p *peer) publicKeyFingerprintSha1() string {
|
|
h := sha1.New()
|
|
|
|
bytes, _ := x509.MarshalPKIXPublicKey(p.publicKey)
|
|
h.Write(bytes)
|
|
|
|
return hex.EncodeToString(h.Sum(nil))
|
|
}
|