-
-
Save rueian/4d5e04b5040e8b2630f78b96236864d9 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"crypto/rand" | |
"crypto/rsa" | |
"crypto/x509" | |
"encoding/pem" | |
"fmt" | |
) | |
// Function to generate RSA key pair | |
func generateKeyPair(bits int) (*rsa.PrivateKey, error) { | |
privateKey, err := rsa.GenerateKey(rand.Reader, bits) | |
if err != nil { | |
return nil, err | |
} | |
return privateKey, nil | |
} | |
// Function to encrypt data with a public key | |
func encryptWithPublicKey(data []byte, publicKey *rsa.PublicKey) ([]byte, error) { | |
encryptedData, err := rsa.EncryptPKCS1v15(rand.Reader, publicKey, data) | |
if err != nil { | |
return nil, err | |
} | |
return encryptedData, nil | |
} | |
// Function to export a RSA key to PEM format | |
func exportRsaKeyToPemStr(key *rsa.PrivateKey) string { | |
privateKeyBytes := x509.MarshalPKCS1PrivateKey(key) | |
privateKeyPem := pem.EncodeToMemory( | |
&pem.Block{ | |
Type: "RSA PRIVATE KEY", | |
Bytes: privateKeyBytes, | |
}, | |
) | |
return string(privateKeyPem) | |
} | |
// Function to export a RSA public key to PEM format | |
func exportRsaPublicKeyToPemStr(pubKey *rsa.PublicKey) (string, error) { | |
publicKeyBytes, err := x509.MarshalPKIXPublicKey(pubKey) | |
if err != nil { | |
return "", err | |
} | |
publicKeyPem := pem.EncodeToMemory( | |
&pem.Block{ | |
Type: "RSA PUBLIC KEY", | |
Bytes: publicKeyBytes, | |
}, | |
) | |
return string(publicKeyPem), nil | |
} | |
func main() { | |
// Replace this with your 32-byte key | |
dataToEncrypt := []byte("your-32-byte-key-here____________") | |
// Generating RSA Key Pair | |
privateKey, err := generateKeyPair(2048) | |
if err != nil { | |
fmt.Println("Error generating key pair:", err) | |
return | |
} | |
publicKey := &privateKey.PublicKey | |
publicKeyPem, err := exportRsaPublicKeyToPemStr(publicKey) | |
if err != nil { | |
fmt.Println("Error exporting public key:", err) | |
return | |
} | |
// Encrypting Data | |
encryptedData, err := encryptWithPublicKey(dataToEncrypt, publicKey) | |
if err != nil { | |
fmt.Println("Error encrypting data:", err) | |
return | |
} | |
// Output the encrypted data and keys | |
fmt.Println("Encrypted Data:", encryptedData) | |
fmt.Println("Public Key:", publicKeyPem) | |
fmt.Println("Private Key:", exportRsaKeyToPemStr(privateKey)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment