`public_decrypt': padding check failed (OpenSSL::PKey::RSAError) - ruby

Im trying to decrypt using a public key.
bob = TCPSocket.open(host, port)
cs_public_key = OpenSSL::PKey::RSA.new File.read 'c_public_key.pem'
puts "Alice is connected to bob"
bobs_public_key = ""
while line = bob.gets # Read lines from socket
bobs_public_key = bobs_public_key + line # and build them
end
bobs_public_key = JSON.parse(bobs_public_key)
puts "Alice recieved Bob's Public Key:"
puts bobs_public_key["key"]
#Error is on this line.
decypted = cs_public_key.public_decrypt(Base64.decode64(bobs_public_key["digest"]))
puts decypted
and am getting the error: 'public_decrypt': padding check failed (OpenSSL::PKey::RSAError)
Can someone explain what this error means and how to avoid it?

I ran into this error recently and tracked it down the the padding algorithm used, OpenSSL::PKey::RSA is defaulting to RSA_PKCS1_PADDING, but the message was generated in another system that defaulted to using the perfered RSA_PKCS1_OAEP_PADDING. The public/private encrypt/decrypt methods all take an optional second argument to set the padding, and this fixed the issue for me.
rsa.private_decrypt encrypted_text, OpenSSL::PKey::RSA::PKCS1_OAEP_PADDING

Turns out I was encrypting the digest using the wrong private key, so that public key was unable to decrypt it and threw that error.

Please make sure that the data you are trying to decrypt with Public key should be encrypted data. From the code, it looks like you are passing plain text instead of encrypted data.
Make sure that bobs_public_key["digest"] is encrypted. Generally it is signature of the data which is encrypted and that is to be passed. Check if your data has signature.
You are getting padding error because in RSA encryption, data is treated as a big number whatever is there in binary and then its power is raised and there is some padding. For plain text or slightly modified data, that padding check may fail.

I recently faced this padding issue while trying to decrypt the key using openssl command.
openssl rsautl -decrypt -in key_raw -inkey SIT_private.pem
RSA operation error
16764:error:0407109F:rsa routines:RSA_padding_check_PKCS1_type_2:pkcs decoding error:../openssl-1.1.1k/crypto/rsa/rsa_pk1.c:251:
16764:error:04065072:rsa routines:rsa_ossl_private_decrypt:padding check failed:../openssl-1.1.1k/crypto/rsa/rsa_ossl.c:491:
In my case using -oaep option solved the problem.
openssl rsautl -decrypt -in key_raw -inkey SIT_private.pem -oaep

Related

How do I decrypt files that are encrypted using des command in Ruby?

I need to decrypt files that are encrypted with this command:
des -E -u -k "some key" file.in file.out.enc
The decryption code in Ruby:
def decrypt(key)
cipher = OpenSSL::Cipher.new(‘des’).decrypt
cipher.key = key
File.open(‘file.out’, ‘wb’) do |outf|
decrypted = cipher.update(File.read(‘file.in.enc’)) + cipher.final
outf.write(decrypted)
end
end
I’m getting wrong final block length error when I run the code above. I also tried decrypting using the openssl command line tool and got a bad magic number error. Any advice?
Try switching the mode, from CBC to ECB for instance with OpenSSL::Cipher.new('DES-ECB').
If you check which ciphers your Ruby installation supports by looking at OpenSSL::Cipher.ciphers, you'll find a list of available modes too.

Generate OpenSSL subject_name hash in ruby

I've investigated 30261296 however I'm still at a loss to find a way to generate the same results in Ruby with the openssl and/or digest gems. The OpenSSL output I'm trying to replicate in ruby is as follows:
$ openssl x509 -noout -subject_hash -in DigiCertSHA2SecureServerCA.pem
85cf5865
In reading many things, I believe this hash is generated from the Subject: portion of the certificate, which is like the distinguished name. In this certificates case something to the effect of:
$ openssl x509 -noout -subject -in DigiCertSHA2SecureServerCA.crt
subject=C = US, O = DigiCert Inc, CN = DigiCert SHA2 Secure Server CA
Attempting to SHA-1 encode that on the command line or in Ruby (which represents this as /C=US,/O=DigiCert Inc/CN=DigiCert SHA2 Secure Server CA when using the openssl gem) has not yeilded the same has results displayed by OpenSSL.
I'm trying to do this more natively in Ruby to avoid shelling out to openssl if possible since openssl and digest come along with the ruby env. In the end I need this to generate the hash directory tree ... i.e. 85cf5865.0 (hash + '.0').
The CA I'm hasing is DigiCertSHA2SecureServerCA.crt - DER encoded. I converted DER to PEM because openssl command line uses that without the additional -inform der switch. It doesn't appear to matter to Ruby's openssl gem.
This turns out to be pretty straightforward, since Ruby’s OpenSSL bindings includes the OpenSSL::X509::Name#hash method, which is exactly what we want.
require 'openssl'
# Read the certificate.
cert = OpenSSL::X509::Certificate.new(File.binread("DigiCertSHA2SecureServerCA.crt"))
# Get the subject, which is an OpenSSL::X509::Name object.
name = cert.subject
# hash returns an integer, we want the hex string so call to_s(16).
puts name.hash.to_s(16) #=> 85cf5865
The integer will be positive since OpenSSL returns an unsigned int, so we can just use to_s(16) and don’t need to worry about converting negative values.

OpenSSL key length too short in Ruby, not in Bash

I originally experimented with a simple encryption script in Bash and it worked pretty much as expected. However, I'm now trying to do the same thing in Ruby and the Ruby version seems function a little differently.
Bash
Encrypt
echo 'hello' | openssl enc -aes-256-cbc -a
Password: mypass
Result: U2FsdGVkX19rERfOXiKs97FgwIkLy3+ttZzaHkEoQyE=
Decrypt
echo 'U2FsdGVkX19rERfOXiKs97FgwIkLy3+ttZzaHkEoQyE=' | openssl aes-256-cbc -d -a
Password: mypass
Result: hello
Ruby
require "openssl"
require 'base64'
cipher = OpenSSL::Cipher.new('AES-256-CBC').encrypt
cipher.key = 'mypass'
This is what I've attempted in Ruby so far but I receive a OpenSSL::Cipher::CipherError: key length too short error. I would like to mimic Bash as much as possible.
OpenSSL uses a (largely undocumented) password based key derivation function (PBKDF) called EVP_BytesToKey using an 8 byte salt and an iteration count of 1. A magic and salt of 8 bytes each are prefixed to the ciphertext (check the first bytes of the result to see the magic).
Obviously "mypass" cannot be a correct key for AES. AES keys are 16, 24 or 32 byte binary values for the 128, 192 and 256 key sizes. You can however specify a key directly using the -K switch on the command line to make the code compatible with the Ruby Cipher object. In that case you need to specify the key using binary (a file) or hexadecimals for the openssl command line and in Ruby. You would also need to specify an IV.
Alternatively you would have to find an EVP_BytesToKey implementation for Ruby, but note that this is an old OpenSSL specific function with a completely insecure iteration count.

Invalid OpenSSH key format when importing an ec2 key form an existing one

I am using the ruby EC2 SDK, Version 2. The private key material of a key generated with EC2 is stored in a string. I am trying to generate the public key material that is necessary to import the key into EC2 using OpenSSL::PKey::RSA
After that I am trying to import the key pair.
It looks like this:
kk=OpenSSL::PKey::RSA.new my_private_key_material
pub=kk.public_key
ec2.import_key_pair({key_name: "my_key", public_key_material: pub.export})
The API is throwing this error:
*** Aws::EC2::Errors::InvalidKeyFormat Exception: Key is not in valid OpenSSH public key format
I am not sure what is wrong and how to generate the public key material correctly. I already tried to Base64 encode the public key string without success.
Edit
I tried a couple of new things.
I generated a new key using the EC2 web console from scratch and then geneerated the public one the way Raphael points out below with
openssl rsa -in mykey.pem -outform PEM -pubout -out mykey.pub
The key is not encrypted.
Whey trying to import the public key, either with the web console or by code, I get the same error.
Edit 2
I found this.
When generating the public key with a different command, it works:
ssh-keygen -y
The generated public key looks different. It starts with
ssh-rsa AAAAB3NzaC1yc2EAAAADA....
While the first generated one starts with
-----BEGIN PUBLIC KEY-----
MIIBIjANBgkqhkiG....
Now the question is how to generate the first format in ruby. I also found this post on different formats.
OK, I solved it by following this post.
It turned out the public key had to be generated in a different way
kk=OpenSSL::PKey::RSA.new my_private_key_material
key=kk.public_key
type = key.ssh_type
data = [ key.to_blob ].pack('m0')
openssh_format = "#{type} #{data}"
ec2.import_key_pair({key_name: "my_key", public_key_material: openssh_format})
The documentation suggests that key contents must be encoded in Base64 client-side, however this is not the case: The SSH key contents should be provided as-is, in the format "ssh-rsa XXXXX....".
Rory is right. In NodeJS below code worked.
let keypair = fs.readFileSync(homedir + '/.ssh/id_rsa.pub');
result = await ec2.importKeyPair({
KeyName: 'KeyPairName',
PublicKeyMaterial: keypair,
}).promise();
I m using Ruby SDK V3 and this is work for me to import key to AWS
#!/usr/bin/env ruby
require 'rubygems'
require 'aws-sdk-ec2'
key_content = File.read('/home/xxx/keys/sshkey.pub')
ec2_client = Aws::EC2::Client.new()
resp = ec2_client.import_key_pair({
dry_run: false,
key_name: "test-ruby-key",
public_key_material: key_content,
})
Hope it helpful!

Extract multiple keys from one .p12 file using OpenSSL ruby

I am wondering how to extract keys from an Apple .p12 file. From my limited understanding, a .p12 file is a combination of X504 certificates and private keys.
I am seeing that every .p12 file I run into has a X504 certificate and at least one key, and in some situations two keys. This is due to the fact that every .p12 has an Apple developer key, and some have an extra key (possibly an Apple root authorization key). I am considering only those .p12 files with two keys as valid. My goal here is to differentiate between those .p12 files that have one key and those that have two.
So far I have used OpenSSL to be able to inspect X504 files and the keys of any .p12. For example I have this code that does the inspections for all .p12 files in a directory:
Dir.glob('*.p12').each do |p|
file = File.read(p)
p12 = OpenSSL::PKCS12.new(file, "")
# note that this new certificate is in an X509 format
cert = p12.certificate
puts p12.inspect()
puts cert.inspect()
end
This is my output:
#<OpenSSL::PKCS12:0x007fcf33018920>
#<OpenSSL::X509::Certificate subject=/UID=FFBMT4K5/CN=iPhone Distribution: A.H. Belo Management Services, Inc./OU=FFBMT4K5/O=FFBMT4K5/C=US, issuer=/C=US/O=Apple Inc./OU=Apple Worldwide Developer Relations/CN=Apple Worldwide Developer Relations Certification Authority, serial=36597980220620, not_before=2012-01-11 16:30:22 UTC, not_after=2013-01-10 16:30:22 UTC>
Now my problem is getting keys. If I do something like this:
puts p12.key
I get a long string on encrypted data like this:
-----BEGIN RSA PRIVATE KEY-----
MIIEowIBAAKCAQEA4Pet7CZrPr4x/SKjMwy5avXmcguzQlix/vBq+qq7aKQhctKr
d5HE7wk4jWbDGj7Rf9ckeFFMktTTbKYmnKCywCct/uJmgavFl1+t45DIQL2V1JMU
JSXvtjDXoKFweKQgdiha5mBNL70+ivqxMzJJw19E+MhFoZ6tFOgQ5gPLcDLR5WTU
ezxH9RbXGWbq+CMBjJ+lw8/Ako7IOm+d95ZTM6u333qp0dsn+1/I/zGeWE1gJXIl
8mIkvrp7+BDTvXHYALADwXnXijqvd/bANfetsDQ+gxRnc06dFt114JUuptcXGwbg
//ykDzNYhuibQD1Z65KfTB/ntQ1aE5FtHEXirwIDAQABAoIBACNCrt/0pZqP9QXY
B/xYYjeBkz0M2GvtuvhadmoTmIwuLY/xtS5oipVsvJBtKudSMUP4VJ8HHxlkgj7l
S+gAyAOWIH9yvN5WLgIr3PVuG/UJwhIve1jXOVs1DJcAtsAx+WSLrrOtJGv3HXZr
FJsRpr4YkJbtzPwoArjkJsHmllxfT2zeQPMJy+RQ/qlHUqsude/ahC0I3RiW3SgB
EKTNM1vGTEkox8bUUhHqNY3ERlihFpZC2wSkroETDY3RkSjuPkNy7uT/b66a/qjj
qaIA0YLhNOYGdN2llJN5GJjYYVKakpiipqcHCFrV1+JtbFB2tKhqAvK6fjCZcSFF
fW58owECgYEA/g8FvAPcejPR3O8E1ydNWChhd9UZQUeQNCET+lY3Dxwklk+u1140
yw/u2hUoNdJLfev1HtlYruglD9jW/LGoLaPodQfcHcaCSfdJa1mmKfSieApOe15+
ijO3WpZK/MJUTteGVMW/B/QnxPBGtsDo6q2v2YxA7fOhzmImn5hgxlsCgYEA4q/A
DBKe1WDZPUyG3R/Cfl5AEqEHly6VkCPFF+uYFZzep/SN/ez34r7fmcfl0RL7H9kn
Q4WBaCMbCgG9dErORW99usoBsjys5pojstNJDZwACUg9rPnV/+uUqMyocjeN0Vrl
2Vg0dC8HH1hLZPLkp+MAy2nNzmnnHcTKiTqsDT0CgYEApVzfzaXxvvS1t4k37Fbf
h+8YqefhfVT4LoYNO9ccFVCrG88XrYTa9gUT4Yz91DJiAr8vl/m+OHJPlUX9gRKd
tb9HEc2g3xyTN1OmzSHX/t0FVv7WYIR79rZ8tJC4lFZki8DK5aikk6e+rvf5/wAH
WqDcocwhgwAeJHhMTXrgGpsCgYBGYqWx2fJBdNHfK6zQafUdAazJXACcW5WK7OBc
vgU56Lxl0BRqnLKXUAbjm+Lq2Qbqa6W6XHDC4euaXtHxkuybOLQEVIbUTeytqXye
IOaU+DQ2rZyg4e4liYNeKjW/SSqar6ugobefv55piCPY02ZWDrEHd/G0PsPJRXpR
w8r6TQKBgFMoEZKywokRIbMCUHHRR3TVeizBMhbNUUmOiRhzsHZPJ2V63PNp3L1c
0NsRo62mbekXDRH8J0C8fLG4R64Y7+rHBQo0tBpgYepPU0NCrsojF7brtYYb3VqI
baVEPRhIy2tJylDad6M36DeOCIhvXalh8GaV/HhEr4lxykth+mGH
-----END RSA PRIVATE KEY-----
My question is how can I determine whether this certificate has more than one key, and also how I can inspect the keys for information. If what I am asking or my understanding of this issue is fundamentally flawed, please let me know. This is my first time being exposed to certificates and any information will be greatly helpful. Any points in the right direction will be appreciated, thanks in advance.
EDIT:
Using OpenSSL I can view the two shrouded keybags of a .p12. Example:
openssl pkcs12 -in some_p12.p12 -info -noout
output:
Enter Import Password:
MAC Iteration 1
MAC verified OK
PKCS7 Encrypted data: pbeWithSHA1And40BitRC2-CBC, Iteration 2048
Certificate bag
Certificate bag
PKCS7 Data
Shrouded Keybag: pbeWithSHA1And3-KeyTripleDES-CBC, Iteration 2048
Shrouded Keybag: pbeWithSHA1And3-KeyTripleDES-CBC, Iteration 2048
So I'm looking for a couple things. Generally speaking, what exactly are these keybags? And also, how can I inspect them/determine how many I have per .p12 file using Ruby. Thanks.
I'm quite late for this one but it also interested me. I've tested creating a p12 file using two of my digital certificates (one expiring in 2023 and the other one in 2027) and this is was the openssl output:
$ openssl pkcs12 -in some_p12.p12 -info -noout
Enter Import Password:
MAC Iteration 1
MAC verified OK
PKCS7 Encrypted data: pbeWithSHA1And40BitRC2-CBC, Iteration 2048
Certificate bag
Certificate bag
PKCS7 Data
Shrouded Keybag: pbeWithSHA1And3-KeyTripleDES-CBC, Iteration 2048
Shrouded Keybag: pbeWithSHA1And3-KeyTripleDES-CBC, Iteration 2048*
When parsing it in ruby using OpenSSL::PKCS12 I noticed one of the certificates could be read from the in ca_certs array and the other from the certificate method:
p12 = OpenSSL::PKCS12.new(file, "1234")
p12.certificate # => The latest one with the further expiry date (2027)
p12.key # => The private key from the certificate
p12.ca_certs # => Array, with the other certificate (expiring in 2023)
p12.ca_certs.count #=> 1
I could read the private key from the certificate using key as usual, however I could not find a way to read the key corresponding the certificate from ca_certs
A .p12 contains only 1 private key, and contains 1 or more public keys. The public keys are the ones that make the chain of trust.
.p12 is a binary format. To convert it and extract to individual certificates, look for example here. The link contains all the openssl commands you need.

Resources