我有一些数据将在 JSON 响应中加密的场景。所以我尝试了一些库来快速解密。但最终我没能做到。
所以我尝试了这个库WebCrypto:https ://github.com/etienne-martin/WebCrypto.swift
哪个工作正常,但调用是异步的,我需要同步。
早些时候我试过这些
- RNCryptor:https ://github.com/RNCryptor/RNCryptor
- CryptoSwift:https ://github.com/krzyzanowskim/CryptoSwift
RNCryptor:代码
import RNCryptor
class DemoRNCryptor {
class func run() {
// Encryption
let data = "my message is not ready".data(using: String.Encoding.utf8)!
let password = "MySecretKey12345"
let encryptedData = RNCryptor.encrypt(data: data, withPassword: password)
print("RNCryptor enc:", encryptedData.hexString)
// Decryption
do {
let originalData = try RNCryptor.decrypt(data: encryptedData, withPassword: password)
let dd = String(data: originalData, encoding: .utf8)
print("RNCryptor dec:", dd)
} catch {
print(error)
}
}
}
CryptoSwift:代码
import CryptoSwift
extension String {
func aesEncryptCS(key: String) throws -> String {
var result = ""
do {
let key: [UInt8] = Array(key.utf8) as [UInt8]
let aes = try AES(key: key, blockMode: ECB(), padding: .pkcs5) // AES128 .ECB pkcs7
let encrypted = try aes.encrypt(Array(self.utf8))
result = encrypted.toBase64()!
print("AES Encryption Result: \(result)")
} catch {
print("Error: \(error)")
}
return result
}
func aesDecryptCS(key: String) throws -> String {
var result = ""
do {
let encrypted = self
let key: [UInt8] = Array(key.utf8) as [UInt8]
let aes = try AES(key: key, blockMode: ECB(), padding: .pkcs5) // AES128 .ECB pkcs7
let decrypted = try aes.decrypt(Array(base64: encrypted))
result = String(data: Data(decrypted), encoding: .utf8) ?? ""
print("AES Decryption Result: \(result)")
} catch {
print("Error: \(error)")
}
return result
}
}
我有一个密钥 = “消息” 和加密文本(“我的消息尚未准备好”) =“ U2FsdGVkX187YbST7kZBjdhI6tGa2YQE5e3bS4WNhaXgi0iy//q5TOfR/q6Sc1Lx ”
如何使用上述两个库中的任何一个来解密此字符串?
我总是得到零或无效的密钥大小。