我用带有填充SwiftyRSA
的公钥加密字符串。PKCS1
不幸的是,BadPadding: Encryption Error
当我在 Java 中解密我的加密字符串时,我发现了。到目前为止,我发现 Java 用于Mode
加密/解密字符串,但Mode
在 iOS/Swift 中没有。请让我知道我应该使用哪种算法在 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));
}
}