解码base64 + decrypt - Swift

时间:2017-04-26 22:18:23

标签: ios swift encryption swift2

let originalMsg:String = "THIS IS A TEST"
let sessionData = originalMsg.dataUsingEncoding(NSUTF8StringEncoding)        
var encryptedPublic:NSData = RNCryptor.encryptData(sessionData!, password: ProjectConstants.MessageEncrypt.PUBLIC_KEY)
var base64EncodedPublic:NSData = encryptedPublic.base64EncodedDataWithOptions([])
var encryptedPrivate = RNCryptor.encryptData(base64EncodedPublic, password: privateKey)
var base64EncodedString:String = encryptedPrivate.base64EncodedStringWithOptions([])

如何解码+解密base64EncodedString以获取原始输入?我想我正在努力解决base64解码问题。

1 个答案:

答案 0 :(得分:2)

这是从Swift 2中的base64字符串获取UTF-8编码NSString的方法:

let decodedData = NSData(base64EncodedString: base64EncodedString,
                         options: NSDataBase64DecodingOptions.fromRaw(0)!)
let decodedString = NSString(data: decodedData, encoding: NSUTF8StringEncoding)

但是如果你想解密,你只需要数据:

do {
    let decodedData = NSData(base64EncodedString: base64EncodedString,
                         options: NSDataBase64DecodingOptions.fromRaw(0)!)
    let decryptedPrivate = RNDecryptor.decryptData(decodedData, password: privateKey)
    let decodedPrivate = NSData(base64EncodedData: decryptedPrivate,
                            options: NSDataBase64DecodingOptions.fromRaw(0)!)
    let decryptedPublic = RNDecryptor.decryptData(decodedPrivate, password: ProjectConstants.MessageEncrypt.PUBLIC_KEY)
    let decryptedMessage = NSString(data: decryptedPublic, encoding: NSUTF8StringEncoding) as String
} catch {
  // handle decryption errors...
}