2

I am using RNCryptor in my application. I generated an encrypted string for a plain text using a password and when I try to decrypt the encrypted string using a password, it does not give me the original plain text instead it gave me some random string.

I guess I am missing something in string encoding/decoding but I am not sure what I am missing here.

Can you please guide me to fix this?

Code

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)")

ENCRYPTED TEXT : AwEsB6wlUSIJ31TAbaeAjVXP272zW89aa2rR9v6zYWwKUf6Hs5GSHekMKQT+n0vw6jMtjsQVhtzO 8AcqGpTLrQ9YR0PUS07P+8HboCp6Ge8UxQ==

DECRYPTED TEXT : MTIzNDU2Nzg5

4

2 回答 2

5

Just try like below, its worked for me now.

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"
        }
}

Thanks.

于 2018-01-10T17:57:37.870 回答
0

In decrypt func you must decode Base64 first than RNC.

于 2018-01-10T13:53:56.613 回答