How to do RSA encryption and decryption process in the Erlang programming language? how to make key RSA public key and private key? I have tried some sample codes like the below as they were old and not compatible with my Erlang OTP 25 version they were not useful, i.e some packages like rsa_private_encrypt can't be found in Erlang 25 and show errors, And they were for PEM files:
{ok,[Entry]} = public_key:pem_to_der("./test_private_key"),
{ok,{'RSAPrivateKey', 'two-prime', N , E, D, _P, _Q, _E1, _E2, _C, _Other}} = public_key:decode_private_key(Entry),
PlainText = "now is the time for all good men to come to the aid of their country",
PrivKey = [crypto:mpint(E), crypto:mpint(N), crypto:mpint(D)] ,
PubKey = [crypto:mpint(E), crypto:mpint(N)],
Foo = crypto:rsa_private_encrypt(PlainText,PrivKey,rsa_pkcs1_padding),
Bar = crypto:rsa_public_decrypt(Foo,PubKey,rsa_pkcs1_padding),
PlainText == binary_to_list(Bar).
OR
PrvKey = [257, 77181119504409699204797322144340611322502523292227043692039327666381749008487, 77131657261414365158890407156927969457179535804176721705182844017912686753873],
PubKey = [257, 77181119504409699204797322144340611322502523292227043692039327666381749008487],
Enc = crypto:rsa_private_encrypt("hello", PrvKey, rsa_pkcs1_padding),
Dec = crypto:rsa_public_decrypt(Enc,PubKey,rsa_pkcs1_padding),
B64 = base64:encode_to_string(Enc),
While reading documentation and helping from previous codes, Now gladly it works:
Declare your plaintext or message:
Msg = "Hello World",
Then generate your public and private keys:
{PublicKey, PrivateKey} = crypto:generate_key(rsa, {2048,65537}),
Make your encrypted message with the public key:
RsaEncryptedCrypto = crypto:public_encrypt(rsa,list_to_binary(Msg),PublicKey,rsa_pkcs1_padding),
Now you can decrypt your encrypted message:
RsaDecryptedCrypto = crypto:private_decrypt(rsa,RsaEncryptedCrypto,PrivateKey,rsa_pkcs1_padding),
Note: We use list_to_binary to change our plaintext to binary as the method wants that argument Now we change the decrypted binary back to string:
R = binary_to_list(RsaDecryptedCrypto)
we print the output:
io:format("~s~n",[R]).
All the codes:
Msg = "Hello World",
{PublicKey, PrivateKey} = crypto:generate_key(rsa, {2048,65537}),
RsaEncryptedCrypto = crypto:public_encrypt(rsa,list_to_binary(Msg),PublicKey,rsa_pkcs1_padding),
RsaDecryptedCrypto = crypto:private_decrypt(rsa,RsaEncryptedCrypto,PrivateKey,rsa_pkcs1_padding),
R = binary_to_list(RsaDecryptedCrypto),
io:format("~s~n",[R]).
Document: https://www.erlang.org/doc/man/crypto.html#public_encrypt-4