Skip to content

Instantly share code, notes, and snippets.

@rueian
Created January 8, 2024 12:22
Show Gist options
  • Save rueian/82e6d7082b87dca8bbe453ded4dd9633 to your computer and use it in GitHub Desktop.
Save rueian/82e6d7082b87dca8bbe453ded4dd9633 to your computer and use it in GitHub Desktop.
package main
import (
"crypto/rand"
"crypto/rsa"
"crypto/sha256"
"fmt"
)
func main() {
// Generate RSA Keys
privateKey, err := rsa.GenerateKey(rand.Reader, 2048)
if err != nil {
fmt.Println(err)
return
}
publicKey := &privateKey.PublicKey
// Message to encrypt
message := []byte("your message here")
// Encrypt message with private key (this is usually for signing)
// In standard practice, you should encrypt with public key
encryptedMessage, err := rsa.EncryptOAEP(sha256.New(), rand.Reader, &rsa.PrivateKey{D: privateKey.D, PublicKey: *publicKey}, message, nil)
if err != nil {
fmt.Println(err)
return
}
fmt.Println("Encrypted Message: ", encryptedMessage)
// Decrypt message with public key
decryptedMessage, err := rsa.DecryptOAEP(sha256.New(), rand.Reader, privateKey, encryptedMessage, nil)
if err != nil {
fmt.Println(err)
return
}
fmt.Println("Decrypted Message: ", string(decryptedMessage))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment