1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677 |
- package unchat
- import (
- "crypto/rand"
- "crypto/rsa"
- "crypto/sha256"
- "crypto/x509"
- "encoding/pem"
- "fmt"
- "log"
- )
- func main() {
- key_pk, err := rsa.GenerateKey(rand.Reader, 2048)
- if err != nil {
- log.Fatalf("could not generate keypair %s", err)
- }
- pub_key := &key_pk.PublicKey
- msg := []byte("this is a new message to be encrypted")
- label := []byte("")
- hash := sha256.New()
- cipher_text, err := rsa.EncryptOAEP(
- hash,
- rand.Reader,
- pub_key,
- msg,
- label)
- if err != nil {
- log.Fatalf("could not encrypt message %s", err)
- }
- fmt.Printf("message encrypted: \n%x\n", cipher_text)
- plain_text, err := rsa.DecryptOAEP(
- hash,
- rand.Reader,
- key_pk,
- cipher_text,
- label)
- if err != nil {
- log.Fatalf("could not decrypt message %s", err)
- }
- fmt.Printf("message decrypted: \n%s\n", plain_text)
- pem := ExportPrivKeyAsPEM(key_pk)
- fmt.Printf("PEM Priv Key \n%s\n", pem)
- ParsePrivKeyFromPEM(pem)
- }
- func ExportPrivKeyAsPEM(privKey *rsa.PrivateKey) string {
- privkey_bytes := x509.MarshalPKCS1PrivateKey(privKey)
- privkey_pem := pem.EncodeToMemory(
- &pem.Block{
- Type: "RSA PRIVATE KEY",
- Bytes: privkey_bytes,
- },
- )
- return string(privkey_pem)
- }
- func ParsePrivKeyFromPEM(pemKey string) (*rsa.PrivateKey, error) {
- block, _ := pem.Decode([]byte(pemKey))
- if block == nil {
- return nil, fmt.Errorf("could not read pem string")
- }
- priv, err := x509.ParsePKCS1PrivateKey(block.Bytes)
- if err != nil {
- return nil, err
- }
- return priv, nil
- }
|