我在我的应用程序中使用 RNCryptor 。我使用密码为纯文本生成了一个加密字符串,当我尝试使用密码解密加密字符串时,它不会给我原始的纯文本,而是给了我一些随机字符串。
我想我在字符串编码/解码中遗漏了一些内容,但我不确定我在这里缺少什么。
你能指导我解决这个问题吗?
代码
func encrypt(plainText : String, password: String) -> String {
let data: Data = plainText.data(using: .utf8)!
let encryptedData = RNCryptor.encrypt(data: data, withPassword: password)
let encryptedString : String = encryptedData.base64EncodedString(options: Data.Base64EncodingOptions.lineLength76Characters)
return encryptedString
}
func decrypt(encryptedText : String, password: String) -> String {
do {
let data: Data = Data.init(base64Encoded: encryptedText, options: NSData.Base64DecodingOptions.ignoreUnknownCharacters)!
let decryptedData = try RNCryptor.decrypt(data: data, withPassword: password)
let decryptedString : String = decryptedData.base64EncodedString(options: Data.Base64EncodingOptions.lineLength76Characters)
return decryptedString
}
catch {
return "FAILED"
}
}
let plainText = "123456789"
let password = "ABCDEFGHIJ"
let encryptedText = self.encrypt(plainText: plainText, password: password)
let decryptedText = self.decrypt(encryptedText: encryptedText, password: password)
print("ENCRYPTED TEXT : \(encryptedText)")
print("DECRYPTED TEXT : \(decryptedText)")
加密文本:AwEsB6wlUSIJ31TAbaeAjVXP272zW89aa2rR9v6zYWwKUf6Hs5GSHekMKQT + n0vw6jMtjsQVhtzO 8AcqGpTLrQ9YR0PUS07P + 8HboCp6Ge8UxQ ==
解密文本:MTIzNDU2Nzg5
答案 0 :(得分:2)
试试如下,现在它对我有效。
func encrypt(plainText : String, password: String) -> String {
let data: Data = plainText.data(using: .utf8)!
let encryptedData = RNCryptor.encrypt(data: data, withPassword: password)
let encryptedString : String = encryptedData.base64EncodedString() // getting base64encoded string of encrypted data.
return encryptedString
}
func decrypt(encryptedText : String, password: String) -> String {
do {
let data: Data = Data(base64Encoded: encryptedText)! // Just get data from encrypted base64Encoded string.
let decryptedData = try RNCryptor.decrypt(data: data, withPassword: password)
let decryptedString = String(data: decryptedData, encoding: .utf8) // Getting original string, using same .utf8 encoding option,which we used for encryption.
return decryptedString ?? ""
}
catch {
return "FAILED"
}
}
感谢。
答案 1 :(得分:0)
在解密功能中,您必须首先解码Base64而不是RNC。