RSA/ECB/PKCS1Padding with DECRYPT_MODE

20,561

Solution 1

You should not use Cipher to create or verify signatures. Instead you should use Signature.getInstance("SHA1withRSA").

Signature schemes and encryption schemes are different and they are not necessarily compatible with each other. For starters, they use different padding methods, and these padding methods are part of the security of the algorithm.

Even if you can get signature verification to work using Cipher, the chances are that you haven't verified the signature to the full extend, and your home-brewed signature verification scheme may (and possibly will) fail if a different implementation of Cipher is being used.

The code in the question seems to be using PKCS#1 v1.5 padding for encryption rather than for signature generation, so it is probably not correct.

Solution 2

That's the PKCS1 Padding. The algorithm appends the pkcs padding to your clear text data (i.e. your hash) to prevent some attacks based on repeated encrypted plain text data. It's a way to randomize the input data. If you re-encrypt the very same hash using the same key you'll get different pkcs header data (and a different cypher block of course). Obviously the pkcs padding has a fixed length so you can strip it out to get your original plain text.

Share:
20,561

Related videos on Youtube

Prem Nair
Author by

Prem Nair

Updated on July 05, 2022

Comments

  • Prem Nair
    Prem Nair almost 2 years

    I am trying to decrypt a string with public key to compare with a hash. The code is the followig

    byte[] dectyptedText = null;
    Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
    cipher.init(Cipher.DECRYPT_MODE, key);
    dectyptedText = cipher.doFinal(text);
    return dectyptedText;
    

    The above code generates a string like this (base64encode)

    MCEwCQYFKw4DAhoFAAQUy3qkZYgfRVo2Sv1F9bHa3pDs044=

    The hash is generated by the following code

     byte[] key = stringToHash.getBytes();
     MessageDigest md = MessageDigest.getInstance("SHA-1");
     hash = md.digest(key);
    

    The above code generates a sample hash like the following

    y3qkZYgfRVo2Sv1F9bHa3pDs044=

    If you notice both has the correct hash which is y3qkZYgfRVo2Sv1F9bHa3pDs044= But the decrypt code generates and prepends an extra MCEwCQYFKw4DAhoFAAQU

    Dont understand how this extra thing is added and why.

    Can please somebody throw some light on this ?

    Thanks

    prem

  • Prem Nair
    Prem Nair over 10 years
    got it. thanks owlstead. this was a non standard signature section. I will try to standardize it using Signature class.
  • Prem Nair
    Prem Nair over 10 years
    thanks g_g. it was the digestinfo padding (alog info) 20 bytes or so.
  • Prem Nair
    Prem Nair over 10 years
    i tried, but it seems I need a reputation of 15+ to do it :( ...i will do it once i get that