-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrsa.go
83 lines (78 loc) · 1.98 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
72
73
74
75
76
77
78
79
80
81
82
83
package pwd
import (
"crypto/rand"
"crypto/rsa"
"crypto/x509"
"encoding/pem"
"fmt"
"os"
"strings"
"github.com/palp1tate/go-crypto-guard"
)
func GenRSAKey(bits int) error {
privateKey, err := rsa.GenerateKey(rand.Reader, bits)
if err != nil {
return err
}
privateStream := x509.MarshalPKCS1PrivateKey(privateKey)
block1 := pem.Block{
Type: "private key",
Bytes: privateStream,
}
fPrivate, err := os.Create("privateKey.pem")
if err != nil {
return err
}
defer fPrivate.Close()
err = pem.Encode(fPrivate, &block1)
if err != nil {
return err
}
publicKey := privateKey.PublicKey
publicStream, err := x509.MarshalPKIXPublicKey(&publicKey)
block2 := pem.Block{
Type: "public key",
Bytes: publicStream,
}
fPublic, err := os.Create("publicKey.pem")
if err != nil {
return err
}
defer fPublic.Close()
pem.Encode(fPublic, &block2)
return nil
}
func GenRSA(password, publicKeyPath string) (encryptedPassword string, err error) {
f, err := os.Open(publicKeyPath)
if err != nil {
return
}
defer f.Close()
fileInfo, _ := f.Stat()
b := make([]byte, fileInfo.Size())
f.Read(b)
block, _ := pem.Decode(b)
keyInit, _ := x509.ParsePKIXPublicKey(block.Bytes)
pubKey := keyInit.(*rsa.PublicKey)
res, _ := rsa.EncryptPKCS1v15(rand.Reader, pubKey, []byte(password))
encryptedPassword = fmt.Sprintf("%s$%s", pwd.RSA, pwd.EncodeToString(res))
return
}
func VerifyRSA(password, encryptedPassword, privateKeyPath string) (isValid bool, err error) {
parts := strings.Split(encryptedPassword, "$")
if len(parts) != 2 {
err = fmt.Errorf("invalid encrypted password format")
return
}
decodedPassword, err := pwd.DecodeString(parts[1])
f, _ := os.Open(privateKeyPath)
defer f.Close()
fileInfo, _ := f.Stat()
b := make([]byte, fileInfo.Size())
f.Read(b)
block, _ := pem.Decode(b)
privateKey, _ := x509.ParsePKCS1PrivateKey(block.Bytes)
encodedPassword, _ := rsa.DecryptPKCS1v15(rand.Reader, privateKey, decodedPassword)
isValid = password == string(encodedPassword)
return
}