Generating encrypted private key file with git-bash - snowflake-cloud-data-platform

I am trying to generate a encrytpted private/public key using the code example given here
https://docs.snowflake.com/en/user-guide/key-pair-auth.html
$ openssl genrsa 2048 | openssl pkcs8 -topk8 -inform PEM -out rsa_key.p8
however it just generates an empty file. Is there something I'm missing perhaps?
Any tips would be appreciated

Related

sign and verify using openssl library functions instead of command line utilities

I am currently framing the openssl commands as a string and using linux system call int system(const char *command); for signing and verifying certain files.
For generating sha i use below command.
openssl dgst -sha256 > test_sha256.txt
After generating test_sha256.txt, i will sign this with my CA , which gives me signature.p7s, from which i extract CRLs(asn1parse -inform DER and dd ) and combining CRLs with my root CA, then i verify using below command.
openssl cms -verify -inform DER -in signature.p7s -binary -content test_sha256.txt -CAfile combined_CA.pem -purpose any -signer signer_file.crt
How can we achieve the same thing using the openssl library calls? Do we have separate openssl functions to achieve sign & verify.

Password callback for reading public key with OpenSSL API

When using public key cryptography, it is often customary to store private keys in an encrypted format, since they are of course supposed to be a secret. This is reflected in the OpenSSL C API, which provides functions like PEM_write_PrivateKey, which takes as function arguments an optional cipher to use to encrypt the key (like AES). Then, when reading the encrypted key back in from disk, the OpenSSL API provides functions like PEM_read_PrivateKey, which allows the user to provide a function pointer used as a callback so the application can provide OpenSSL with the password for the encrypted key.
But what confuses me is that the OpenSSL API also seems to let the user provide a password callback when reading in a Public key. For example, one API function signature for reading in a public key is:
EVP_PKEY *PEM_read_PUBKEY(FILE *fp, EVP_PKEY **x,
pem_password_cb *cb, void *u);
So what is the purpose of providing a password callback when reading in a public key? AFAIK it makes no sense to encrypt a public key, since a public key is by definition supposed to be available to the general public. So why does the OpenSSL API have a function parameter here that takes a password callback?
As mentioned in this comment, any PEM-encoded data can be encrypted. Message encryption for privacy-enhanced mail (PEM) is defined in RFC 1421 and in the context of your question, it is interesting to look at the example message in
section 4.6 Summary of Encapsulated Header Fields
-----BEGIN PRIVACY-ENHANCED MESSAGE-----
Proc-Type: 4,ENCRYPTED
Content-Domain: RFC822
DEK-Info: DES-CBC,F8143EDE5960C597
Originator-ID-Symmetric: linn#zendia.enet.dec.com,,
Recipient-ID-Symmetric: linn#zendia.enet.dec.com,ptf-kmc,3
Key-Info: DES-ECB,RSA-MD2,9FD3AAD2F2691B9A,
B70665BB9BF7CBCDA60195DB94F727D3
Recipient-ID-Symmetric: pem-dev#tis.com,ptf-kmc,4
Key-Info: DES-ECB,RSA-MD2,161A3F75DC82EF26,
E2EF532C65CBCFF79F83A2658132DB47
LLrHB0eJzyhP+/fSStdW8okeEnv47jxe7SJ/iN72ohNcUk2jHEUSoH1nvNSIWL9M
8tEjmF/zxB+bATMtPjCUWbz8Lr9wloXIkjHUlBLpvXR0UrUzYbkNpk0agV2IzUpk
J6UiRRGcDSvzrsoK+oNvqu6z7Xs5Xfz5rDqUcMlK1Z6720dcBWGGsDLpTpSCnpot
dXd/H5LMDWnonNvPCwQUHt==
-----END PRIVACY-ENHANCED MESSAGE-----
Looking at the 1.1 branch of OpenSSL it has a function PEM_read_bio() that supports reading such a message and splitting it into its name (as given in the top line), header (the name-value pairs below that) and data (the base64-encoded stuff):
int PEM_read_bio(BIO *in, char **name, char **header,
unsigned char **data, long *len);
All OpenSSL PEM_read_XYZ() functions at some point invoke it, from PEM_bytes_read_bio(), because they are all implemented in the same way by means of macro expansions. That function contains the following calls:
PEM_read_bio(bp, &nm, &header, &data, &len)
to split the message, then
PEM_get_EVP_CIPHER_INFO(header, &cipher);
to figure out which type of encryption information is found in the header of that message and fill an EVP_CIPHER_INFO object with it, and then
PEM_do_header(&cipher, data, &len, cb, u);
to do the decryption of the data based on the cipher information found -- again if needed. Note the cb parameter which stands for callback, a mechanism to get input for any passphrase if needed.
Now what might be confusing, is that certain private key formats, like for example PKCS#8, also have their own mechanism of storing encryption information independent of the PEM encoding. Technically speaking, it should be possible to apply encryption to such keys twice: once at the PEM level and once at the PKCS#8 level. The OpenSSL tools for generating or converting to PKCS#8 formatted keys do not seem to offer that option though. Also, none of the tools seem to expose the option of encrypting any generated public key PEM files, unless a private key is included as well.
You can check some of the outputs to see if they match my story. First, generating an RSA key pair to a PKCS#1 format, nothing encrypted:
$ openssl genrsa
Generating RSA private key, 2048 bit long modulus (2 primes)
.................+++++
............+++++
e is 65537 (0x010001)
-----BEGIN RSA PRIVATE KEY-----
MIIEpQIBAAKCAQEAlcnR/w7zPoLrhuqFvcfz5fn8DFb0fEcCKOKSj+x+JJxGth9P
rJbxkt4pRXxbMIL0fX59HN5bRvQh2g59l/kfr30kCOnclap9nRrohWyg2i7720Cw
<truncated>
Then the same command, but using encryption, which happens at the PEM level, as you can see in the headers:
$ openssl genrsa -des3
Generating RSA private key, 2048 bit long modulus (2 primes)
.....................+++++
....................+++++
e is 65537 (0x010001)
Enter pass phrase:
Verifying - Enter pass phrase:
-----BEGIN RSA PRIVATE KEY-----
Proc-Type: 4,ENCRYPTED
DEK-Info: DES-EDE3-CBC,D90861647707F687
DIupLghCjcvpLenqAAULaJj1EDvUUfc2Xc58YVh7rMTSVgLwZ+9CtnUQJcup4aUQ
a1EdGXTadwBQB2jTtiFJbH67/5D26PHXPnM+YN2rnoReOExVS7hKu3DTq7c4j6a3
<truncated>
Finally generating a similar key but now to PKCS#8, which has its own encryption and therefore does not get encrypted at the PEM level. You can see that the PEM headers are not there.
$ openssl genpkey -algorithm RSA -des3
.........................................+++++
...........................................................................+++++
Enter PEM pass phrase:
Verifying - Enter PEM pass phrase:
-----BEGIN ENCRYPTED PRIVATE KEY-----
MIIFHDBOBgkqhkiG9w0BBQ0wQTApBgkqhkiG9w0BBQwwHAQIV0Ih4bsI6egCAggA
MAwGCCqGSIb3DQIJBQAwFAYIKoZIhvcNAwcECNOim8HAN8j5BIIEyEe05hHtc8HL
<truncated>
If all my reasoning is correct, then the prompt "Enter PEM pass phrase" is inaccurate since this is not a PEM-level encryption but a PKCS#8-level encryption.

