-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathcrypto.go
More file actions
42 lines (34 loc) · 965 Bytes
/
crypto.go
File metadata and controls
42 lines (34 loc) · 965 Bytes
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
package main
import (
"crypto/rand"
"crypto/rsa"
"crypto/sha256"
"encoding/base64"
"log"
)
// function to encrypt message to be sent
func encrypt(msg string, key rsa.PublicKey) string {
label := []byte("OAEP Encrypted")
rng := rand.Reader
// * using OAEP algorithm to make it more secure
// * using sha256
ciphertext, err := rsa.EncryptOAEP(sha256.New(), rng, &key, []byte(msg), label)
// check for errors
if err != nil {
log.Fatalln("unable to encrypt")
}
return base64.StdEncoding.EncodeToString(ciphertext)
}
// function to decrypt message to be received
func decrypt(cipherText string, key rsa.PrivateKey) string {
ct, _ := base64.StdEncoding.DecodeString(cipherText)
label := []byte("OAEP Encrypted")
rng := rand.Reader
// decrypting based on same parameters as encryption
plaintext, err := rsa.DecryptOAEP(sha256.New(), rng, &key, ct, label)
// check for errors
if err != nil {
log.Fatalln(err)
}
return string(plaintext)
}