美文网首页Swift
CBC 加密解密

CBC 加密解密

作者: 小奉不在乎 | 来源:发表于2023-01-29 13:54 被阅读0次
import Foundation
import CryptoKit
import CommonCrypto

class PTECKeyUtil: NSObject {
    
    static let share = PTECKeyUtil()
    
    /// 在X25519上执行椭圆曲线Diffie-Hellmann密钥协议。
    open class func getShareKey(from peerPubKey: Data, privateKey: Curve25519.KeyAgreement.PrivateKey) throws -> SharedSecret {
        let theirKey = try Curve25519.KeyAgreement.PublicKey(rawRepresentation: peerPubKey)
        return try privateKey.sharedSecretFromKeyAgreement(with: theirKey)
    }
    
    // MARK: cbc 加密
    /// cbc 加密
    open class func encryptCBCMode(_ data: Data, key: Data, iv: Data) -> Data? {
        
        let input_bytes = data.bytes
        let key_bytes = key.bytes
        let iv_bytes = iv.bytes
        
        var encrypt_length = input_bytes.count + kCCBlockSizeAES128
        var encrypt_bytes = [UInt8](repeating: 0, count: encrypt_length)
        // 加密解密不同的地方 加密是:kCCEncrypt  解密是kCCDecrypt
        let status = CCCrypt(UInt32(kCCEncrypt), UInt32(kCCAlgorithmAES128), UInt32(kCCOptionPKCS7Padding),
                             key_bytes, key.count,
                             iv_bytes,
                             input_bytes, input_bytes.count,
                             &encrypt_bytes, encrypt_bytes.count,
                             &encrypt_length)
        if status == Int32(kCCSuccess) {
            return Data.init(bytes: encrypt_bytes, count: encrypt_length)
        } else {
            PTLog("加密密失败")
        }
        return nil
    }
    
    
    // MARK: cbc 解密
    /// cbc 解密
    open class func decryptCBCMode(_ data: Data, key: Data, iv: Data) -> Data? {

        let input_bytes = data.bytes
        let key_bytes = key.bytes
        let iv_bytes = iv.bytes
        
        var encrypt_length = input_bytes.count + kCCBlockSizeAES128
        var encrypt_bytes = [UInt8](repeating: 0, count: encrypt_length)
        
        let status = CCCrypt(UInt32(kCCDecrypt), UInt32(kCCAlgorithmAES128), UInt32(kCCOptionPKCS7Padding),
                             key_bytes, key.count,
                             iv_bytes,
                             input_bytes, input_bytes.count,
                             &encrypt_bytes, encrypt_bytes.count,
                             &encrypt_length)
        if status == Int32(kCCSuccess) {
            return Data.init(bytes: encrypt_bytes, count: encrypt_length)
        } else {
            PTLog("解密失败")
        }
        return nil
    }
}

相关文章

网友评论

    本文标题:CBC 加密解密

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