为什么我不能在java环境下解码来自android设备的字符串?

guicsvcw  于 2021-07-05  发布在  Java
关注(0)|答案(1)|浏览(320)

我使用android设备用以下代码编写字符串:
安卓侧,键长:2048

//Init: need time
private void prepareEncrypt(String publicKey) throws Exception {
    X509EncodedKeySpec keySpec = new X509EncodedKeySpec(Base64.getDecoder().decode(publicKey.getBytes()));
    KeyFactory keyFactory = KeyFactory.getInstance("RSA");
    PublicKey pubKey = keyFactory.generatePublic(keySpec);
    cp = Cipher.getInstance("RSA/ECB/OAEPWithSHA-512AndMGF1Padding");
    cp.init(Cipher.ENCRYPT_MODE, pubKey);
}

//encrypt
private byte[] encryptByPublicKey(byte[] data) {
    //data = Base64.getEncoder().encode(data);
    byte[] result = new byte[0];
    try {
        result = cp.doFinal(data);
    } catch (BadPaddingException e) {
        e.printStackTrace();
    } catch (IllegalBlockSizeException e) {
        e.printStackTrace();
    }

    return result;
}

获取密文a。
然后我试着在elipse上用java解码a:

public static byte[] decryptByPrivateKey(byte[] encrypted, byte[] privateKey) throws Exception {
    PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(Base64.getDecoder().decode(privateKey));
    KeyFactory kf = KeyFactory.getInstance("RSA");
    PrivateKey keyPrivate = kf.generatePrivate(keySpec);
    Cipher cp = Cipher.getInstance("RSA/ECB/OAEPWithSHA-512AndMGF1Padding");
    cp.init(Cipher.DECRYPT_MODE, keyPrivate);
    byte[] arr = cp.doFinal(Base64.getDecoder().decode(encrypted));
    return arr;
}

我总是解码不出这个字符串。

javax.crypto.BadPaddingException: Decryption error
    at sun.security.rsa.RSAPadding.unpadOAEP(Unknown Source)
    at sun.security.rsa.RSAPadding.unpad(Unknown Source)
    at com.sun.crypto.provider.RSACipher.doFinal(RSACipher.java:363)
    at com.sun.crypto.provider.RSACipher.engineDoFinal(RSACipher.java:389)

如果android不更改对象密码上的转换参数,例如:
rsa/ecb/NOP添加
rsa/ecb/PKCS1P添加
rsa/ecb/OAEPHA-1和MGF1填充
rsa/ecb/OAEPHA-224和MGF1填充
rsa/ecb/OAEPHA-256和MGF1填充
rsa/ecb/OAEPHA-384和MGF1填充
rsa/ecb/OAEPHA-512和MGF1填充
如何成功解码密文a?

ncecgwcz

ncecgwcz1#

需要这个:

OAEPParameterSpec oaepParameterSpecDec = new OAEPParameterSpec("SHA-512", "MGF1", new MGF1ParameterSpec("SHA-512"), PSource.PSpecified.DEFAULT);
    ...
    cp.init(Cipher.DECRYPT_MODE, keyPrivate, oaepParameterSpecDec);

很明显,给我一些参数

相关问题