古老的榕树

Go 常用 AES 加密解密代码

潘军杰 发表于 2018-05-10 15:19 阅读(3122) 评论(0) 赞(0)

Go 中常用到 AES 对称加密解密算法,以下把关键代码分享出来:


// AES 加密 AES-128。key string 长度:16, 24, 32 bytes 对应 AES-128, AES-192, AES-256
func AesEncrypt(origData, key []byte) ([]byte, error) {
	block, err := aes.NewCipher(key)
	if err != nil {
		return nil, err
	}

	blockSize := block.BlockSize()
	blockMode := cipher.NewCBCEncrypter(block, key[:blockSize])
	origData = PKCS5Padding(origData, blockSize)

	if origData == nil {
		return nil, errors.New("origData is nil")
	}

	cryptData := make([]byte, len(origData))
	blockMode.CryptBlocks(cryptData, origData)
	return cryptData, nil
}


// AES 解密 key string 长度:16, 24, 32 bytes 对应 AES-128, AES-192, AES-256
func AesDecrypt(cryptData, key []byte) ([]byte, error) {
	block, err := aes.NewCipher(key)
	if err != nil {
		return nil, err
	}

	blockSize := block.BlockSize()
	blockMode := cipher.NewCBCDecrypter(block, key[:blockSize])
	origData := make([]byte, len(cryptData))
	blockMode.CryptBlocks(origData, cryptData)
	origData = PKCS5UnPadding(origData)
	if origData == nil {
		return nil, errors.New("origData is nil")
	}

	return origData, nil
}


func PKCS5Padding(ciphertext []byte, blockSize int) []byte {
	if ciphertext == nil || blockSize <= 0 {
		return nil
	}

	padding := blockSize - len(ciphertext)%blockSize
	if padding <= 0 {
		return nil
	}

	padtext := bytes.Repeat([]byte{byte(padding)}, padding)
	return append(ciphertext, padtext...)
}


func PKCS5UnPadding(origData []byte) []byte {
	if origData == nil {
		return nil
	}

	length := len(origData)
	if length <= 0 {
		return []byte{}
	}

	unpadding := int(origData[length-1])
	return origData[:(length - unpadding)]
}



标签: Go AES 加密 解密
0 条网友评论

哇~~~ 竟然还没有评论!

称呼*
邮箱*
内容*
验证码*
验证码 看不清换张