nps/lib/crypt/crypt.go

77 lines
1.8 KiB
Go
Raw Normal View History

2019-02-09 09:07:47 +00:00
package crypt
2019-01-02 17:44:45 +00:00
import (
"bytes"
"crypto/aes"
"crypto/cipher"
"crypto/md5"
"encoding/hex"
2019-01-09 12:33:00 +00:00
"errors"
2019-01-02 17:44:45 +00:00
"math/rand"
"time"
)
2019-01-03 16:21:23 +00:00
//en
2019-01-02 17:44:45 +00:00
func AesEncrypt(origData, key []byte) ([]byte, error) {
block, err := aes.NewCipher(key)
if err != nil {
return nil, err
}
blockSize := block.BlockSize()
origData = PKCS5Padding(origData, blockSize)
blockMode := cipher.NewCBCEncrypter(block, key[:blockSize])
crypted := make([]byte, len(origData))
blockMode.CryptBlocks(crypted, origData)
return crypted, nil
}
2019-01-03 16:21:23 +00:00
//de
2019-01-02 17:44:45 +00:00
func AesDecrypt(crypted, 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(crypted))
blockMode.CryptBlocks(origData, crypted)
2019-01-07 16:21:02 +00:00
err, origData = PKCS5UnPadding(origData)
return origData, err
2019-01-02 17:44:45 +00:00
}
2019-02-09 09:07:47 +00:00
//Completion when the length is insufficient
2019-01-02 17:44:45 +00:00
func PKCS5Padding(ciphertext []byte, blockSize int) []byte {
padding := blockSize - len(ciphertext)%blockSize
padtext := bytes.Repeat([]byte{byte(padding)}, padding)
return append(ciphertext, padtext...)
}
2019-02-09 09:07:47 +00:00
//Remove excess
2019-01-07 16:21:02 +00:00
func PKCS5UnPadding(origData []byte) (error, []byte) {
2019-01-02 17:44:45 +00:00
length := len(origData)
unpadding := int(origData[length-1])
2019-01-07 16:21:02 +00:00
if (length - unpadding) < 0 {
return errors.New("len error"), nil
}
return nil, origData[:(length - unpadding)]
2019-01-02 17:44:45 +00:00
}
2019-02-09 09:07:47 +00:00
//Generate 32-bit MD5 strings
2019-01-02 17:44:45 +00:00
func Md5(s string) string {
h := md5.New()
h.Write([]byte(s))
return hex.EncodeToString(h.Sum(nil))
}
2019-02-09 09:07:47 +00:00
//Generating Random Verification Key
2019-01-02 17:44:45 +00:00
func GetRandomString(l int) string {
str := "0123456789abcdefghijklmnopqrstuvwxyz"
bytes := []byte(str)
result := []byte{}
r := rand.New(rand.NewSource(time.Now().UnixNano()))
for i := 0; i < l; i++ {
result = append(result, bytes[r.Intn(len(bytes))])
}
return string(result)
}