I need to encrypt client-private-key with RSA-2048 server-public-key. I know that private key is obviously longer than the public key and I'm not sure if it's possible... but I saw a similar task was done in Python, so I want to know your opinion.
/* main */
clientPrivateKey, _ := generateRsaPair(2048)
_, serverPublicKey := generateRsaPair(2048)
clientPrivateKeyAsByte := privateKeyToBytes(clientPrivateKey)
encryptWithPublicKey(clientPrivateKeyAsByte, serverPublicKey)
Fatal error crypto/rsa: message too long for RSA public key size
/* Functions */
func generateRsaPair(bits int) (*rsa.PrivateKey, *rsa.PublicKey) {
privkey, err := rsa.GenerateKey(rand.Reader, bits)
if err != nil {
log.Error(err)
}
return privkey, &privkey.PublicKey
}
func encryptWithPublicKey(msg []byte, pub *rsa.PublicKey) []byte {
hash := sha512.New()
ciphertext, err := rsa.EncryptOAEP(hash, rand.Reader, pub, msg, nil)
checkError(err)
return ciphertext
}
func privateKeyToBytes(priv *rsa.PrivateKey) []byte {
privBytes := pem.EncodeToMemory(
&pem.Block{
Type: "RSA PRIVATE KEY",
Bytes: x509.MarshalPKCS1PrivateKey(priv),
},
)
return privBytes
}