【问题标题】:BadPadding: Encryption Error when I decrypt my encrypted string at javaBadPadding:当我在 java 中解密我的加密字符串时出现加密错误
【发布时间】:2018-08-30 01:55:16
【问题描述】:

我使用SwiftyRSA 使用带有PKCS1 填充的公钥加密字符串。不幸的是,当我在 Java 中解密我的加密字符串时,我发现了BadPadding: Encryption Error。到目前为止,我发现 Java 使用 Mode 来加密/解密字符串,但在 iOS/Swift 中没有 Mode。请告诉我应该使用哪种算法在 Swift 和 Java 之间进行加密/解密。

这是用于加密/解密的公钥和私钥

https://github.com/ppshein/Encrypt-Decrypt

快速加密

let publicKey = try PublicKey(pemNamed: "public")
let clear = try ClearMessage(string: inString, using: .utf8)
let encrypted = try clear.encrypted(with: publicKey, padding: .init(rawValue: 0))
let base64 = encrypted.data.base64EncodedString()

Java 解密

public class CryptographyUsingKeystore {
    private static final String ALGORITHM = "RSA";
    public static byte[] encrypt(PublicKey publicKey, byte[] inputData)
            throws Exception {
        Cipher cipher = Cipher.getInstance(ALGORITHM);
        cipher.init(Cipher.PUBLIC_KEY, publicKey);
        byte[] encryptedBytes = cipher.doFinal(inputData);
        return encryptedBytes;
    }
    public static byte[] decrypt(PrivateKey privateKey, byte[] inputData)
            throws Exception {
        Cipher cipher = Cipher.getInstance(ALGORITHM);
        cipher.init(Cipher.PRIVATE_KEY, privateKey);
        byte[] decryptedBytes = cipher.doFinal(inputData);
        return decryptedBytes;
    }
    public static void main(String[] args) throws Exception {
        KeyProvider keyProvider = new KeyProvider();

        PublicKey publicKey = myKey.getPemPublicKey();
        //PrivateKey privateKey = (PrivateKey) keyProvider.getPrivateKey();

        byte[] encryptedData = encrypt(publicKey,
                "Hello".getBytes());

        System.out.println("Encrypted Key.... ");
        System.out.println(new String(Base64.getEncoder().encode(encryptedData)));

      byte[] decryptedData = decrypt(privateKey, encryptedData);

        System.out.println("Decrypted key.... ");
        System.out.println(new String(decryptedData));
    }
}

【问题讨论】:

    标签: java swift encryption badpaddingexception


    【解决方案1】:

    Java 加密 (JCA) 使用语法 algorithm/mode/padding called a transformation(或只是转换)来指定所有密码。如果仅指定算法,则默认模式和填充。 对于 RSA,没有实际的操作模式,转换中的模式 (ECB) 只是一个符合固定语法的占位符。但是有明显不同的填充方案。

    我不是 Swift 人,但it appears to me from the doc 0 实际上是 sigRaw,而 PKCS1 是 1。 如果是这样,您使用 'raw' = no padding 进行加密,这对应于 Java 的 NoPadding,因此使用 Java 默认的 PKCS1Padding 解密将失败,如您所见。试试"RSA/ECB/NoPadding"。或者更好的是,使用 PKCS1 加密 使用 PKCS1(显式或默认)解密,因为 ...

    警告: 没有填充的 RSA 加密在语义上总是不安全的,并且取决于您如何使用它通常完全不安全(例如,攻击者可以快速解密您的所有数据)。这正是它不是默认值且不推荐的原因。但是,安全不是 stackoverflow 的主题;这是 crypto.SX 和 security.SX 的主题,其中已经有许多 Q 和 As 解释未填充的又名“教科书”或“幼稚”RSA 加密的危险。

    【讨论】:

      猜你喜欢
      • 2020-03-20
      • 1970-01-01
      • 2018-03-05
      • 1970-01-01
      • 2019-06-07
      • 1970-01-01
      • 1970-01-01
      • 2019-02-07
      • 2017-11-20
      相关资源
      最近更新 更多