1
votes

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
}
1
Does the input have to be PEM encoded? The DER data should be much shorter. If all else fails you can always encrypt symmetrically and wrap the symmetric key. - Peter
Is there a reason you can't just split the key into 2048 byte chunks and encrypt each? I guess the better question is, what do you gain from encrypting the client's secret key? You should never be sending the client's secret key to the server. - Jesse
No, the input is DER data. > "always encrypt symmetrically and wrap the symmetric key" I agree, maybe it's a good idea. - Nick M
@user2896976 Thanks, > "Is there a reason you can't just split the key into 2048 byte chunks and encrypt each" No there's not. I thought about it, just searched a simpler way. - Nick M
encrypt client-private-key with RSA-2048 server-public-key This is almost certainly a mistake, misunderstanding, or both. - President James K. Polk

1 Answers

0
votes

If you want to encrypt something larger than the key size then you can simply use hybrid encryption. You first encrypt (or wrap, if a specific wrapping operation is available) the encoding of the private key using a random AES key, e.g. using AES-CBC or AES-CTR (with an all zero IV). Then you encrypt that AES key using the private key. The ciphertext consists of the encrypted AES key followed by the encrypted data - in this case an RSA private key.

Note however that a private key should really be managed by one entity. It is not called a private key for nothing. Distributing private keys is generally considered bad key management practice.