-
Notifications
You must be signed in to change notification settings - Fork 29
/
Copy pathrsa_sample.go
91 lines (68 loc) · 1.86 KB
/
rsa_sample.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
84
85
86
87
88
89
90
91
package main
import (
"crypto"
"crypto/rand"
"crypto/rsa"
"crypto/sha256"
"fmt"
"os"
)
func main() {
// Generate RSA Keys
miryanPrivateKey, err := rsa.GenerateKey(rand.Reader, 2048)
if err != nil {
fmt.Println(err.Error)
os.Exit(1)
}
miryanPublicKey := &miryanPrivateKey.PublicKey
raulPrivateKey, err := rsa.GenerateKey(rand.Reader, 2048)
if err != nil {
fmt.Println(err.Error)
os.Exit(1)
}
raulPublicKey := &raulPrivateKey.PublicKey
fmt.Println("Private Key : ", miryanPrivateKey)
fmt.Println("Public key ", miryanPublicKey)
fmt.Println("Private Key : ", raulPrivateKey)
fmt.Println("Public key ", raulPublicKey)
//Encrypt Miryan Message
message := []byte("the code must be like a piece of music")
label := []byte("")
hash := sha256.New()
ciphertext, err := rsa.EncryptOAEP(hash, rand.Reader, raulPublicKey, message, label)
if err != nil {
fmt.Println(err)
os.Exit(1)
}
fmt.Printf("OAEP encrypted [%s] to \n[%x]\n", string(message), ciphertext)
fmt.Println()
// Message - Signature
var opts rsa.PSSOptions
opts.SaltLength = rsa.PSSSaltLengthAuto // for simple example
PSSmessage := message
newhash := crypto.SHA256
pssh := newhash.New()
pssh.Write(PSSmessage)
hashed := pssh.Sum(nil)
signature, err := rsa.SignPSS(rand.Reader, miryanPrivateKey, newhash, hashed, &opts)
if err != nil {
fmt.Println(err)
os.Exit(1)
}
fmt.Printf("PSS Signature : %x\n", signature)
// Decrypt Message
plainText, err := rsa.DecryptOAEP(hash, rand.Reader, raulPrivateKey, ciphertext, label)
if err != nil {
fmt.Println(err)
os.Exit(1)
}
fmt.Printf("OAEP decrypted [%x] to \n[%s]\n", ciphertext, plainText)
//Verify Signature
err = rsa.VerifyPSS(miryanPublicKey, newhash, hashed, signature, &opts)
if err != nil {
fmt.Println("Who are U? Verify Signature failed")
os.Exit(1)
} else {
fmt.Println("Verify Signature successful")
}
}