GoLang使用AES CBC加密解密

AES CBC实现:

package ciphers

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

type AesCrypt struct {
	Key []byte
	Iv  []byte
}

func (a *AesCrypt) Encrypt(data []byte) ([]byte, error) {
	aesBlockEncrypt, err := aes.NewCipher(a.Key)
	if err != nil {
		println(err.Error())
		return nil, err
	}

	content := pKCS5Padding(data, aesBlockEncrypt.BlockSize())
	cipherBytes := make([]byte, len(content))
	aesEncrypt := cipher.NewCBCEncrypter(aesBlockEncrypt, a.Iv)
	aesEncrypt.CryptBlocks(cipherBytes, content)
	return cipherBytes, nil
}

func (a *AesCrypt) Decrypt(src []byte) (data []byte, err error) {
	decrypted := make([]byte, len(src))
	var aesBlockDecrypt cipher.Block
	aesBlockDecrypt, err = aes.NewCipher(a.Key)
	if err != nil {
		println(err.Error())
		return nil, err
	}
	aesDecrypt := cipher.NewCBCDecrypter(aesBlockDecrypt, a.Iv)
	aesDecrypt.CryptBlocks(decrypted, src)
	return pKCS5Trimming(decrypted), nil
}

func pKCS5Padding(cipherText []byte, blockSize int) []byte {
	padding := blockSize - len(cipherText)%blockSize
	padText := bytes.Repeat([]byte{byte(padding)}, padding)
	return append(cipherText, padText...)
}

func pKCS5Trimming(encrypt []byte) []byte {
	padding := encrypt[len(encrypt)-1]
	return encrypt[:len(encrypt)-int(padding)]
}
View Code

测试代码:

package ciphers

import (
	"encoding/base64"
	"fmt"
	"testing"
)

func TestAesCrypt_Encrypt(t *testing.T) {
	var aesCrypt = AesCrypt{
		Key: []byte("ABCDEFGHIJKLMNOP"),
		Iv:  []byte{0x12, 0x34, 0x56, 0x78, 0x9A, 0xBC, 0xDE, 0xF0, 0x12, 0x34, 0x56, 0x78, 0x9A, 0xBC, 0xDE, 0xF0},
	}

	var text = "areful1997"
	result, err := aesCrypt.Encrypt([]byte(text))
	if err != nil {
		fmt.Println(err)
		return
	}

	pass64 := base64.StdEncoding.EncodeToString(result)
	fmt.Println(pass64)
}

func TestAesCrypt_Decrypt(t *testing.T) {
	var aesCrypt = AesCrypt{
		Key: []byte("ABCDEFGHIJKLMNOP"),
		Iv:  []byte{0x12, 0x34, 0x56, 0x78, 0x9A, 0xBC, 0xDE, 0xF0, 0x12, 0x34, 0x56, 0x78, 0x9A, 0xBC, 0xDE, 0xF0},
	}

	pass64 := "8oAbgUpjro+xwDuxiGDFTQ=="
	bytesPass, err := base64.StdEncoding.DecodeString(pass64)
	if err != nil {
		fmt.Println(err)
		return
	}

	plainText, err := aesCrypt.Decrypt(bytesPass)
	if err != nil {
		fmt.Println(err)
		return
	}

	fmt.Println(string(plainText))
}
View Code

 

转载于:https://www.cnblogs.com/areful/p/11107119.html

你可能感兴趣的:(golang)