我在iOS应用程序上使用“ CryptoSwift 1.0.0”和带有Xcode 10.2的Swift 5,CryptoSwift加密工作正常,PHP服务器的加密和解密也很好。
但是执行此方法时,我收到此错误:dataPaddingRequired
:
let cipher = try aes.decrypt(Array<UInt8>(cryptedData))
这是我的代码:
加密功能
static func cryptArtisan(strClair: String) -> [String:String] {
let key = generateStringKey()
var cryptedMessage = ""
var cryptedKey = ""
do {
let aes = try AES(key: Array<UInt8>(key.utf8), blockMode: ECB(), padding: .pkcs5) // aes128
let ciphertext = try aes.encrypt(Array(strClair.utf8))
cryptedMessage = ciphertext.toBase64()!
let publicKey = try PublicKey(derNamed: "public")
let clear = try ClearMessage(string: key, using: .utf8)
let encrypted = try clear.encrypted(with: publicKey, padding: .PKCS1)
cryptedKey = encrypted.base64String
} catch { }
cryptedMessage = cryptedMessage.replacingOccurrences(of: "+", with: "%2B")
cryptedKey = cryptedKey.replacingOccurrences(of: "+", with: "%2B")
return ["msg":cryptedMessage, "key":cryptedKey, "clairKey": key]
}
解密功能
static func decryptArtisan(cryptedMessage: String , key:String) -> String? {
var clairMessage:String? = nil;
if let cryptedData = Data(base64Encoded: cryptedMessage) {
do {
let aes = try AES(key: Array<UInt8>(key.utf8), blockMode: ECB(), padding: .pkcs5) // aes128
let cipher = try aes.decrypt(Array<UInt8>(cryptedData))
clairMessage = String(bytes: cipher, encoding: .utf8)
}catch{
print(error)
}
}
return clairMessage
}
如何解密服务器发送的加密消息?
更新: 我尝试不向NSError投错,我注意到抛出了dataPaddingRequired错误。