Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package main
- import (
- "crypto"
- "crypto/rand"
- "crypto/rsa"
- "crypto/sha256"
- "fmt"
- "os"
- )
- func main() {
- // Set up both public and private key to both jimena and Alisair.
- jimenaPrivateKey, err := rsa.GenerateKey(rand.Reader, 2048)
- if err != nil {
- fmt.Println(err.Error())
- os.Exit(1)
- }
- jimenaPublicKey := &jimenaPrivateKey.PublicKey
- alistairPrivateKey, err := rsa.GenerateKey(rand.Reader, 2048)
- if err != nil {
- fmt.Println(err.Error())
- os.Exit(1)
- }
- alistairPublicKey := &alistairPrivateKey.PublicKey
- fmt.Println("JIMENA PRIVATE KEY:")
- fmt.Println("")
- fmt.Println(jimenaPrivateKey)
- fmt.Println("")
- fmt.Println("JIMENA PUBLIC KEY:")
- fmt.Println("")
- fmt.Println(jimenaPublicKey)
- fmt.Println("")
- fmt.Println("ALISTAIR PRIVATE KEY:")
- fmt.Println("")
- fmt.Println(alistairPrivateKey)
- fmt.Println("")
- fmt.Println("ALISTAIR PUBLIC KEY:")
- fmt.Println("")
- fmt.Println(alistairPublicKey)
- fmt.Println("")
- // Get message, convert to bytes, hash the message and encrypt with alistairs public key.
- message := []byte("The code must be like a piece of music")
- label := []byte("")
- hash := sha256.New()
- ciphertext, err := rsa.EncryptOAEP(hash, rand.Reader, alistairPublicKey, message, label)
- if err != nil {
- fmt.Println(err)
- os.Exit(1)
- }
- fmt.Println("ENCRYPTED MESSAGE:")
- fmt.Println("")
- fmt.Printf("OAEP encrypted the message: %s to: \n[%x]\n", string(message), ciphertext)
- fmt.Println("")
- // Next Jimena should sign your message with her
- //private key to ensure the recipient can check
- //the message sender with Jimena’s public key
- //to confirm the sender is Jimena.
- 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, jimenaPrivateKey, newhash, hashed, &opts)
- if err != nil {
- fmt.Println(err)
- os.Exit(1)
- }
- fmt.Println("PSS SIGNATURE:")
- fmt.Println("")
- fmt.Printf("PSS Signature : %x\n", signature)
- // Now Alistair needs to decrypt the message
- plainText, err := rsa.DecryptOAEP(hash, rand.Reader, alistairPrivateKey, ciphertext, label)
- if err != nil {
- fmt.Println(err)
- os.Exit(1)
- }
- fmt.Println("")
- fmt.Println("DECRYPTED MESSAGE:")
- fmt.Println("")
- fmt.Printf("OAEP decrypted [%x] to \n[%s]\n", ciphertext, plainText)
- // Last thing is for Alistair to check the message origin
- // to determine that it is Jimena who sent the message
- err = rsa.VerifyPSS(jimenaPublicKey, newhash, hashed, signature, &opts)
- if err != nil {
- fmt.Println("Who are U?? Verify signature failed")
- os.Exit(1)
- } else {
- fmt.Println("")
- fmt.Println("Verify signature successful")
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement