美文网首页
2023-02-22

2023-02-22

作者: 娜尔丶 | 来源:发表于2023-02-21 10:19 被阅读0次

    一、 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) ?? ""
    }
    

    相关文章

      网友评论

          本文标题:2023-02-22

          本文链接:https://www.haomeiwen.com/subject/rgmnkdtx.html