wanghao qin
wanghao qin

Reputation: 145

Failed to RSA decrypt with java

My password is encrypted with RSA in an android app. On the server side, I need to decrypt it., What I have is a .pem file, and the php code for decrypting:

 function privatekey_decodeing($crypttext, $fileName, $fromjs = FALSE)
    {
        $key_content = file_get_contents( $fileName );
        $prikeyid = openssl_get_privatekey( $key_content, "1234" );
        $crypttext = str_replace(' ', '+', $crypttext);
        $crypttext = base64_decode( $crypttext );
        $padding = $fromjs ? OPENSSL_NO_PADDING : OPENSSL_PKCS1_PADDING;
        if( openssl_private_decrypt( $crypttext, $sourcestr, $prikeyid, $padding ) )
        {
            return $fromjs ? rtrim( strrev( $sourcestr ), "/0" ) : "" . $sourcestr;
        }
        return;
    }

the fileName is frivatekey file(.pem file) Now I need to use java to decrypt it. I have tried some methods, all have failed. Here is what I have tried:

  1. using the .pem file to generate a .der key file
  2. reading the .der file to get the privateKey
  3. using the byte[] read from .der file to generate keyfile

    public static PrivateKey generatePrivateKey(byte[] key)
        throws NoSuchAlgorithmException, InvalidKeySpecException {
        KeySpec keySpec = new PKCS8EncodedKeySpec(key);
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        return keyFactory.generatePrivate(keySpec);
    }
    
  4. decrypt my password

    public static byte[] decrypt(PrivateKey privateKey, byte[] data)
        throws Exception {
        Cipher ci = Cipher.getInstance(ALGORITHOM, DEFAULT_PROVIDER);
        ci.init(Cipher.DECRYPT_MODE, privateKey);
        return ci.doFinal(data);
    }
    

But it does not work, and I do not know where is going wrong. In the php code I see $prikeyid = openssl_get_privatekey( $key_content, "1234" ); But I don't know what does the "1234" means. Does it mean using "1234" to encrypt the keyfile? Is this the reason the decrypt failed?

Upvotes: 1

Views: 567

Answers (1)

Scott Arciszewski
Scott Arciszewski

Reputation: 34113

$padding = $fromjs ? OPENSSL_NO_PADDING : OPENSSL_PKCS1_PADDING;

These are both bad options:

Please don't implement RSA yourself. You're going to make your application incredibly insecure.

Recommended reading:

Upvotes: 1

Related Questions