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") // 待加密的數(shù)據(jù)
    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("解密結(jié)果:", 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("解密結(jié)果:", 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("解密結(jié)果:", string(decrypted))
}

// =================== CBC ======================
func AesEncryptCBC(origData []byte, key []byte) (encrypted []byte) {
    // 分組秘鑰
    // NewCipher該函數(shù)限制了輸入k的長(zhǎng)度必須為16, 24或者32
    block, _ := aes.NewCipher(key)
    blockSize := block.BlockSize()                              // 獲取秘鑰塊的長(zhǎng)度
    origData = pkcs5Padding(origData, blockSize)                // 補(bǔ)全碼
    blockMode := cipher.NewCBCEncrypter(block, key[:blockSize]) // 加密模式
    encrypted = make([]byte, len(origData))                     // 創(chuàng)建數(shù)組
    blockMode.CryptBlocks(encrypted, origData)                  // 加密
    return encrypted
}
func AesDecryptCBC(encrypted []byte, key []byte) (decrypted []byte) {
    block, _ := aes.NewCipher(key)                              // 分組秘鑰
    blockSize := block.BlockSize()                              // 獲取秘鑰塊的長(zhǎng)度
    blockMode := cipher.NewCBCDecrypter(block, key[:blockSize]) // 加密模式
    decrypted = make([]byte, len(encrypted))                    // 創(chuàng)建數(shù)組
    blockMode.CryptBlocks(decrypted, encrypted)                 // 解密
    decrypted = pkcs5UnPadding(decrypted)                       // 去除補(bǔ)全碼
    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
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容