2
votes

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" ?

1
Just for the record: you understand that using SHA1 translates to "waste of time and energy"? blog.qualys.com/ssllabs/2014/09/09/… ... When you start looking into cryptography, better go for algorithms that are recommended to be used in 2017. SHA1 is ... not.GhostCat
And just for the record: if you dont get good answers here; consider asking on security.stackexchange.comGhostCat
Well, at a quick glance rsaDecodeHex seems to be sha1Hex padded with a couple of prefix bytes, but I may be wrong.biziclop
@GhostCat It obviously depends on what you use this for, but in this scheme SHA1 serves as just a traditional hash function, while secrecy is provided by RSA. If you need your hash to be secure too (which you probably do), then SHA1 is definitely not the answer.biziclop
@biziclop: this is a signature, RSA doesn't provide secrecy per se. So SHA1 needs to provide some security guarantees in this instance too.President James K. Polk

1 Answers

6
votes

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