What's the detail in "SHA1withRSA"? - java

Innocently, I thought "SHA1withRSA algorithm" was simply operating the plainText with "SHA1", and use RSA/pkcs1padding to encrypt the result of "SHA1"。However, I found I was wrong until I wrote some java code to test what I thought.
I use RSA publickey to decrypt the signature which I use the corresponding privatekey to sign with "SHA1withRSA algorithm" . But I found the result is not equal to "SHA1(plainText)", below is my java code:
String plaintext= "123456";
Signature signature=Signature.getInstance("SHA1withRSA",new BouncyCastleProvider());
signature.initSign(pemPrivatekey);
signature.update(plaintext.getBytes());
byte[] sign = signature.sign();
//RSA decode
byte[] bytes = RsaCipher.decryptByRsa(sign, pemPublickey);
String rsaDecodeHex=Hex.toHexString(bytes);
System.out.println(rsaDecodeHex.toLowerCase());
String sha1Hex = Hash.getSha1(plaintext.getBytes());
System.out.println(sha1Hex);
//rsaDecodeHex!=sha1Hex
Easy to find that rsaDecodeHex!=sha1Hex, where
rsaDecodeHex=3021300906052b0e03021a050004147c4a8d09ca3762af61e59520943dc26494f8941b
and
sha1Hex=7c4a8d09ca3762af61e59520943dc26494f8941b 。
So, What's the detail in "SHA1withRSA" ?

The digital signature algorithm defined in PCKS#1 v15 makes a RSA encryption on digest algorithm identifier and the digest of the message encoded in ASN.1
signature =
RSA_Encryption(
ASN.1(DigestAlgorithmIdentifier + SHA1(message) ))
See (RFC2313)
10.1 Signature process
The signature process consists of four steps: message digesting, data
encoding, RSA encryption, and octet-string-to-bit-string conversion.
The input to the signature process shall be an octet string M, the
message; and a signer's private key. The output from the signature
process shall be a bit string S, the signature.
So your rsaDecodeHex contains the algorithm identifier and the SHA1 digest of plainText

Related

RSA should I use X.509 or PKCS #1

Use case:
I have a use case wherein client generates private and public key , sends the base 64 encoded public key to the server.
On server side I will encrypt a message using this public key and send the encrypted message to client , which the client decrypts using its private key.The algorithm agreed upon is 'RSA'.
The problem is on server side I am seeing that certain keys are working using X509EncodedKeySpec as key spec
byte[] publicBytes = Base64.decodeBase64(base64EncodedPubKey);
X509EncodedKeySpec keySpec = new X509EncodedKeySpec(publicBytes);
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
PublicKey pubKey = keyFactory.generatePublic(keySpec);
While some keys throw exception (Caused by: java.security.InvalidKeyException: IOException: algid parse error, not a sequence) using X509EncodedKeySpec but work using RSAPublicKeySpec:
byte[] publicBytes = Base64.decodeBase64(base64EncodedPubKey);
org.bouncycastle.asn1.pkcs.RSAPublicKey.RSAPublicKey pkcs1PublicKey = org.bouncycastle.asn1.pkcs.RSAPublicKey.RSAPublicKey.getInstance(publicBytes);
BigInteger modulus = pkcs1PublicKey.getModulus();
BigInteger publicExponent = pkcs1PublicKey.getPublicExponent();
RSAPublicKeySpec keySpec = new RSAPublicKeySpec(modulus, publicExponent);
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
PublicKey pubKey = keyFactory.generatePublic(keySpec);
So, what I came to understand is that client and server need to agree whether to use:
PKCS #1 or X.509 for encoding the key . My question is which one is better for my use case? Any guidelines when to use which format?
There's very little difference. The key format Java calls X.509, more exactly known as the ASN.1 structure SubjectPublicKeyInfo (or SPKI) defined in X.509 or equivalently and more conveniently in RFC5280 sec 4.1, is a quite simple way to handle a large and flexible set of algorithms: it consists of a substructure AlgorithmIdentifier which identifies the algorithm and its parameters if applicable, then an opaque BIT STRING which contains the actual key information (encoded) in a format depending on (the algorithm identified by) the AlgorithmIdentifier.
For RSA, the algorithm-dependent part is the ASN.1 structure RSAPublicKey defined in PKCS1 or more conveniently RFC8017 appendix A.1.1 and its earlier versions, and duplicated in RFC3279 sec 2.3.1. Thus for RSA the X.509 (SPKI) format contains the PKCS1 format, and since RSA doesn't have parameters (or at least key-related parameters), the only real difference is that the X.509 format explicitly specifies that the key is RSA -- which in your application you already know.
You have already discovered that vanilla (Oracle-was-Sun-now-OpenJDK) Java crypto, aka JCA Java Cryptographic Architecture, directly supports only the X.509 (SPKI) format, which is a minor advantage. However if you use BouncyCastle it is much easier to convert back and forth than the code in your Q; you simply use the org.bouncycastle.asn1.x509.SubjectPublicKeyInfo class to add or discard the AlgorithmIdentifier:
// test data source
KeyStore ks = KeyStore.getInstance("JKS"); ks.load (new FileInputStream (args[0]), args[1].toCharArray());
byte[] spkienc = ks.getCertificate(args[2]).getPublicKey().getEncoded();
System.out.println (DatatypeConverter.printHexBinary(spkienc));
// extract PKCS1 part of original SPKI
byte[] pkcs1enc = SubjectPublicKeyInfo.getInstance(spkienc).parsePublicKey().getEncoded();
System.out.println (DatatypeConverter.printHexBinary(pkcs1enc));
// rebuild SPKI from the PKCS1
AlgorithmIdentifier algid = new AlgorithmIdentifier(PKCSObjectIdentifiers.rsaEncryption, DERNull.INSTANCE);
byte[] spki2enc = new SubjectPublicKeyInfo (algid, pkcs1enc).getEncoded();
System.out.println (DatatypeConverter.printHexBinary(spki2enc));
See my answer to the similar golang x509.MarshalPKIXPublicKey vs x509.MarshalPKCS1PublicKey() and especially the links to:
Converting A public key in SubjectPublicKeyInfo format to RSAPublicKey format java
Generating RSA keys in PKCS#1 format in Java
Problem transmiting a RSA public key, javaME , bouncy castle
If you don't have BouncyCastle, it's a little harder; you need to write a partial ASN.1 parser or generator. Full ASN.1 processing is rather complicated, but for this case you need only a small subset that isn't too bad. (Yeah, that's faint praise.) I may add this later if I have more time.
A much bigger potential issue is that your key is not authenticated. The hard part of public key distribution, much harder than tiny format details, is making sure that only the legitimate key is distributed. If an attacker can substitute their publickey for the correct one, then the victim encrypts the supposedly secret data in a way the attacker can easily read, and all your fancy cryptography code is completely worthless.
This is why most actual systems don't distribute bare publickeys, but instead certificates that allow verifying the key is the correct key. There are a few certificate schemes, but the most widespread by far is X.509 and its Internet profile PKIX -- in fact the RFCs I referenced above, 5280 and 3279, are part of PKIX. SSL-now-TLS uses X.509. Code-signing uses X.509. S/MIME email uses X.509. (PGP/GPG uses a different kind of certificates, not X.509, but still certificates.) And (vanilla) Java directly supports X.509 certificates just as well or even better than it does "X.509" (SPKI) publickeys.

