最近做了一个项目,我是用go +gin做的接口,需要用到跟第三方合作公司做接口对接,因为对方公司是用java springboot做的,他们提供额一个算法。如下。

private static String encryptData(String appKey, String appId, String content) throws Exception{
    byte[] byteContent = content.getBytes(StandardCharsets.UTF_8);
    SecretKeySpec secretKeySpec = new SecretKeySpec(appKey.getBytes(), "AES");
    IvParameterSpec ivParameterSpec = new IvParameterSpec(appId.getBytes());
    // 指定加密的算法、工作模式和填充方式
    Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
    cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec, ivParameterSpec);
    byte[] encryptedBytes = cipher.doFinal(byteContent);
    //对加密后数据进行 base64 编码
    return Base64.encodeBase64String(encryptedBytes);
}

因为最java不熟悉,一开始是就蒙了,于是乎,我就想如想它转换成go或者php,因为本人php程序员,所有就先想把其转换为php,经过半天的倒腾,结果写出来了,发现上面的方法,估计也是对方对方在网上找个加密方法。我的golang 方法如下

func getKeyBytes(key string) []byte {
	keyBytes := []byte(key)
	switch l := len(keyBytes); {
	case l < 16:
		keyBytes = append(keyBytes, make([]byte, 32-l)...)
	case l > 16:
		keyBytes = keyBytes[:32]
	}
	return keyBytes
}

func encrypt(appKey string, appId string, origData []byte) ([]byte, error) {
	keyBytes := getKeyBytes(appKey)
	block, err := aes.NewCipher(keyBytes)
	iv := getKeyBytes(appId)
	if err != nil {
		return nil, err
	}
	blockSize := block.BlockSize()
	origData = PKCS5Padding(origData, blockSize)
	blockMode := cipher.NewCBCEncrypter(block, iv)
	crypted := make([]byte, len(origData))
	blockMode.CryptBlocks(crypted, origData)
	return crypted, nil
}

希望对后面又需要的同学有所帮助