密码学-AES

AES算法

在AES算法中的秘钥可以是16位,24位或者32位,在加密和解密的过程中要使用同一个秘钥。

package main

import (
    "bytes"
    "crypto/aes"
    "crypto/cipher"
    "fmt"
)

func main() {
    key16 := []byte("1234567890123456")
    encryptcode := AesEncrypt([]byte("sanyang"), key16)
    fmt.Printf("%x\n", encryptcode)
    decryptcode := AesDeEncrypt(encryptcode, key16)
    fmt.Println(string(decryptcode))
}

//补码
func PKCS7Padding(ciphertext []byte, blocksize int) []byte {
    padding := blocksize - len(ciphertext)%blocksize
    padtext := bytes.Repeat([]byte{byte(padding)}, padding)

    return append(ciphertext, padtext...)
}

//去码
func PKCS7UnPadding(origData []byte) []byte {
    lenth := len(origData)
    unpadding := int(origData[lenth-1])

    return origData[:(lenth - unpadding)]
}

//加密
func AesEncrypt(origData []byte, key []byte) []byte {
    //分组秘钥
    block, _ := aes.NewCipher(key)
    //获得秘钥块长度
    blocksize := block.BlockSize()
    origData = PKCS7Padding(origData, blocksize)
    //设置加密方式
    blockMode := cipher.NewCBCEncrypter(block, key[:blocksize])
    //创建数组
    cryted := make([]byte, len(origData))
    //加密
    blockMode.CryptBlocks(cryted, origData)
    return cryted
}
//解密
func AesDeEncrypt(cryted, key []byte) []byte {
    //分组秘钥
    block, _ := aes.NewCipher(key)
    //获得秘钥块长度
    blocksize := block.BlockSize()
    //设置解密方式
    blockMode := cipher.NewCBCDecrypter(block, key[:blocksize])
    //创建数组
    origData := make([]byte, len(cryted))
    //解密
    blockMode.CryptBlocks(origData, cryted)
    origData = PKCS7UnPadding(origData)
    return origData
}

猜你喜欢

转载自blog.csdn.net/qq_37133717/article/details/80356391