0

I'm trying to implement RSA Encryption in both Java and PHP, but I can't seem to get PHP to output the same Encrypted Result with Java.

Java Code

public static String sign(byte[] data,String privateKey)throws Exception{
    byte[] keyBytes = Base64.decodeBase64(privateKey);
    PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(keyBytes);

    //KEY_ALGORTHM="RSA";
    KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORTHM);
    PrivateKey privateKey2 = keyFactory.generatePrivate(pkcs8EncodedKeySpec);

    //SIGNATURE_ALGORITHM="SHA1WithRSA"
    Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM);
    signature.initSign(privateKey2);
    signature.update(data);
    return Base64.encodeBase64String(signature.sign());
}

PHP Code

public function sign( string $data,string $privateKey){
      openssl_private_encrypt($data,$encrypted,$privateKey);
      return base64_encode($encrypted);
}

Can someone help me to translate it to PHP Code ?

Any help would be greatly appreciated o.O

3
  • Which PHP code did you write so far? Commented Apr 17, 2018 at 7:57
  • @Med hi,Med,I have added the PHP code Commented Apr 17, 2018 at 8:05
  • From the openssl_private_encrypt man page have you played around with the $padding arg? It defaults too OPENSSL_PKCS1_PADDING but you may want OPENSSL_PKCS1_OAEP_PADDING instead Commented Apr 17, 2018 at 8:22

1 Answer 1

3

I have solved the problem.

In Java Code,it's SIGNATURE_ALGORITHM is 'SHA1WithRSA'

so,In PHP Code

public function sign( string $data,string $privateKey){
  openssl_sign($data,$sign,$privateKeyString,OPENSSL_ALGO_SHA1);
  return base64_encode($encrypted);
}
Sign up to request clarification or add additional context in comments.

2 Comments

Good stuff please mark this as the answer so the topic can be closed =)
@IsThisJavascript ok,but SO said 2 days later then I can mark my answer as the topic's answer:)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.