我想使用DES在我的iOS应用程序中加密和解密字符串(是的,我知道DES不再安全,但应用程序接收并向使用它的BLE模块发送消息)。 我成功地为Common Crypto创建了一个桥接头,我发现它用于加密并适用于DES和swift 3 Asynchronous encryption in Swift:
func testCrypt(data:NSData, keyData:NSData, ivData:NSData, operation:CCOperation) -> NSData? {
let keyBytes = keyData.bytes.assumingMemoryBound(to: UInt8.self)
print("keyLength = \(keyData.length), keyData = \(keyData)")
let ivBytes = ivData.bytes.assumingMemoryBound(to: UInt8.self)
print("ivLength = \(ivData.length), ivData = \(ivData)")
let dataLength = Int(data.length)
let dataBytes = data.bytes.assumingMemoryBound(to: UInt8.self)
print("dataLength = \(dataLength), data = \(data)")
let cryptData: NSMutableData! = NSMutableData(length: Int(dataLength) + kCCBlockSizeDES)
let cryptPointer = cryptData.mutableBytes.assumingMemoryBound(to: UInt8.self)
let cryptLength = size_t(cryptData.length)
let keyLength = size_t(kCCKeySizeDES)
let algoritm: CCAlgorithm = UInt32(kCCAlgorithmDES)
let options: CCOptions = UInt32(kCCOptionECBMode)
var numBytesEncrypted :size_t = 0
let cryptStatus = CCCrypt(operation,
algoritm,
options,
keyBytes, keyLength,
ivBytes,
dataBytes, dataLength,
cryptPointer, cryptLength,
&numBytesEncrypted)
return cryptData;
}
函数调用和参数:
override func viewDidLoad() {
super.viewDidLoad()
let ivString = "Use a random iv!"
let ivData = (ivString as NSString).data(using: String.Encoding.utf8.rawValue) as NSData!
let key = Data.init(bytes: [0x23, 0x12, 0x4d, 0x89, 0x88, 0x34, 0xCf, 0x50])
let keyData = NSData.init(data: key)
let message = "Don´t try to read this text. Top Secret Stuff"
let data = (message as NSString).data(using: String.Encoding.utf8.rawValue) as NSData!
print("data: \(data)")
if let encryptedData = testCrypt(data: data!, keyData:keyData, ivData: ivData!, operation:UInt32(kCCEncrypt)) {
print("encryptedData: \(encryptedData)")
if let decryptedData = testCrypt(data: encryptedData, keyData:keyData, ivData: ivData!, operation:UInt32(kCCDecrypt)) {
let dec = Data.init(referencing: decryptedData)
print("decryptedData: \(decryptedData))")
}
}
}
预期结果=< 446f6ec2 b4742074 72792074 6f207265 61642074 68697320 74657874 2e20546f 70205365 63726574 20537475 6666>
encryptedData:< 6081ada9 0487c0a5 35e542bd e9600861 4250a693 65573337 39df5525 66c40cd8 b358bf6a d9837f9c 00000000 00000000 00000000 0000>
decryptedData =< 446f6ec2 b4742074 72792074 6f207265 61642074 68697320 74657874 2e20546f 70205365 63726574 e0456e88 3f896b9b 00000000 00000000 00000000 0000>
为什么解密只返回部分正确的结果?
答案 0 :(得分:0)
所以似乎没有可用的NoPadding选项,最后我刚从'cryptData'初始化中删除了'+ kCCBlockSizeDES',并在加密它之前将'0'字符添加到我的字符串中以达到正确的大小(例如长度) 8)的倍数,然后在解密后我刚删除零以获得原始字符串。