【问题标题】:RSA Bad Padding ExceptionRSA 错误填充异常
【发布时间】:2017-10-17 04:44:30
【问题描述】:

我正在尝试对 Android 上的数据进行 RSA 加密并将其发送到服务器(spring)。 得到 BadPaddingException :

方法: 服务器以字符串形式发送公钥,我将其转换为 PublicKey 对象并在加密后从 App 发送数据作为字符串。 服务器有一个私钥字符串,将其转换为PublicKey对象,然后解密数据。

任何帮助将不胜感激。

密钥生成:

    public static KeyPair generateKeyPairRSA()  {
    try {
        SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
        KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
        keyGen.initialize(1024, random);
        KeyPair keyPair = keyGen.generateKeyPair();
        return keyPair;
    } catch (Exception e) {
        Log.d(TAG,e.getLocalizedMessage());
    }
    return null;
}


public byte[] RSAEncrypt(final String plain, PublicKey publicKey) throws Exception {
    Cipher cipher = Cipher.getInstance(ALGO_RSA);
    cipher.init(Cipher.ENCRYPT_MODE, publicKey);
    byte[] encryptedBytes = cipher.doFinal(plain.getBytes());
    return encryptedBytes;
}

public static PublicKey loadPublicKey1(String stored) throws Exception{
    byte[] data = Base64.decode(stored.getBytes());
    X509EncodedKeySpec spec = new X509EncodedKeySpec(data);
    KeyFactory fact = KeyFactory.getInstance(ALGO_RSA);
    return fact.generatePublic(spec);
}

服务器方法:

public byte[] decryptRSA(String inputData) throws Exception {
    byte[] inputBytes = Base64.decodeBase64(inputData);
    PrivateKey key = loadPrivateKey(getPrivateKey());
    Cipher cipher1 = Cipher.getInstance("RSA");
    cipher1.init(Cipher.DECRYPT_MODE, key);
    return cipher1.doFinal(inputBytes);
}

private PrivateKey loadPrivateKey(String key64) throws Exception {
    byte[] pkcs8EncodedBytes = Base64.decodeBase64(key64);
    PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(pkcs8EncodedBytes);
    KeyFactory kf = KeyFactory.getInstance("RSA");
    return kf.generatePrivate(keySpec);
}

【问题讨论】:

  • 只是出于好奇,ALGO_RSA 映射到什么?
  • RSA。顺便说一句,解决了。谢谢

标签: java spring encryption rsa badpaddingexception


【解决方案1】:

得到它的工作。 所以不同的库有不同的密码实现。 所以在打电话时

Cipher.getInstance("RSA/ECB/PKCS1Padding");

明确提及加密模式和填充。

希望它对某人有所帮助。

【讨论】:

    猜你喜欢
    • 2012-09-14
    • 2014-07-13
    • 1970-01-01
    • 1970-01-01
    • 2017-12-10
    • 1970-01-01
    • 2017-08-21
    • 2021-08-08
    • 1970-01-01
    相关资源
    最近更新 更多