├── README └── rsa_sample.go /README: -------------------------------------------------------------------------------- 1 | # Brainattica & Cryptography. Golang & Cryptography. RSA sample.. 2 | 3 | This repo make reference to a post in our blog [http://http://blog.brainattica.com/golang-cryptography-rsa/] -------------------------------------------------------------------------------- /rsa_sample.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "crypto" 5 | "crypto/rand" 6 | "crypto/rsa" 7 | "crypto/sha256" 8 | "fmt" 9 | "os" 10 | ) 11 | 12 | func main() { 13 | 14 | // Generate RSA Keys 15 | miryanPrivateKey, err := rsa.GenerateKey(rand.Reader, 2048) 16 | 17 | if err != nil { 18 | fmt.Println(err.Error) 19 | os.Exit(1) 20 | } 21 | 22 | miryanPublicKey := &miryanPrivateKey.PublicKey 23 | 24 | raulPrivateKey, err := rsa.GenerateKey(rand.Reader, 2048) 25 | 26 | if err != nil { 27 | fmt.Println(err.Error) 28 | os.Exit(1) 29 | } 30 | 31 | raulPublicKey := &raulPrivateKey.PublicKey 32 | 33 | fmt.Println("Private Key : ", miryanPrivateKey) 34 | fmt.Println("Public key ", miryanPublicKey) 35 | fmt.Println("Private Key : ", raulPrivateKey) 36 | fmt.Println("Public key ", raulPublicKey) 37 | 38 | //Encrypt Miryan Message 39 | message := []byte("the code must be like a piece of music") 40 | label := []byte("") 41 | hash := sha256.New() 42 | 43 | ciphertext, err := rsa.EncryptOAEP(hash, rand.Reader, raulPublicKey, message, label) 44 | 45 | if err != nil { 46 | fmt.Println(err) 47 | os.Exit(1) 48 | } 49 | 50 | fmt.Printf("OAEP encrypted [%s] to \n[%x]\n", string(message), ciphertext) 51 | fmt.Println() 52 | 53 | // Message - Signature 54 | var opts rsa.PSSOptions 55 | opts.SaltLength = rsa.PSSSaltLengthAuto // for simple example 56 | PSSmessage := message 57 | newhash := crypto.SHA256 58 | pssh := newhash.New() 59 | pssh.Write(PSSmessage) 60 | hashed := pssh.Sum(nil) 61 | 62 | signature, err := rsa.SignPSS(rand.Reader, miryanPrivateKey, newhash, hashed, &opts) 63 | 64 | if err != nil { 65 | fmt.Println(err) 66 | os.Exit(1) 67 | } 68 | 69 | fmt.Printf("PSS Signature : %x\n", signature) 70 | 71 | // Decrypt Message 72 | plainText, err := rsa.DecryptOAEP(hash, rand.Reader, raulPrivateKey, ciphertext, label) 73 | 74 | if err != nil { 75 | fmt.Println(err) 76 | os.Exit(1) 77 | } 78 | 79 | fmt.Printf("OAEP decrypted [%x] to \n[%s]\n", ciphertext, plainText) 80 | 81 | //Verify Signature 82 | err = rsa.VerifyPSS(miryanPublicKey, newhash, hashed, signature, &opts) 83 | 84 | if err != nil { 85 | fmt.Println("Who are U? Verify Signature failed") 86 | os.Exit(1) 87 | } else { 88 | fmt.Println("Verify Signature successful") 89 | } 90 | 91 | } 92 | --------------------------------------------------------------------------------