Home > Software engineering >  Encrypt the message with the key
Encrypt the message with the key

Time:01-01

I need to use a public key to encrypt the message "Message" and save it as a file ciphertext.txt by converting pre-received data in HEX encoding. I do not need the public key to be generated, I already have a ready-made public key. Using this public key, you need to encrypt the message. Here's what I was able to do:

package main

import (
"crypto/rand" 
"crypto/rsa"
"crypto/sha256" 
"crypto/x509" 
"encoding/pem" 
"errors"
"log"
"os"
)

func main() {
publicKeyBytes, err := os.ReadFile("publicik.key")
if err!= nil {
    return
} 
publicKey, err := decodepublicKey(publicKeyBytes)
if  err != nil {
    return
}
plaintext := []byte("Message")
ciphertext, err := rsa.EncryptOAEP(sha256.New(), rand.Reader, publicKey, plaintext, nil)
if err != nil {
    return
}
log.Printf( "%x", ciphertext)

privateKeyBytes, err := os.ReadFile("private.key")
if err != nil {
    return
}
privateKey, err := decodePrivateKey(privateKeyBytes)
if err != nil {
    return  
}
decryptedtext, err := rsa.DecryptOAEP(sha256.New(), rand.Reader, privateKey,ciphertext, nil)
if  err != nil {
    return
}
log.Printf("%s", decryptedtext)
}

func decodepublicKey(key []byte) (*rsa.PublicKey, error) {
    block, _:= pem.Decode(key) 
    if block == nil {
    return nil, errors.New("can't decode pem block")
    }
    publicKey, err := x509.ParsePKCS1PublicKey(block.Bytes) 
    if err != nil {
    return nil, err
    }
    return publicKey, nil
    }

func decodePrivateKey(key []byte) (*rsa.PrivateKey,error) { block, _ := pem.Decode(key)
    if block ==  nil {
    return nil, errors.New("can't decode pem block")
    }
    privateKey, err := x509.ParsePKCS1PrivateKey(block.Bytes) 
    if err != nil {
    return nil, err
    }
    return privateKey, nil
}

Then I don’t know how to solve this problem? Please help with solving this problem

CodePudding user response:

I debugged your code and found 2 potential issues:

  1. Double check whether you need to use x509.ParsePKCS1PublicKey() or x509.ParsePKIXPublicKey(). This depends on the format of your public key. More here: https://stackoverflow.com/a/54775627/9698467
  2. You may need to type assert the public key in your decodepublicKey function: return publicKey.(*rsa.PublicKey), nil.
  •  Tags:  
  • go
  • Related