What are bag attributes and how can i generate them?

while converting some certificates from keystore to openssl/pem I noticed for the first time that there are "Bag Attributes" prepended to the certs.
The look like this:
Bag Attributes
friendlyName: CN=PositiveSSL CA,O=Comodo CA Limited,L=Salford,ST=Greater Manchester,C=GB
subject=/C=GB/ST=Greater Manchester/L=Salford/O=Comodo CA Limited/CN=PositiveSSL CA
issuer=/C=US/ST=UT/L=Salt Lake City/O=The USERTRUST Network/OU=http://www.usertrust.com/CN=UTN-USERFirst-Hardware
Do they serve any function?
I noticed that I like them because they make my chain-files (a concatenation of certificates) more clear. Sadly the ca certs I download don't have them.
So how do I generate them?
To be exact, you apparently mean converting (or just reading) with the openssl pkcs12 (import) utility a PKCS#12 file, which can be supported by Java as a keystore but was not the default (update) until Java9 in 2017. PKCS#12 was designed and normally is used for a privatekey and the cert(s) (usually multiple) for that key, although the format is flexible enough to allow lone cert(s). OpenSSL commandline pkcs12 -export requires a privatekey, although it will add "extra" certs, and a program calling the API can apparently do no privatekey. In my experience, Java didn't support lone cert(s) in PKCS#12 before version 8, and in my 8 and 9 has two attributes: pkcs9.friendlyName and 2.16.840.1.113894.746875.1.1 which is apparently an Oracle-defined trustedKeyUsage. Most lone certs are not stored, or downloaded, as PKCS#12.
PKCS#12 is defined in terms of several (slightly different) "bag" structures that contain various things, primarily privatekeys and certs with optional attributes attached that are unsurprisingly called "bag attributes"; your case (apparently) has only cert(s). These attributes follow the now-conventional structure of an arbitrary number of pairs of OID plus value depending on the OID. Note in your display only friendlyName is a bag attribute, indicated because it is indented under the heading.
The subject= and issuer= lines are fields from the cert itself which the openssl pkcs12 (import) utility extracts and prints for convenience. If that is sufficient, you can display them for any cert with the x509 utility; in particular if you want to have them before the PEM-encoded cert "blob" in the way pkcs12 output does, use openssl x509 -in infile -subject -issuer -out outfile. This does one cert, so if you have a chain in a PEM file you need to split it apart and do each cert separately, and possibly combine again afterwards; for example something like
# split into files cert_1, cert_2, etc.
$ awk <chain.pem -va="openssl x509 -subject -issuer >cert_"
'/^-----BEGIN/{b=a (++n);x=1}x{print|b}/^-----END/{close(b);x=0}'
# output entire "bag" to stdout (with blank lines between certs)
$ awk <chain.pem -va="openssl x509 -subject -issuer" \
'/^-----BEGIN/{b=a;x=1}x{print|b}/^-----END/{close(b);x=0;print""}'
As a comparison, openssl s_client -showcerts does something very similar: it outputs subject and issuer with each cert blob from the received chain, labelling them with a level number, "s:" and "i:".

