Skip to content

Javascrip Golang AES Decrypt Encrypt

mojocn edited this page Jul 21, 2020 · 1 revision

aesjs.go

package util

import (
	"bytes"
	"crypto/aes"
	"crypto/cipher"
	"encoding/hex"
	"errors"
	"fmt"
)

// JsAesDecrypt 上面js代码最后返回的是16进制
// 所以收到的数据hexText还需要用hex.DecodeString(hexText)转一下,这里略了
func JsAesDecrypt(hexS, key []byte) ([]byte, error) {
	hexRaw, err := hex.DecodeString(string(hexS))
	if err != nil {
		return nil, err
	}
	if len(key) == 0 {
		return nil, errors.New("key 不能为空")
	}
	pkey := paddingLeft(key, '0', 16)
	block, err := aes.NewCipher(pkey) //选择加密算法
	if err != nil {
		return nil, fmt.Errorf("key 长度必须 16/24/32长度: %s", err)
	}
	blockModel := cipher.NewCBCDecrypter(block, pkey)
	plantText := make([]byte, len(hexRaw))
	blockModel.CryptBlocks(plantText, hexRaw)
	plantText = pkcs7UnPadding(plantText)
	return plantText, nil
}

func paddingLeft(ori []byte, pad byte, length int) []byte {
	if len(ori) >= length {
		return ori[:length]
	}
	pads := bytes.Repeat([]byte{pad}, length-len(ori))
	return append(pads, ori...)
}

func JsAesEncrypt(raw string, key string) (string, error) {
	origData := []byte(raw)
	// 转成字节数组
	if len(key) == 0 {
		return "", errors.New("key 不能为空")
	}
	k := paddingLeft([]byte(key), '0', 16)

	// 分组秘钥
	block, err := aes.NewCipher(k)
	if err != nil {
		return "", fmt.Errorf("填充秘钥key的16位,24,32分别对应AES-128, AES-192, or AES-256  key 长度必须 16/24/32长度: %s", err)
	}
	// 获取秘钥块的长度
	blockSize := block.BlockSize()
	// 补全码
	origData = pkcs7Padding(origData, blockSize)
	// 加密模式
	blockMode := cipher.NewCBCEncrypter(block, k)
	// 创建数组
	cryted := make([]byte, len(origData))
	// 加密
	blockMode.CryptBlocks(cryted, origData)
	//使用RawURLEncoding 不要使用StdEncoding
	//不要使用StdEncoding  放在url参数中会导致错误
	return hex.EncodeToString(cryted), nil
}

aesjs_test.go

package util

import (
	"testing"
)

func TestDecryptJs(t *testing.T) {

	got, err := JsAesDecrypt([]byte("a8ee9b4cfee2c682f382f1c292a93c6bb100be65cc34ba4246b45d744e8e3abf"), []byte("1595231954955"))
	if err != nil {
		t.Errorf("DecryptJs() error = %v", err)
		return
	}
	t.Log(string(got))
}
func TestDecryptJs2(t *testing.T) {

	got, err := JsAesDecrypt([]byte("e1d4d9ae99fa43e5d968bae170f6ca25e07cfdf41d738f156e7b076b3074067b"), []byte("1595241274949"))
	if err != nil {
		t.Errorf("DecryptJs() error = %v", err)
		return
	}
	t.Log(string(got))
}

func TestJsAesEncrypt(t *testing.T) {
	raw, key := "Admin@arrian.007", "1595231954955"
	d, err := JsAesEncrypt(raw, key)
	if err != nil {
		t.Error(err)
		return
	}
	if d != "a8ee9b4cfee2c682f382f1c292a93c6bb100be65cc34ba4246b45d744e8e3abf" {
		t.Error(d)
		return
	}

	got, err := JsAesDecrypt([]byte(d), []byte(key))
	if err != nil {
		t.Errorf("DecryptJs() error = %v", err)
		return
	}
	if string(got) != raw {
		t.Error("failed")
	}
}