2017-04-26 64 views
1
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解碼。解碼base64 +解密 - 斯威夫特

回答

2

這是你如何得到一個UTF-8從一個base64字符串斯威夫特2編碼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... 
}