-
-
Notifications
You must be signed in to change notification settings - Fork 1
/
main.go
52 lines (40 loc) · 1.25 KB
/
main.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
package rsa
import (
b64 "encoding/base64"
"fmt"
)
type KeyPair struct {
PrivateKey string
PublicKey string
}
// Generates a new RSA key pair.
func GenerateKeyPair(keySize int, passphrase string) KeyPair {
privKey, publicKey := generateRsaKeys(keySize)
privKeyByte := PrivateKeyToBytes(privKey, passphrase)
publicKeyByte := PublicKeyToBytes(publicKey, passphrase)
// Keys in PEM format
return KeyPair{
PrivateKey: string(privKeyByte),
PublicKey: string(publicKeyByte),
}
}
// RSA Encrypt
func Encrypt(publicKey string, plainText string, passphrase string) string {
pubKey := PemToPublicKey([]byte(publicKey), passphrase)
// Encrypt plaintext
ciphertext := encryptUsingPublicKey(pubKey, []byte(plainText))
// Convert ciphertext to base64 string.
return b64.StdEncoding.EncodeToString(ciphertext)
}
// RSA Decrypt
func Decrypt(privateKey string, cipherText string, passphrase string) string {
privKey := PemToPrivateKey([]byte(privateKey), passphrase)
// Convert ciphertext from base64 string.
ciphertext, err := b64.StdEncoding.DecodeString(cipherText)
if err != nil {
panic(fmt.Sprintf("failed to decode ciphertext: %s", err))
}
// Decrypt ciphertext
plaintext := decryptUsingPrivateKey(privKey, ciphertext)
return string(plaintext)
}