How do I load DSA Parameters from a PEM file in Bouncycastle? - bouncycastle

I have a PEM file for DSA Parameters. In other words, the content has header/footer like this:
-----BEGIN DSA PARAMETERS-----
.......
-----END DSA PARAMETERS-----
I see that bouncycastle has classes for DSAParameters and DSAKeyGenerationParmaters. I suspect that this PEM is a representation of those parameters, but I can't figure out how to load it from a PEM format.
(Background: from legacy projects, I expected the signature of a DSA to be 40-bytes, but I am getting 46-bytes instead. I suspect that the DSA parameters are to blame, and I have this old dsa1024.pem as described, that I am trying to load and use to generate keys/generate signatures...)

At least through 1.57 (I don't have 1.58 installed yet) BCpkix org.bouncycastle.openssl.PEMParser doesn't implement DSA PARAMETERS (although it DOES do EC PARAMETERS) so this won't be easy.
To just look at your parameters it will be (much) easier to use
openssl dsaparam -in file -noout -text
But I guarantee you won't find anything wrong in your parameters. Classic DSA parameters have been 1024 bit group and 160 bit subgroup without any variation or change for 20 years and I've never seen any implementation get that wrong.
The usual reason a DSA-1024/160 signature occupies more than 40 octets is because by convention (though not required by FIPS 186) it is encoded in ASN.1 DER. If you had asked a question about that, I could point to you to existing Qs for ECDSA, which has exactly the same issue:
https://crypto.stackexchange.com/questions/1795/how-can-i-convert-a-der-ecdsa-signature-to-ASN.1
https://crypto.stackexchange.com/questions/33095/shouldnt-a-signature-using-ecdsa-be-exactly-96-bytes-not-102-or-103
https://crypto.stackexchange.com/questions/37528/why-do-openssl-elliptic-curve-digital-signatures-differ-by-one-byte
https://crypto.stackexchange.com/questions/44988/length-of-ecdsa-signature
but since you asked a question that isn't about your actual problem it's against Stack policy to give you a solution to your actual problem.
FWIW if you generate a DSA key(pair) in OpenSSL using the parameters, all 4 PEM formats for privatekey (pkcs8 clear and encrypted, 'legacy' clear and encrypted) and the usual PEM format for publickey (SPKI) are readable by PEMParser and can produce key objects from which the parameters can be extracted. (Technically the specification for SPKI allows DSA parameters to be omitted in certain situations, but OpenSSL never does so.)

Related

How do you decrypt a file that has been encrypted with openssl using nodejs javascript

I have a file that has been encrypted using openssl using the following command:
openssl enc -in data -out encrypted -e -aes256 -k myverystrongpassword
Where data is the original file and encrypted is the encrypted file.
I tried various ways using crypto library but nothing seems to work. I understand that the password needs to be converted into a key so maybe I am doing something wrong there. Looked all over for a solution but nothing seems to work.
The posted OpenSSL statement uses a key derivation function EVP_BytesToKey() to derive a 32 bytes key and a 16 bytes IV from the password in combination with a random 8 bytes salt.
The ciphertext corresponds to the concatenation of the ASCII encoding of Salted__, followed by the salt and finally by the actual ciphertext.
As you already know according to your comment, EVP_BytesToKey() uses a digest for which OpenSSL applied MD5 by default in earlier versions and SHA-256 as of version v1.1.0 (the default value can be overridden in the OpenSSL statement with the -md option).
Decryption is possible e.g. with CryptoJS: Due to its OpenSSL compatibility (s. sec. Interoperability) CryptoJS has a built-in implementation of an accessible EVP_BytesToKey() function and additionally allows to explicitly set the digest in the internal EVP_BytesToKey() call during key derivation. This makes it possible to decrypt encryptions that used SHA-256 or MD5 in key derivation.
The following data is the Base64 encoding of a ciphertext generated with the posted OpenSSL statement. The plaintext used was The quick brown fox jumps over the lazy dog. The OpenSSL version applied is v1.1.1i (i.e. SHA-256 is implicitly used in the key derivation):
U2FsdGVkX19W4wmC9dD35X4J66cSvaRaIQpvjDKHrLF9+qYg5VTo5urvExHLXhwf/bE8FXJTQZmKN8ITMJVdqQ==
This ciphertext can be successfully decrypted using the following CryptoJS implementation:
const password = 'myverystrongpassword';
const saltCiphertextB64 = 'U2FsdGVkX19W4wmC9dD35X4J66cSvaRaIQpvjDKHrLF9+qYg5VTo5urvExHLXhwf/bE8FXJTQZmKN8ITMJVdqQ==';
CryptoJS.algo.EvpKDF.cfg.hasher = CryptoJS.algo.SHA256.create(); // default: MD5
const decryptedData = CryptoJS.AES.decrypt(saltCiphertextB64, password);
console.log(decryptedData.toString(CryptoJS.enc.Utf8)); // The quick brown fox jumps over the lazy dog
<script src="https://cdnjs.cloudflare.com/ajax/libs/crypto-js/4.1.1/crypto-js.min.js"></script>
Note that the digest in the code must be explicitly specified as SHA-256 since OpenSSL v1.1.1i was used for encryption.
If the encryption was done with an OpenSSL version that uses MD5, the digest in the code must be modified accordingly.
Edit: As noted in the comment, the crypto functions createCipher()/createDecipher() also use EVP_BytesToKey() as key derivation.
However, the following should be noted:
Unlike CryptoJS, it is not possible to specify the digest, i.e. MD5 is used unchangeably. Thus, encryptions that applied SHA-256 for key derivation cannot be decrypted (what applies to the encryptions here).
In contrast to CryptoJS, no salt is used by default. Therefore, salt creation and concatenation (Salted__|<salt>|<cipherext>) during encryption and separation during decryption would have to be implemented additionally. createCipher()/createDecipher() then has to be passed the concatenation of passphrase and salt.
Both functions are deprecated since version 10.0.0 and should actually not be used.
A more robust approach to decrypt encryptions (with arbitrary digests in key derivation) using the crypto module is to apply createCipheriv()/createDecipheriv() and a port of the required functionality of EVP_BytesToKey() to derive key and IV (various implementations can be found on the net).
Security: EVP_BytesToKey() is deemed to be a vulnerability these days. This is worsened by a low iteration count (like 1, which is used by OpenSSL), a broken digest (like MD5) or a missing salt (as is the default for crypto). Ultimately, this is why createCipher()/createDecipher() are deprecated. Instead of EVP_BytesToKey(), a more reliable key derivation function such as PBKDF2 or the more modern scrypt or Argon2 should be used.

Can a digital signature change for the same input data PKCS7 / SHA256

Conceptually, can a digital signature vary if it is generated multiple times for the same input data with SHA256 hashing and PKCS7 formatting.
Thank you for any help.
If data is same, SHA256 hash would be same and PKCS7 signature, using same private/public key pair, may be same unless it contains time stamping.

Create EC private key from input keying material in NodeJS

I'd like to derive an elliptic curve private key from input keying material (a master key). Is this possible?
Attempts
Node's crypto function, crypto.generateKeyPair does not accept input keying material, and crypto.createPrivateKey only converts a .pem to Node's native KeyObject.
I also can't find a way to do this in OpenSSL using ecparam. The -rand flag seems promising but isn't widely available (it's not on my machine).
Why / Details
I need to create a number of secrets and want have all of them derived from a single master key. This is analogous to HKDF.
I'm using the keys for ECDSA with curve P-384 (secp384r1).
I'm surprised you think ecparam -rand file -genkey ... is rare; it's in every upstream version back at least to 0.9.8 in 2005, and it's not one of the things that can be omitted by a build (configure) option, so your machine must have one weird version. But it doesn't matter because -rand doesn't do what you want; it adds the file data to the RNG 'pool' but does not replace it, so it doesn't give you deterministic key generation.
As Woodstock commented, for all practical purposes a raw P-384 private key is just 384 bits from any good random generator, or deterministically from any uniform random function. Technically you should exclude zero and values greater than or equal to the (sub)group order n, but those exclusions are so small relative to 2^384 that there is essentially no chance a good random choice will hit them during the lifetime of the Earth, and perhaps of the universe. You might want to look at how Bitcoin 'hierarchical deterministic' key derivation aka BIP 32 works, although of course that does 256-bit keys for secp256k1.
That leaves you the problem of converting the raw key to a form usable by nodejs crypto (which is a fairly thin wrapping of openssl library) and/or openssl commandline. To do this follow the principles of How to convert an ECDSA key to PEM format which is in turn based on https://bitcoin.stackexchange.com/questions/66594/signing-transaction-with-ssl-private-key-to-pem except use the OID and size(s) for P-384 instead of secp256k1. Specifically, concatenate
the 7 bytes represented in hex by 303e0201010430
the 48 bytes (384 bits) of the raw private key
the 9 bytes represented in hex by a00706052b81040022 (for P-384 aka secp384r1)
Depending on your language(s) or tool(s) you might handle these values directly, or concatenate the hex representations and then convert to binary. The result is the 'DER' (binary) form of the algorithm-specific (SEC1) private key (only), which can be read by nodejs 11 or 12 crypto.createPrivateKey( {key:(data), format:'der', type:'sec1'} ) and also by commandline openssl ec -inform der.
If you prefer textlike things (e.g. for cut&paste), convert the DER above to base64, break into lines of 64 chars (other than the last), and add lines -----BEGIN EC PRIVATE KEY----- before and -----END EC PRIVATE KEY------ after. This is PEM format and can be read by createPrivateKey without any other options, and by openssl ec without any option.

Understanding BCryptSignHash output signature

I have signed a hash value in windows using BCryptSignHash with ECDSA algorithm. The output signature buffer is of length 64 bytes. I also generated the public and private key blobs using BCryptGenerateKeyPair function (BCRYPT_ECDSA_P256_ALGORITHM algorithm) with which i signed the hash.
I have to verify this signature with this key pair in linux. I am able to decipher the public-private key pair that got generated, using the link "http://msdn.microsoft.com/en-us/library/windows/desktop/aa375520%28v=vs.85%29.aspx" and able to use the same in linux.
The 64-byte signature generated should ideally be signature pair (r,s) (http://en.wikipedia.org/wiki/Elliptic_Curve_DSA).
Is there a way to understand the 64-bytes signature generated so that i can map the signature blob contents to (r,s) pair in linux and verify it?
Or is there a simpler way to verify the generated signature in linux?
Thanks,
F
Is there a way to understand the 64-bytes signature generated so that I can map the signature blob contents to (r,s) pair in linux and verify it?
The r and s are in P1363 format, which is simply a concatenation of r and s in a 2's compliment format. That is, the signature is simply r || s.
You need to know the hash to use this format. For example, SHA1 will create a r of 20 bytes and an s of 20 bytes. If r or s is "too short", then it is padded on the left with 0's.
Java and OpenPGP are different than P1363. Java and OpenPGP use an ASN.1 encoding:
SEQUENCE ::= {
r INTEGER,
s INTEGER
}
Depending what library you use on Linux, you may have to convert between the formats. Cryptographic Interoperability: Digital Signatures gives examples of signing and verifying using a few different libraries.
Or is there a simpler way to verify the generated signature in linux?
Try Crypto++. I believe Microsoft and Crypto++ uses the same signature format, so you won't need to convert. See Elliptic Curve Digital Signature Algorithm for details.

Space constrained asymmetric signature

I need to sign a small string with an asymmetric key encryption scheme.
The signature will be stored on a small chip together with the signed string. I have very little space to spare (about 60bytes for signature + string), so the generated signature should be as small as possible.
I looked around for how to do it, and what I found is that I could use RSA-SHA1, but the generated signature with a 512 bit key is 64 bytes. That is a bit much.
What secure algorithm could I use to generate a small asymmetric signature?
Would it still be secure if I store the SHA1 sum of the RSA-SHA1 signature, and later verify that instead?
What you're bumping up against here is one of the properties of a good hash function - the return value should be long to protect against birthday attacks (where two different inputs result in the same output hash). Generally 128-512 bits is preferred hence the SHA-1 signature gives you 512 bits.
As with all things in cryptography security is a trade off. As you are using asymmetric signing have you considered using RSA-MD5 as your signature option? This will give you a far shorter return of 128 bits but this comes with the caveat that MD5 is considered broken and is generally being moved away from.

Resources