Get the sha1-hashed value from XML signature value

I need someone to help me understand XML digital signature method rsa-sha1. I suppose the signature value = RSA-encrypt(sha1(signedInfo), privatekey).
Note Base64.encode(sha1(signedInfo)) contains 28 characters. So I think Base64.encode(RSA-decrypt(signaturevalue), publickey) should return 28 characters as well. However, I actually got a 48-character string.
Base64 base64 = new Base64();
byte[] encrypted = base64.decode(signatureValue);
try {
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.DECRYPT_MODE, getX509Cert().getPublicKey());
byte[] cipherText = cipher.doFinal(encrypted);
System.out.println(base64.encodeToString(cipherText));
//print out MCEwCQYFKw4DAhoFAAQU0G+7jFPydS/sWGO1QPjB0v3XTz4=
//which contains 48 characters.
}
catch (Exception ex){
ex.printStackTrace();
}
Signature method as indicated in XML file
<ds:SignatureMethod Algorithm="http://www.w3.org/2000/09/xmldsig#rsa-sha1"/>
RSA signing is not actually the same as encrypting with the private key, but JCE promotes this mistake by allowing 'backwards' operations in Cipher for RSA (only) which actually do PKCS1-v1_5 signature and recovery instead of encryption and decryption as they were designed to.
For the original standardized RSA signature scheme in PKCS1 through v1.5, now retronymed RSASSA-PKCS1-v1_5, the value that is padded (with 'type' 01 multiple FFs and one 00) and modexp'ed with the private key is not just the hash but an ASN.1 structure containing the hash. See the encoding operation EMSA-PKCS1-v1_5 in section 9.2 of rfc8017 or rfc3447 or 9.2.1 in rfc2437, especially step 2 and (for the newer two versions) 'Notes' item 1.
Dupe Using SHA1 and RSA with java.security.Signature vs. MessageDigest and Cipher
and Separate digest & signing using java security provider

RSA encryption in Java, decrypt in PHP

