Golang 实现Java的AES ECB 加密

Java

    public static String encryptAesEcb(String target, String sKey) throws Exception {
        byte[] raw = sKey.getBytes("UTF-8");
        //  "AES" 就是用 AES/ECB/PKCS5Padding
        SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
        Cipher cipher = Cipher.getInstance("AES");
        cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
        byte[] encrypted = cipher.doFinal(target.getBytes());
        return byteTurnHex(encrypted);
    }

		// 转16进制字符
    private static String byteTurnHex(byte[] b) {
        StringBuilder hs = new StringBuilder();
        String stmp;
        for (int n = 0; b != null && n < b.length; n++) {
            stmp = Integer.toHexString(b[n] & 0XFF);
            if (stmp.length() == 1) {
                hs.append('0');
            }
            hs.append(stmp);
        }
        return hs.toString().toLowerCase();
    }

golang 实现

func main() {
	// 方法1: 自行实现
	encrypt1()
	// 方法2: 使用别人写的包, go get github.com/forgoer/openssl
  // openssl 包还实现了AES其他几种加密方式
	encrypt2()
}

func encrypt1() {
	src := "实现加密过程"
	key := "0234567890123450"
	crypted := encryptService.AesEncrypt(src, key)
	fmt.Println(string(crypted))

	de := encryptService.AesDecrypt(crypted, []byte(key))
	fmt.Println(string(de))

	d := encryptService.ByteToHex(crypted)
	fmt.Println(d)
}

// 这个方法是可行的,实现对方java加密的
func encrypt2() {
	src := []byte("实现加密过程")
	key := []byte("0234567890123450")
	dst, err := openssl.AesECBEncrypt(src, key, openssl.PKCS5_PADDING)
	d := encryptService.ByteToHex(dst)
	fmt.Println(d, err)
	return
}

encryptService.go 的内容,转载自:https://blog.csdn.net/zhizhengguan/article/details/89281336 :

/*
*
AES/ECB/PKCS5 加密解密
*/
package encryptService

import (
	"bytes"
	"crypto/aes"
	"crypto/cipher"
	"fmt"
	"strings"
)

func ByteToHex(b []byte) string {
	var sb strings.Builder
	for _, v := range b {
		sb.WriteString(fmt.Sprintf("%02x", v))
	}
	return sb.String()
}

func AesDecrypt(crypted, key []byte) []byte {
	block, err := aes.NewCipher(key)
	if err != nil {
		fmt.Println("err is:", err)
	}
	blockMode := NewECBDecrypter(block)
	origData := make([]byte, len(crypted))
	blockMode.CryptBlocks(origData, crypted)
	origData = PKCS5UnPadding(origData)
	return origData
}

func AesEncrypt(src, key string) []byte {
	block, err := aes.NewCipher([]byte(key))
	if err != nil {
		fmt.Println("key error1", err)
	}
	if src == "" {
		fmt.Println("plain content empty")
	}
	ecb := NewECBEncrypter(block)
	content := []byte(src)
	content = PKCS5Padding(content, block.BlockSize())
	crypted := make([]byte, len(content))
	ecb.CryptBlocks(crypted, content)
	return crypted
}

func PKCS5Padding(ciphertext []byte, blockSize int) []byte {
	padding := blockSize - len(ciphertext)%blockSize
	padtext := bytes.Repeat([]byte{byte(padding)}, padding)
	return append(ciphertext, padtext...)
}

func PKCS5UnPadding(origData []byte) []byte {
	length := len(origData)
	// 去掉最后一个字节 unpadding 次
	unpadding := int(origData[length-1])
	return origData[:(length - unpadding)]
}

type ecb struct {
	b         cipher.Block
	blockSize int
}

func newECB(b cipher.Block) *ecb {
	return &ecb{
		b:         b,
		blockSize: b.BlockSize(),
	}
}

type ecbEncrypter ecb

// NewECBEncrypter returns a BlockMode which encrypts in electronic code book
// mode, using the given Block.
func NewECBEncrypter(b cipher.Block) cipher.BlockMode {
	return (*ecbEncrypter)(newECB(b))
}
func (x *ecbEncrypter) BlockSize() int { return x.blockSize }
func (x *ecbEncrypter) CryptBlocks(dst, src []byte) {
	if len(src)%x.blockSize != 0 {
		panic("crypto/cipher: input not full blocks")
	}
	if len(dst) < len(src) {
		panic("crypto/cipher: output smaller than input")
	}
	for len(src) > 0 {
		x.b.Encrypt(dst, src[:x.blockSize])
		src = src[x.blockSize:]
		dst = dst[x.blockSize:]
	}
}

type ecbDecrypter ecb

// NewECBDecrypter returns a BlockMode which decrypts in electronic code book
// mode, using the given Block.
func NewECBDecrypter(b cipher.Block) cipher.BlockMode {
	return (*ecbDecrypter)(newECB(b))
}
func (x *ecbDecrypter) BlockSize() int { return x.blockSize }
func (x *ecbDecrypter) CryptBlocks(dst, src []byte) {
	if len(src)%x.blockSize != 0 {
		panic("crypto/cipher: input not full blocks")
	}
	if len(dst) < len(src) {
		panic("crypto/cipher: output smaller than input")
	}
	for len(src) > 0 {
		x.b.Decrypt(dst, src[:x.blockSize])
		src = src[x.blockSize:]
		dst = dst[x.blockSize:]
	}
}

posted @ 2024-05-24 15:39  熊先生不开玩笑  阅读(239)  评论(0)    收藏  举报