How to make “MessageDigest SHA-1 and Signature NONEwithRSA” equivalent to “Signature SHA1withRSA ”

后端 未结 2 456
陌清茗
陌清茗 2021-02-03 14:47

I am interested in applying a SHA-1 hash with RSA signature to some data, but I need to do it in two steps - apply hash first and then sign the data. The Signature.sign() funct

2条回答
  •  失恋的感觉
    2021-02-03 15:44

    I was able to solve this by doing the following:

    1. The data to be signed needed to be formatted correctly in a DigestInfo DER-encoded byte array. The Signature SHA1withRSA takes care of this for you, but if you want to accomplish it in a two-step process, you need to create your own DigestInfo. I ended up copying a very minimal amount of ASN.1 classes from BouncyCastle into my project to accomplish this, despite my desire not to use a third party lib.

    2. If you try to use the Cipher API to encrypt the DigestInfo, the PKCS1 padding will be random and not appropriate for a digital signature. I needed static padding.

    3. The Signature.getInstance("NONEwithRSA", "SunMSCAPI") rejects the DER-encoded DigestInfo format, and will return an error if you try to sign that data. But, since I ultimately wanted to use the PKCS11 API to generate the signature, I ended up signing the DER-encoded DigestInfo with the PKCS11 C_SignInit and C_Sign functions.

    To summarize, what worked for me was:

    1. generate the SHA-1 hash of the data to sign using the Java MessageDigest API
    2. generated a DigestInfo DER-encoded ASN.1 object with the SHA-1 hash and SHA-1 OID embedded in the object.
    3. signed the DigestInfo using the PKCS11 C_Sign function from a third party library.

    The following links were most helpful in solving my problem:

    Oracle Forums: SHA1withRSA - how to do that in 2 steps?

    StackOverflow: Using SHA1 and RSA with java.security.Signature vs. MessageDigest and Cipher

提交回复
热议问题