RSA .NET encryption Java decryption

后端 未结 3 1135
天命终不由人
天命终不由人 2020-12-23 12:41

I am trying to encrypt strings in .NET by using a RSA algorithm and decrypt the result in Java. At the moment, I have been able to do the opposite (Encrypt in Java, Decrypt

3条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-23 13:19

    The last few lines of your Java decrypt code do not make sense. These lines are:

    byte[] base64String = Base64.decode(encodedString);
    byte[] plainBytes = new String(base64String).getBytes("UTF-8");
    byte[] cipherData = cipher.doFinal(plainBytes);
    
    System.out.println(cipherData);
    return cipherData.toString();
    

    You have to reverse the order of the steps you used to encrypt in .NET. First, you should Base64 decode the encoded string to get the cipher bytes. You did that, but you mislabeled the result as base64String. You probably should call this result cipherData. Second, you need to decrypt cipherData to get plain text. Third, you should create a string from plainbytes using the two-arg String constructor with the Charset for the second argument. Here is what the code should look like, or close to it.

    byte[] cipherData = Base64.decode(encodedString);
    byte[] plainBytes = cipher.doFinal(cipherData);
    
    return new String(plainBytes, "UTF-8");
    

    Finally, in Java every object has a toString() method but it doesn't always do what you want. For arrays the toString() method simply returns a representation of object id for that array, sort of the JVM equivalent of a memory address.

    EDIT:

    I missed that you are also using the wrong key in your decrypt code. Your are using the RSA public key, but you must instead use the RSA private key.

提交回复
热议问题