/
rosa.go
70 lines (54 loc) · 1.72 KB
/
rosa.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
// Package rosa wrap the RSA package in a simplified form
package rosa
import (
"crypto/md5"
"crypto/rand"
"crypto/rsa"
)
//PublicKeyPath where is stored the public key
var PublicKeyPath string
//PrivateKeyPath where is stored the private key
var PrivateKeyPath string
//FriendListPath where is stored the friend list
var FriendListPath string
//Decrypt decrypt the given message with the given private key.
func Decrypt(content []byte, privatekey *rsa.PrivateKey) ([]byte, error) {
md5hash := md5.New()
label := []byte("")
decryptedmsg, err := rsa.DecryptOAEP(md5hash, rand.Reader, privatekey, content, label)
if err != nil {
return nil, err
}
return decryptedmsg, nil
}
//Encrypt Encrypt the given message with the given public key.
func Encrypt(content []byte, publickey *rsa.PublicKey) ([]byte, error) {
md5hash := md5.New()
label := []byte("")
encryptedmsg, err := rsa.EncryptOAEP(md5hash, rand.Reader, publickey, content, label)
if err != nil {
return nil, err
}
return encryptedmsg, nil
}
//Generate is use to create a pair of keys (Private and Public) you can specify if you want to save them in a file,
// the path is defined by PrivateKeyPath and PublicKeyPath global variable
func Generate(identifier string, save bool) (*rsa.PrivateKey, *rsa.PublicKey, error) {
var publickey *rsa.PublicKey
var privatekey *rsa.PrivateKey
privatekey, err := rsa.GenerateKey(rand.Reader, 1024)
if err != nil {
return nil, nil, err
}
privatekey.Precompute()
err = privatekey.Validate()
if err != nil {
return nil, nil, err
}
publickey = &privatekey.PublicKey
if save == true {
savePrivateKey(privatekey, PrivateKeyPath)
savePublicKey(publickey, identifier, PublicKeyPath)
}
return privatekey, publickey, nil
}