Merge pull request #2 from vashstorm/master

Add crypto module
This commit is contained in:
fatedier 2016-02-03 14:38:46 +08:00
commit f427e3bc33
2 changed files with 134 additions and 0 deletions

View File

@ -0,0 +1,87 @@
package pcrypto
import (
"bytes"
"compress/gzip"
"crypto/aes"
"crypto/cipher"
"encoding/base64"
"encoding/hex"
"errors"
"fmt"
"io/ioutil"
)
type Pcrypto struct {
pkey []byte
paes cipher.Block
}
func (pc *Pcrypto) Init(key []byte) error {
var err error
pc.pkey = PKCS7Padding(key, aes.BlockSize)
pc.paes, err = aes.NewCipher(pc.pkey)
return err
}
func (pc *Pcrypto) Encrypto(src []byte) ([]byte, error) {
// aes
src = PKCS7Padding(src, aes.BlockSize)
blockMode := cipher.NewCBCEncrypter(pc.paes, pc.pkey)
crypted := make([]byte, len(src))
blockMode.CryptBlocks(crypted, src)
// gzip
var zbuf bytes.Buffer
zwr := gzip.NewWriter(&zbuf)
defer zwr.Close()
zwr.Write(crypted)
zwr.Flush()
// base64
return []byte(base64.StdEncoding.EncodeToString(zbuf.Bytes())), nil
}
func (pc *Pcrypto) Decrypto(str []byte) ([]byte, error) {
// base64
data, err := base64.StdEncoding.DecodeString(string(str))
if err != nil {
return nil, err
}
// gunzip
zbuf := bytes.NewBuffer(data)
zrd, _ := gzip.NewReader(zbuf)
defer zrd.Close()
data, _ = ioutil.ReadAll(zrd)
// aes
decryptText, err := hex.DecodeString(fmt.Sprintf("%x", data))
if err != nil {
return nil, err
}
if len(decryptText)%aes.BlockSize != 0 {
return nil, errors.New("crypto/cipher: ciphertext is not a multiple of the block size")
}
blockMode := cipher.NewCBCDecrypter(pc.paes, pc.pkey)
blockMode.CryptBlocks(decryptText, decryptText)
decryptText = PKCS7UnPadding(decryptText)
return decryptText, nil
}
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 {
length := len(origData)
unpadding := int(origData[length-1])
return origData[:(length - unpadding)]
}

View File

@ -0,0 +1,47 @@
package pcrypto
import (
"crypto/aes"
"fmt"
"testing"
)
func Test_Encrypto(t *testing.T) {
pp := new(Pcrypto)
pp.Init([]byte("Hana"))
res, err := pp.Encrypto([]byte("Just One Test!"))
if err != nil {
t.Error(err)
}
fmt.Printf("[%x]\n", res)
}
func Test_Decrypto(t *testing.T) {
pp := new(Pcrypto)
pp.Init([]byte("Hana"))
res, err := pp.Encrypto([]byte("Just One Test!"))
if err != nil {
t.Error(err)
}
res, err = pp.Decrypto(res)
if err != nil {
t.Error(err)
}
fmt.Printf("[%s]\n", string(res))
}
func Test_PKCS7Padding(t *testing.T) {
ltt := []byte("Test_PKCS7Padding")
ltt = PKCS7Padding(ltt, aes.BlockSize)
fmt.Printf("[%x]\n", (ltt))
}
func Test_PKCS7UnPadding(t *testing.T) {
ltt := []byte("Test_PKCS7Padding")
ltt = PKCS7Padding(ltt, aes.BlockSize)
ltt = PKCS7UnPadding(ltt)
fmt.Printf("[%x]\n", ltt)
}