Assume I have the following Java code to generate a Public-private keypair:
KeyPairGenerator generator = KeyPairGenerator.getInstance ("RSA");
SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
generator.initialize (1024, random);
KeyPair pair = generator.generateKeyPair();
RSAPrivateKey priv = (RSAPrivateKey)pair.getPrivate();
RSAPublicKey pub = (RSAPublicKey)pair.getPublic();
// Sign a message
Signature dsa = Signature.getInstance("SHA1withRSA");
dsa.initSign (priv);
dsa.update ("Hello, World".getBytes(), 0, "Hello, World".length());
byte[] out = dsa.sign();
/* save the signature in a file */
FileOutputStream sigfos = new FileOutputStream("sig");
sigfos.write(out);
sigfos.close();
How would one go about and decrypt the file "sig" in PHP? I've read the post: https://stackoverflow.com/a/1662887/414414 which supplies a function to convert a DER file to PEM (Assume I also save the public key from Java).
I have tried something like:
$key = openssl_pkey_get_public ("file://pub_key.pem");
$data = null;
openssl_public_decrypt ( file_get_contents ("sig"), $data, $key);
echo $data, "\n";
It successfully decrypts the message, but it is many weird characters.
Our scenario is a Java client that is sending messages to a PHP server, but encrypts the data with a private key. PHP knows about the public key, which it should use to decrypt and validate the message.
I've read a lot of posts regarding this issue here on SO, but I've come to realize that this is a bit specific issue, especially if there's different algorithms in use, etc. So sorry if this may be a duplicate.
Any feedbacks are greatly appreciated!
an "RSA signature" is usually more than just "encrypt with private key, decrypt with public key", since Public key protocols like PKCS#1 also specify padding schemes, and all signature schemes will encrypt a digest of the message, instead of the full message. I cannot find any documentation if java's signature scheme uses the signature padding scheme specified in PKCS#1, but my suspicion is that it is.
If it is, you will instead want to use the openssl_verify method in PHP, documented here. This will return a 0 or 1 if the signature is invalid or valid, respectively.
In the event that Java does not use a padding scheme, your issue is that the data encrypted in the signature is a hash of the message, instead of the message itself (you can see in the Java code that it uses the SHA-1 hash algorithm). So on the PHP side, you will need to take the sha1 hash of your message using the sha1 method with $raw_output set to true, and compare those strings to ensure your message is valid.
From the snippet
$key = openssl_pkey_get_public ("file://pub_key.pem");
It looks like you're referencing the public key, which would be the wrong one to decrypt. Double check ?

How to verify Hash of a plainText instead of plainText itself

I'm trying to verify a SHA1 With RSA signature in Java. My code is actually this :
String plainText = "myString";
String signature_b64_encoded = "bOBrJmPGJ6eqDpk7sZMJZ0QujErTVz/boe44ANTLbeHd1Pm56UBH3uUCdH4sDZcDczIW5E6Q0o2dq/4lpjTAOzu3FjaLMAZ1sSTn8Ds8XxQnOnmhapbrd/6sNSr9fC57c7BlgAy7GZbCZGUQC/b/UETb8cIR0B1Dqk41RDorm+NdwDEVCTl4q9I7D70/Kau/aGpUvJ3ULgzM3/JnxHpaWmG7xAsXH9MyxVSxi/ZpJ0WuyuaAiSmiDN946O/ElIxRqnaEtFuSIDinUYz4yAWtoLdssDO5SqMFb8EskUdfExs1IcGtYRaIbz3ASTFdVQoou7HI4pxVn1Sh4Y4mrxa7Ag==";
Signature instance = Signature.getInstance("SHA1WithRSA");
PublicKey pkey = cert.getPublicKey(); // gets my Public Key
instance.initVerify(pkey);
instance.update(plainText.getBytes());
Boolean blnResult = instance.verify(Base64.decode(strSignature.getBytes("UTF-8"), Base64.DEFAULT));
The problem is that the signature verified is false only in some cases and in other cases it is true. I don't manage to understand the cause of the randomness of this result.
The string i'm trying to verify is signed in .NET environment
The verification of the signature done in .NET is made on the hash of the plainText and not on the plainText.
Question 1
Is there a means to verify the hash of the plainText instead of plainText itself in Java (as it is possible in .NET) ? This would allow to be sure to have the same input at the beginning of the verification process.
Question 2
Is there another way to verify a SHA1 with RSA signature in Java ?

Java: How to create a RSA Public Key from the String

I have the byte array of the RSA Public Key. I found on the internet that I can create a real PublicKey object of it by using this code:
PublicKey publicKey =
KeyFactory.getInstance("RSA").generatePublic(new X509EncodedKeySpec(bytes));
But every time I run this code, I'm getting another result for the encrypted data using that key. I'm sure the data I want to encrypt is always the same, so does the byte array representing the key.
Is this normal?
Here is my code always producing another output:
byte[] keyBytes = Base64.decodeBase64(rsa_1024_public_key);
// rsa_1024_public key is a constant String
Cipher c = Cipher.getInstance("RSA");
PublicKey publicKey =
KeyFactory.getInstance("RSA").generatePublic(new X509EncodedKeySpec(keyBytes));
c.init(Cipher.ENCRYPT_MODE, publicKey);
return c.doFinal(password.getBytes());
This is probably a part of the asymmetric encryption algorithm?
Thanks.
RSA is non-determinstic.
You can make it deterministic by selecting a non-random padding mode; however, that will not be secure.

Categories

Resources