4

Go加密解密之AES

 3 years ago
source link: http://blog.studygolang.com/2013/01/go%e5%8a%a0%e5%af%86%e8%a7%a3%e5%af%86%e4%b9%8baes/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

一、AES简介

密码学中的高级加密标准(Advanced Encryption Standard,AES),又称Rijndael加密法,这个标准用来替代原先的DES。AES加密数据块分组长度必须为128bit,密钥长度可以是128bit、192bit、256bit中的任意一个。
AES也是对称加密算法。关于该算法的更多信息可以参考 http://baike.baidu.com/view/2310288.htm

二、Go AES加密解密

学会了DES加密后,AES加密相当简单。除了第一步,将crypto/des包换为crypto/aes外,其他几乎一样。当然,需要注意的是密钥长度和iv的长度。

DES中blocksize是8byte,AES中则是16byte(128bit)。

AES包中,使用函数func NewCipher(key []byte) (cipher.Block, error),和DES一样(包不一样)

由于详细讲解了DES之后,Goes实现AES加解密十分简单,这里只给出关键代码,不做详细解释

1func AesEncrypt(origData, key []byte) ([]byte, error) {
2block, err := aes.NewCipher(key)
3if err != nil {
4return nil, err
5}
6blockSize := block.BlockSize()
7origData = PKCS5Padding(origData, blockSize)
8// origData = ZeroPadding(origData, block.BlockSize())
9blockMode := cipher.NewCBCEncrypter(block, key[:blockSize])
10crypted := make([]byte, len(origData))
11// 根据CryptBlocks方法的说明,如下方式初始化crypted也可以
12// crypted := origData
13blockMode.CryptBlocks(crypted, origData)
14return crypted, nil
15}
16 
17func AesDecrypt(crypted, key []byte) ([]byte, error) {
18block, err := aes.NewCipher(key)
19if err != nil {
20return nil, err
21}
22blockSize := block.BlockSize()
23blockMode := cipher.NewCBCDecrypter(block, key[:blockSize])
24origData := make([]byte, len(crypted))
25// origData := crypted
26blockMode.CryptBlocks(origData, crypted)
27origData = PKCS5UnPadding(origData)
28// origData = ZeroUnPadding(origData)
29return origData, nil
30}

对比上篇DES加密的代码,几乎一样。

三、和其他语言交互:加解密

和DES一样,实现了PHP、Java版本。具体代码在github上

欢迎关注我的公众号:

polarisxu-qrcode-soso-s.png

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK