我正在尝试从base64解码以下字符串而没有任何退出。它总是返回零。我试图将NSDataBase64DecodingOptions更改为IgnoreUnknowCharanters,但它也不起作用。我也尝试删除填充,就像这个答案说swift base64 decoding returns nil但是我的字符串的长度可以被4整除所以它不起作用。
的字符串
PY5ehymWfQKExWxPyOImGiQkxNjyuBREmOXtQdePVpuH9PFzizaO+WTuM1sLouTQPz5UO7csloC9GjOFqkq4POmlB9d3mMJGLB2pVCNs8t9EejOcjV4fRHaITkmfMfVbizCnTvHGBwLWXjLc7gwyhu2+S9qw0NXc5jw6EdEk+zuesrdwLgqws0hDqFSoVw57+CnvUmgXwtNfKP4p64mJ9inH/0xAMarCc5N4Wjz/zmlTyd2PoDFUC/iLdZ7csau7X2M=
选项1
if let decodedData = NSData(base64EncodedString: base64String, options: NSDataBase64DecodingOptions.IgnoreUnknownCharacters),
let decodedString = NSString(data: decodedData, encoding: NSUTF8StringEncoding) {
print(decodedString) // foo
}
选项2
if let decodedData = NSData(base64EncodedString: pnpData, options: NSDataBase64DecodingOptions.init(rawValue: 0)),
let decodedString = NSString(data: decodedData, encoding: NSUTF8StringEncoding) {
print(decodedString) // foo
}
希望你能帮助我。谢谢!
答案 0 :(得分:0)
我上串怀疑 “PY5ehymWfQKExWxPyOImGiQkxNjyuBREmOXtQdePVpuH9PFzizaO + WTuM1sLouTQPz5UO7csloC9GjOFqkq4POmlB9d3mMJGLB2pVCNs8t9EejOcjV4fRHaITkmfMfVbizCnTvHGBwLWXjLc7gwyhu2 + S9qw0NXc5jw6EdEk + zuesrdwLgqws0hDqFSoVw57 + CnvUmgXwtNfKP4p64mJ9inH / 0xAMarCc5N4Wjz / zmlTyd2PoDFUC / iLdZ7csau7X2M =”
这很有效,该字符串也会进行编码和解码
let utf8str = "PY5ehymWfQKExWxPyOImGiQkxNjyuBREmOXtQdePVpuH9PFzizaO+WTuM1sLouTQPz5UO7csloC9GjOFqkq4POmlB9d3mMJGLB2pVCNs8t9EejOcjV4fRHaITkmfMfVbizCnTvHGBwLWXjLc7gwyhu2+S9qw0NXc5jw6EdEk+zuesrdwLgqws0hDqFSoVw57+CnvUmgXwtNfKP4p64mJ9inH/0xAMarCc5N4Wjz/zmlTyd2PoDFUC/iLdZ7csau7X2M=".dataUsingEncoding(NSUTF8StringEncoding)
let base64Encoded = utf8str?.base64EncodedStringWithOptions(NSDataBase64EncodingOptions(rawValue: 0))
let encodedString : String = base64Encoded!
print(encodedString) // my encoded data
let decodedData = NSData(base64EncodedString: encodedString, options:NSDataBase64DecodingOptions(rawValue: 0))
let decodedString : String = String(data: decodedData!, encoding: NSUTF8StringEncoding)!
print(decodedString) // my plain data
这不起作用,解码后的字符串不会被编码
let decodedData = NSData(base64EncodedString: "PY5ehymWfQKExWxPyOImGiQkxNjyuBREmOXtQdePVpuH9PFzizaO+WTuM1sLouTQPz5UO7csloC9GjOFqkq4POmlB9d3mMJGLB2pVCNs8t9EejOcjV4fRHaITkmfMfVbizCnTvHGBwLWXjLc7gwyhu2+S9qw0NXc5jw6EdEk+zuesrdwLgqws0hDqFSoVw57+CnvUmgXwtNfKP4p64mJ9inH/0xAMarCc5N4Wjz/zmlTyd2PoDFUC/iLdZ7csau7X2M=", options:NSDataBase64DecodingOptions(rawValue: 0))
let decodedString : String = String(data: decodedData!, encoding: NSUTF8StringEncoding)!
print(decodedString) // my plain data
这可能是理由,请查看https://www.base64decode.org/
虽然字符串中不能保留特殊字符。
答案 1 :(得分:0)
也许你可以按照这个
https://github.com/krzyzanowskim/CryptoSwift#data-padding
并使用以下方法进行解码(我猜你的字符串是由aes cbc和base64编码的,如果你想解码这个字符串,你必须知道编码键和iv)
"PY5ehymWfQKExWxPyOImGiQkxNjyuBREmOXtQdePVpuH9PFzizaO+WTuM1sLouTQPz5UO7csloC9GjOFqkq4POmlB9d3mMJGLB2pVCNs8t9EejOcjV4fRHaITkmfMfVbizCnTvHGBwLWXjLc7gwyhu2+S9qw0NXc5jw6EdEk+zuesrdwLgqws0hDqFSoVw57+CnvUmgXwtNfKP4p64mJ9inH/0xAMarCc5N4Wjz/zmlTyd2PoDFUC/iLdZ7csau7X2M=".decryptBase64ToString(cipher)
答案 2 :(得分:0)