码迷,mamicode.com
首页 > 其他好文 > 详细

熟悉一下GO的AES加密库

时间:2016-03-01 20:45:11      阅读:281      评论:0      收藏:0      [点我收藏+]

标签:

 

package main

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

type ConnAes struct {
    key      string
    keyBlock cipher.Block
    iv       string
}

func NewConnAes(key string, iv string) (ca ConnAes, err error) {
    if len(iv) != aes.BlockSize {
        return ca, errors.New("error iv size not 16")
    }
    ca.key = key
    ca.iv = iv
    ca.keyBlock, err = aes.NewCipher([]byte(key))
    return ca, err
}
//加密
func (ca *ConnAes) Encrypt(src []byte) ([]byte, error) {
    paddinglen := aes.BlockSize - (len(src) % aes.BlockSize)
    for i := 0; i < paddinglen; i++ {
        src = append(src, byte(paddinglen))
    }
    enbuf := make([]byte, len(src))
    cbce := cipher.NewCBCEncrypter(ca.keyBlock, []byte(iv))
    cbce.CryptBlocks(enbuf, src)
    return enbuf, nil
}
//解密
func (ca *ConnAes) Decrypt(src []byte) ([]byte, error) {

    if (len(src) < aes.BlockSize) || (len(src)%aes.BlockSize != 0) {
        return nil, errors.New("error encrypt data size")
    }

    debuf := make([]byte, len(src))
    cbcd := cipher.NewCBCDecrypter(ca.keyBlock, []byte(iv))
    cbcd.CryptBlocks(debuf, src)
    paddinglen := int(debuf[len(src)-1])
    if paddinglen > 16 {
        return nil, errors.New("error encrypt data size")
    }
    return debuf[:len(src)-paddinglen], nil
}

熟悉一下GO的AES加密库

标签:

原文地址:http://www.cnblogs.com/hgd7123/p/5232383.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!