This article will explain how to encrypt and decrypt data with RSA algorithm using PKCS#1 v1.5 padding scheme.
It is based from RFC 2313
code: https://github.com/fi1ingcabinet/cryptico_rsa_enc_dec_single-block
Pre-requisites
cryptico js library for generating RSA key in javascript
Complete html/js example
How to use it:
- clone the github repo
- open the file in windows explorer/mac finder
- Open the file “test_rsa2.html” in browser
This is the html code:
HTML |
---|
Creating an RSA key
OpenSSL | HTML/JS |
---|---|
OpenSSL creates a key file and saves it to the hard drive using random generation in the hardware using random input from system
HTML – I’m using the cryptico library. This generates a key using an input seed of your choice so is deterministic (the same seed always produces the same output). The key size is selected in
The public and private keys are displayed in PEM format and prints some html elements to display them
add_pem_html – adds PEM header and footer (with <br>’s)
split64_html – adds a <br> every 64 characters
base16tobase64 – converts the key from hex to base64
RSAKeyOut – the key in hex format
Encrypt/Decrypt some data
OpenSSL | HTML/JS |
---|---|
OpenSSL again creates some output files of encrypted and decrypted files as specified
HTML – Here we encrypt and decrypte twice. First with cryptico library, then with a library I created as test rsa-rfc2313.js
See my test always creates the same ciphertext for the same plaintext (very insecure!!). This is because I used exactly the same padding string each time (121212… etc. upto the required length in rfc).
Test OpenSSL <=> HTML/JS
Now we have created some ciphertext in js with my library lets test it out in OpenSSL to check its working well.
- Copy and paste the private key into a file on your computer
- Copy the ciphertext into a file on your computer
- Use OpenSSL to decrypt the ciphertext
vi priv_key.pem
#add copy paste the private key including the start/end lines and save the file
vi ctext.b64
#copy paste the ciphertext starting U/hAz01Scg+YF+GHED0O+j4yo.... to this file and save
openssl base64 -d -in ctext.b64 -out ciphertext.base64.decode
#convert the file from b64 to binary
openssl rsautl -decrypt -inkey priv_key.pem -in ciphertext.base64.decode -out plaintext.decr.txt
cat plaintext.decr.txt
Hi this is some text to encrypt!
#decrypt using the OpenSSL decrypt function and cat the result to the terminal, this is the text we encrypted! wow :)
Conclusion
The above is probably not a good idea to use for any real purpose you have in real life (indeed RSA encryption should probably not be used at all, see here)
However its nice to see how it is supposed to work, and I will use this in a program I’m writing so its not completely frivolous 😛