to use RSA_PKCS1_OAEP_PADDING for RSA signature

Previously I was using rsa signature with no padding ,but now I was asked to add PKCS1_OAEP padding ,Initially I tried simple adding this flag "RSA_PKCS1_OAEP_PADDING", but it is giving error code while running like this
error:04066076:rsa routines:RSA_EAY_PRIVATE_ENCRYPT:unknown padding type
Further I googled about the rsa signature with PKCS1_OAEP padding but didn't get anything except it is said that for implementing RSA_PKCS1_OAEP padding you have to use this one
int RSA_padding_add_PKCS1_OAEP(unsigned char *to, int tlen,
unsigned char *f, int fl, unsigned char *p, int pl);
and then do private_encrypt with RSA_NO_padding but still having confusion as they have not explained clearly how to use this padding_add function explictly .can anyone provide help .would really appreciate that .
thanks in advance
According to RFC 3447 OAEP padding scheme can be used only with encryption operation and therefore it cannot be used with signatures. If standard RSASSA-PKCS1-v1_5 scheme is not good enough for you I believe you should use RSASSA-PSS which is recommended for new applications and have characteristics similar to OAEP scheme. See RFC 3447 for more details.
You can easily check out that my answer is correct with command line OpenSSL tool:
Generate private key:
openssl genrsa -out private.key 2048
Generate some input data:
echo "Hello world" > input.data
Try to generate signature with OAEP scheme:
openssl rsautl -sign -oaep -inkey private.key -in input.data -out output.data
RSA operation error
139655304349344:error:04066076:rsa routines:RSA_EAY_PRIVATE_ENCRYPT:unknown padding type:rsa_eay.c:389:
Try to encrypt data with OAEP scheme:
openssl rsautl -encrypt -oaep -inkey private.key -in input.data -out output.data
You can also take a look at "rsautl" module source code if you need more information but remember that RFC 3347 is your friend :)

How do I use libtomcrypt to import an RSA public key?

I am experimenting with using libtomcrypt to do RSA-2048 bit encryption. My current objective is to import a public key from a file. This file was generated using OpenSSL with the command:
$ openssl rsa -in private.pem -outform PEM -pubout -out public.pem
So I believe my public key is in PKCS#1 padding and in OpenSSL's PEM format.
I believe the function I need to use is rsa_import(), but that takes an in buffer, a length, and outputs an rsa_key pointer. Just to be clear, I believe what I need to do is as follows:
Read in the contents of public.pem to a buffer
Toss out the Header and Footers containing "Begin Public Key" etc.
Decode data from base64.
Pass in resulting data to rsa_import.
Is this correct? Can anyone who has used libtomcrypt for this purpose comment on this? Thanks.
So, upon digging into the source of rsa_import(), I figured out pretty quickly that it was expecting the key to be in DER format. Since I had access to the private key, I just made a DER file using this openssl command:
openssl rsa -in private.pem -outform DER -pubout -out public.der
Notably the argument for -outform is now DER rather than PEM. After this, I just read the file contents into a char buffer, then passed that in as the main argument for rsa_import. After that rsa_import made the key no problem and I was able to encrypt/decrypt from there.

Resources