[erlang-questions] Private key encryption

Marcus Nilsson tandy.nilsson@REDACTED
Tue Apr 14 15:54:27 CEST 2015

Thanks for the reply Martin and helping me with this.

The reason for doing this is that I want to share the files with a few people.
After getting a better understanding of how this works I changed the
my approach to this.

1. A shared secret is generated in the following form [Key, IV]
2. This secret is then used to encrypt the binary with aes_cfb128 a
symmetric block encryption algo
3. The secret is then encrypted with the private key with RSA a
asymmetric encryption algo
4. Both the encrypted shared secret and content is concatenated in the
output file like this <<SharedSecretLength, EncryptedSecret,


1. Extract the encrypted secret from the file
2. Decrypt the shared secret with the public key with RSA
3. Decrypt the encrypted content with the now decrypted secret with
aes_cfb128 algo

The following snippet seems to do the job

    Key = crypto:rand_bytes(16),
    IV = crypto:rand_bytes(16),
    EncryptedContent = crypto:block_encrypt(aes_cfb128, Key, IV, Input),
    EncryptedKey = public_key:encrypt_private(list_to_binary([Key,
IV]), PrivKey),
    [integer_to_binary(byte_size(EncryptedKey)), EncryptedKey,


2015-04-14 0:54 GMT+02:00 Martin Karlsson <martink@REDACTED>:
> Hi Marcus,
> The encrypt_private is doing an RSA encryption using PKCS1 padding by
> default.
> RSA can't encrypt large payloads (i.e. 256 bytes - 11 for padding for 2048
> bit RSA keys) so this is the likely reason you can only encrypt small
> portions of the file.
> Normally you use public key crypto to encrypt a symmetrical key and then
> encrypt the large payload with the symmetric key using AES or something.
> In addition you don't want to encrypt using the private key but rather the
> public key, otherwise anyone with access to your public key can decrypt the
> cipher. Private key encryption is usually only used for signatures.
> Crypto is hard to get right, especially if you are only working with RSA
> primitives (you need to think about padding, hashing, MDCs, signatures). You
> might want to have a look a NaCl (https://github.com/jloius/enacl for a
> binding to erlang) which is much friendlier to use.
> Cheers,
> Martin
> On Tuesday, 14 April 2015, Marcus Nilsson <tandy.nilsson@REDACTED> wrote:
>> I'am trying to encrypt a bigger file with the public_key module.
>> Everything works fine as long as the content of the file is small.
>> But when the size of the binary exceed's a certain size I get a
>> **error:encrypt_failed. I guess this has to do with the padding parameter.
>> But I have not been able to find any documentation how to compute the
>> padding to get this working any help would be very welcomed!
>> I use this code to perform the encryption
>> public_key:encrypt_private(Input, PrivKey);
>> /Marcus

More information about the erlang-questions mailing list