一、 Swift AES ECB Padding .pkcs7 加密解密,密钥字节数不够16位补全:
// AES加密
internal func aes_encrypt(_ str:String, _ aes_key:String) -> String{
//AES ECB Padding pkcs7需要密钥长度16字节倍数,此处为不够16位补全
var keyBytes = aes_key.bytes
let letter = 0x00
let diffByteNum = 16 - keyBytes.count
if diffByteNum > 0 {
for _ in 0..<diffByteNum {
keyBytes.append(UInt8(letter))
}
}
var encryptedStr = ""
do {// AES encrypt
let encrypted = try AES(key: keyBytes, blockMode: ECB(), padding: .pkcs7).encrypt(str.bytes);
let data = Data(base64Encoded: Data(encrypted), options: .ignoreUnknownCharacters)
//加密结果从data转成string 转换失败 返回""
encryptedStr = String(bytes: data!.bytes, encoding: .utf8) ?? ""
} catch {
print(error.localizedDescription)
}
return encryptedStr
}
// AES解密
internal func aes_decrypt(_ str:String , _ aes_key:String) -> String{
//decode base64
let data = Data(base64Encoded: str, options: .ignoreUnknownCharacters)!
//AES ECB Padding pkcs7需要密钥长度16字节倍数,此处为不够16位补全
var keyBytes = aes_key.bytes
let letter = 0x00
let diffByteNum = 16 - keyBytes.count
if diffByteNum > 0 {
for _ in 0..<diffByteNum {
keyBytes.append(UInt8(letter))
}
}
var decrypted: [UInt8] = []
do {
// decode AES
decrypted = try AES(key: keyBytes, blockMode: ECB(), padding: .pkcs7).decrypt(data.bytes);
} catch {
print(error.localizedDescription)
}
//解密结果从data转成string 转换失败 返回""
return String(bytes: Data(decrypted).bytes, encoding: .utf8) ?? ""
}
网友评论