加密堆栈溢出问题
我有一个由 openssl 使用 aes256 和 2048 但加密生成的私钥/公钥对。在服务器上,我可以使用 openssl 以及私钥和公钥来加密和解密数据,没有任何问题。 我在 Swift 中加密数据根本没有成功。我尝试了几种方法,数据似乎已加密,但当我尝试在服务器上解密时,它不断告诉我
rsa routines:rsa_ossl_private_decrypt:data greater than mod len:crypto\rsa\rsa_ossl.c:407
我还没有找到任何关于如何在 Swift 中做到这一点的真正好的资源,但这就是我所拥有的; (忽略强力展开。它们只是用于测试)
private func createSecKey() -> SecKey {
// Remove headers and footers from the PEM, leaving us with DER encoded data split by new lines
[
"-----BEGIN RSA PUBLIC KEY-----", "-----END RSA PUBLIC KEY-----",
"-----BEGIN PUBLIC KEY-----", "-----END PUBLIC KEY-----"
].forEach { publicKey = publicKey.replacingOccurrences(of: $0, with: "") }
// Construct DER data from the remaining PEM data
let der = Data(base64Encoded: publicKey, options: .ignoreUnknownCharacters)!
let attributes: [String: Any] = [
String(kSecAttrKeyType): kSecAttrKeyTypeRSA,
String(kSecAttrKeyClass): kSecAttrKeyClassPublic,
String(kSecAttrKeySizeInBits): der.count * 8
]
let key = SecKeyCreateWithData(der as CFData, attributes as CFDictionary, nil)!
return key
}
private func encryptMessageData(secKey: SecKey, message: String) {
print(aesKeyPair)
// An example message to encrypt
let messageData = message.data(using: .utf8)!
// Perform the actual encryption
let encryptedMessage = SecKeyCreateEncryptedData(secKey, .rsaEncryptionOAEPSHA256, messageData as CFData, nil)! as Data
print("=====Encrypted Message Below=====")
print(encryptedMessage.map { String(format: "%02x", $0) }.joined())
self.encryptedAESKey.text = cipherText.map { String(format: "%02x", $0) }.joined()
}
我尝试将加密响应编码为 Base64 并解密;
let base64Data = encryptedMessage.base64EncodedData(options: .endLineWithLineFeed)
当我尝试在服务器上解密时;
openssl pkeyutl -decrypt -inkey tvde_private.pem -in message.decoded > message.txt -pkeyopt rsa_padding_mode:oaep
这就是我得到的地方
Public Key operation error
501A0000:error:02000079:rsa routines:RSA_padding_check_PKCS1_OAEP_mgf1:oaep decoding error:crypto\rsa\rsa_oaep.c:314:
我不知道这是否会让我更接近我的目标>
现在,我认为问题出在数据加密过程中;
let encryptedMessage = SecKeyCreateEncryptedData(secKey, .rsaEncryptionOAEPSHA256, messageData as CFData, nil)! as Data
我真的不知道这里该选择哪种算法。我已经尝试过 .rsaEncryptionOAEPSHA256 和 .rsaEncryptionOAEPSHA256AESGCM 但老实说我不知道 SecKeyAlgorithm 中列出的所有算法是什么,并且我生成的密钥只是使用 aes256 和 2048 位加密完成的。
没有人有什么建议吗?
当然,在花了几个小时没有想到任何东西之后,我可以看到另一个对我有帮助的 SO 帖子:openssl 填充错误。我需要将算法更改为 .rsaEncryptionPKCS1 进行加密。然后我对它进行 Base64 编码,将其关闭并能够在服务器上解密。