-
Notifications
You must be signed in to change notification settings - Fork 2
/
rsa.go
71 lines (55 loc) · 1.44 KB
/
rsa.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
package rsa
import (
"crypto/rand"
"crypto/rsa"
"crypto/sha512"
"crypto/x509"
"encoding/base64"
"encoding/pem"
"github.com/alexfalkowski/go-service/crypto/algo"
)
// Generate key pair with RSA.
func Generate() (string, string, error) {
p, err := rsa.GenerateKey(rand.Reader, 4096)
if err != nil {
return "", "", err
}
pub := pem.EncodeToMemory(&pem.Block{Type: "RSA PUBLIC KEY", Bytes: x509.MarshalPKCS1PublicKey(&p.PublicKey)})
pri := pem.EncodeToMemory(&pem.Block{Type: "RSA PRIVATE KEY", Bytes: x509.MarshalPKCS1PrivateKey(p)})
return string(pub), string(pri), nil
}
// Algo for rsa.
type Algo interface {
algo.Cipher
}
// NewAlgo for rsa.
func NewAlgo(cfg *Config) (Algo, error) {
if !IsEnabled(cfg) {
return &algo.NoCipher{}, nil
}
pub, err := cfg.PublicKey()
if err != nil {
return nil, err
}
pri, err := cfg.PrivateKey()
if err != nil {
return nil, err
}
return &rsaAlgo{publicKey: pub, privateKey: pri}, nil
}
type rsaAlgo struct {
publicKey *rsa.PublicKey
privateKey *rsa.PrivateKey
}
func (a *rsaAlgo) Encrypt(msg string) (string, error) {
e, err := rsa.EncryptOAEP(sha512.New(), rand.Reader, a.publicKey, []byte(msg), nil)
return base64.StdEncoding.EncodeToString(e), err
}
func (a *rsaAlgo) Decrypt(msg string) (string, error) {
d, err := base64.StdEncoding.DecodeString(msg)
if err != nil {
return "", err
}
d, err = rsa.DecryptOAEP(sha512.New(), rand.Reader, a.privateKey, d, nil)
return string(d), err
}