Openssl/Rsa - Using a Public Key to Decrypt

openssl/RSA - Using a Public key to decrypt

Let's assume you have generated a public and private RSA key using openssl genrsa:

$ openssl genrsa -out mykey
Generating RSA private key, 512 bit long modulus
...++++++++++++
..........++++++++++++
e is 65537 (0x10001)
$ openssl rsa -in mykey -pubout -out mykey.pub
writing RSA key

You can sign something with the private key like this:

$ md5sum myfile | openssl rsautl -inkey mykey -sign > checksum.signed

You can verify this data using the public key:

$ openssl rsautl -inkey mykey.pub -pubin -in checksum.signed
df713741d8e92b15977ccd6e019730a5 myfile

Is this what you're looking for?

OpenSSL, decrypting with a private key

Here you have the commands you need to encrypt or decrypt using openssl:

Decrypt:

$ openssl rsautl -decrypt -in $ENCRYPTED -out $PLAINTEXT -inkey keys/privkey.pem

Encrypt:

$ openssl rsautl -encrypt -in $PLAINTEXT -out $PLAINTEXT.encrypt -pubin -inkey keys/pubkey.pem

Hope this helps! :)

Decrypt with RSA Public Key

Encryption with the private key and decryption with the public key takes place only in the context of signing/verifying.

In contrast, what is commonly referred to as encryption/decryption (for the purpose of confidentiality) uses the public key for encryption and the private key for decryption.

Note that both processes generally cannot be converted into each other by exchanging the keys, since they use different paddings.

Typically, when verifying, decryption is performed under the hood, only the result of the verification is returned outwards: true or false.

openssl_public_decrypt(), however, supports a low level verification that explicitly allows decryption. If this is executed the resulting plaintext is:

op3f1libgh.biz:3005980741:1622505600

The corresponding PHP code is:

$publicKey = "-----BEGIN PUBLIC KEY-----
MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDmnUhgRhvcf39f1OincMXxs6ko
+QXMuGmaSr++7jeMWHUuR1phLm+UY5wL7Ssm7qVm9wFFsDe1DyDvtkfr+oaxfhod
mqXLPSPRu1RAYk6ItgegYmdy8uvJI9aI3po7axvoP/wpMP6LBElsHklmOJyRSmuU
Cc09/RK1GYpthTw5rwIDAQAB
-----END PUBLIC KEY-----";

$signature = base64_decode("P999MR0e//emIov0Z2qtoKKKhFtb1F6l+zMxn9a3q2p18ZWeaTyPXMAlXDAQI3bz6pxmeQzGCuz1P1ms25AiPKGuqhZ+etJXVnjy9Ir4zc2UU3jyeFZhs7UEfGAcZut5LY9dt5tCJKhPhYwbz4s2ZixBVUWPbFDuODCJIi4L3fw=");

openssl_public_decrypt($signature, $decrypted, $publicKey, OPENSSL_PKCS1_PADDING);
print($decrypted) . PHP_EOL; // op3f1libgh.biz:3005980741:1622505600

Note that you specified the public key in PKCS#1 format and I converted it to X.509/SPKI format for the PHP code using openssl:

openssl rsa -pubout -RSAPublicKey_in -in <path to pkcs#1 public key> -out <path to x.509/spki public key>

Openssl decryption using a public key

Public keys cannot be used to decrypt, they can only be used to encrypt and to verify the encryption signature.



Related Topics



Leave a reply



Submit