go aes各种加密方式(CBC/ECB/CFB)

package main

import (
    "bytes"
    "crypto/aes"
    "crypto/cipher"
    "crypto/rand"
    "encoding/base64"
    "encoding/hex"
    "io"
    "log"
)

func main() {
    origData := []byte("Hello World") // 待加密的数据
    key := []byte("ABCDEFGHIJKLMNOP") // 加密的密钥
    log.Println("原文:", string(origData))

    log.Println("------------------ CBC模式 --------------------")
    encrypted := AesEncryptCBC(origData, key)
    log.Println("密文(hex):", hex.EncodeToString(encrypted))
    log.Println("密文(base64):", base64.StdEncoding.EncodeToString(encrypted))
    decrypted := AesDecryptCBC(encrypted, key)
    log.Println("解密结果:", string(decrypted))

    log.Println("------------------ ECB模式 --------------------")
    encrypted = AesEncryptECB(origData, key)
    log.Println("密文(hex):", hex.EncodeToString(encrypted))
    log.Println("密文(base64):", base64.StdEncoding.EncodeToString(encrypted))
    decrypted = AesDecryptECB(encrypted, key)
    log.Println("解密结果:", string(decrypted))

    log.Println("------------------ CFB模式 --------------------")
    encrypted = AesEncryptCFB(origData, key)
    log.Println("密文(hex):", hex.EncodeToString(encrypted))
    log.Println("密文(base64):", base64.StdEncoding.EncodeToString(encrypted))
    decrypted = AesDecryptCFB(encrypted, key)
    log.Println("解密结果:", string(decrypted))
}

// =================== CBC ======================
func AesEncryptCBC(origData []byte, key []byte) (encrypted []byte) {
    // 分组秘钥
    // NewCipher该函数限制了输入k的长度必须为16, 24或者32
    block, _ := aes.NewCipher(key)
    blockSize := block.BlockSize()                              // 获取秘钥块的长度
    origData = pkcs5Padding(origData, blockSize)                // 补全码
    blockMode := cipher.NewCBCEncrypter(block, key[:blockSize]) // 加密模式
    encrypted = make([]byte, len(origData))                     // 创建数组
    blockMode.CryptBlocks(encrypted, origData)                  // 加密
    return encrypted
}
func AesDecryptCBC(encrypted []byte, key []byte) (decrypted []byte) {
    block, _ := aes.NewCipher(key)                              // 分组秘钥
    blockSize := block.BlockSize()                              // 获取秘钥块的长度
    blockMode := cipher.NewCBCDecrypter(block, key[:blockSize]) // 加密模式
    decrypted = make([]byte, len(encrypted))                    // 创建数组
    blockMode.CryptBlocks(decrypted, encrypted)                 // 解密
    decrypted = pkcs5UnPadding(decrypted)                       // 去除补全码
    return decrypted
}
func pkcs5Padding(ciphertext []byte, blockSize int) []byte {
    padding := blockSize - len(ciphertext)%blockSize
    padtext := bytes.Repeat([]byte{byte(padding)}, padding)
    return append(ciphertext, padtext...)
}
func pkcs5UnPadding(origData []byte) []byte {
    length := len(origData)
    unpadding := int(origData[length-1])
    return origData[:(length - unpadding)]
}

// =================== ECB ======================
func AesEncryptECB(origData []byte, key []byte) (encrypted []byte) {
    cipher, _ := aes.NewCipher(generateKey(key))
    length := (len(origData) + aes.BlockSize) / aes.BlockSize
    plain := make([]byte, length*aes.BlockSize)
    copy(plain, origData)
    pad := byte(len(plain) - len(origData))
    for i := len(origData); i < len(plain); i++ {
        plain[i] = pad
    }
    encrypted = make([]byte, len(plain))
    // 分组分块加密
    for bs, be := 0, cipher.BlockSize(); bs <= len(origData); bs, be = bs+cipher.BlockSize(), be+cipher.BlockSize() {
        cipher.Encrypt(encrypted[bs:be], plain[bs:be])
    }

    return encrypted
}
func AesDecryptECB(encrypted []byte, key []byte) (decrypted []byte) {
    cipher, _ := aes.NewCipher(generateKey(key))
    decrypted = make([]byte, len(encrypted))
    //
    for bs, be := 0, cipher.BlockSize(); bs < len(encrypted); bs, be = bs+cipher.BlockSize(), be+cipher.BlockSize() {
        cipher.Decrypt(decrypted[bs:be], encrypted[bs:be])
    }

    trim := 0
    if len(decrypted) > 0 {
        trim = len(decrypted) - int(decrypted[len(decrypted)-1])
    }

    return decrypted[:trim]
}
func generateKey(key []byte) (genKey []byte) {
    genKey = make([]byte, 16)
    copy(genKey, key)
    for i := 16; i < len(key); {
        for j := 0; j < 16 && i < len(key); j, i = j+1, i+1 {
            genKey[j] ^= key[i]
        }
    }
    return genKey
}

// =================== CFB ======================
func AesEncryptCFB(origData []byte, key []byte) (encrypted []byte) {
    block, err := aes.NewCipher(key)
    if err != nil {
        panic(err)
    }
    encrypted = make([]byte, aes.BlockSize+len(origData))
    iv := encrypted[:aes.BlockSize]
    if _, err := io.ReadFull(rand.Reader, iv); err != nil {
        panic(err)
    }
    stream := cipher.NewCFBEncrypter(block, iv)
    stream.XORKeyStream(encrypted[aes.BlockSize:], origData)
    return encrypted
}
func AesDecryptCFB(encrypted []byte, key []byte) (decrypted []byte) {
    block, _ := aes.NewCipher(key)
    if len(encrypted) < aes.BlockSize {
        panic("ciphertext too short")
    }
    iv := encrypted[:aes.BlockSize]
    encrypted = encrypted[aes.BlockSize:]

    stream := cipher.NewCFBDecrypter(block, iv)
    stream.XORKeyStream(encrypted, encrypted)
    return encrypted
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,我会尽力回答你的问题。首先,需要注意的是,OpenSSL库提供了AES算法的实现,但是并没有提供5种分组模式的加密和解密的具体实现,需要我们自己编写代码实现。 以下是C++中使用OpenSSL库实现5种分组模式的AES算法加密和解密的示例代码,其中使用了ECB分组模式作为示例(其他分组模式的实现方法类似): ```c++ #include <openssl/aes.h> #include <iostream> #include <cstring> using namespace std; // ECB模式加密 int aes_ecb_encrypt(unsigned char *in, int in_len, unsigned char *out, unsigned char *key, int key_len) { AES_KEY aes_key; if (AES_set_encrypt_key(key, key_len * 8, &aes_key) < 0) { return -1; } int padding = AES_BLOCK_SIZE - in_len % AES_BLOCK_SIZE; int new_len = in_len + padding; unsigned char *padded_in = new unsigned char[new_len]; memcpy(padded_in, in, in_len); memset(padded_in + in_len, padding, padding); for (int i = 0; i < new_len; i += AES_BLOCK_SIZE) { AES_encrypt(padded_in + i, out + i, &aes_key); } delete[] padded_in; return new_len; } // ECB模式解密 int aes_ecb_decrypt(unsigned char *in, int in_len, unsigned char *out, unsigned char *key, int key_len) { AES_KEY aes_key; if (AES_set_decrypt_key(key, key_len * 8, &aes_key) < 0) { return -1; } for (int i = 0; i < in_len; i += AES_BLOCK_SIZE) { AES_decrypt(in + i, out + i, &aes_key); } int padding = out[in_len - 1]; return in_len - padding; } int main() { unsigned char in[] = "Hello World!"; unsigned char key[] = "1234567890123456"; int in_len = strlen((char *)in); int key_len = strlen((char *)key); int out_len = in_len + AES_BLOCK_SIZE; unsigned char *out = new unsigned char[out_len]; memset(out, 0, out_len); // ECB模式加密 int encrypt_len = aes_ecb_encrypt(in, in_len, out, key, key_len); cout << "ECB encrypt: "; for (int i = 0; i < encrypt_len; i++) { printf("%02x", out[i]); } cout << endl; // ECB模式解密 unsigned char *decrypt_out = new unsigned char[out_len]; memset(decrypt_out, 0, out_len); int decrypt_len = aes_ecb_decrypt(out, encrypt_len, decrypt_out, key, key_len); cout << "ECB decrypt: " << string((char *)decrypt_out, decrypt_len) << endl; delete[] out; delete[] decrypt_out; return 0; } ``` 以上代码中使用了OpenSSL库的AES函数进行加密和解密。其中,ECB模式加密的函数为`aes_ecb_encrypt`,解密的函数为`aes_ecb_decrypt`。这些函数的实现方式可以类比实现其他分组模式的加密和解密函数。 需要注意的是,这里的输入和输出数据均为字节数组,需要根据具体应用进行调整。 希望以上代码对你有所帮助!

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值