这个星期工作上需要用http做数据上报

后台是用java实现,而我这边游戏开发使用go语言开发更顺手

最终http上报流程就是

go作为http客户端,把数据加密,签名后发出http

java作为http服务器,收到数据后进行解密,验签,无误后才接受

代码如下,都是3des加密

go语言版本

// 3des加密数据(data:明文数据,key:密钥字符串,返回密文数据)
func DesCBCEncrypt(data, key []byte) string {
block, err := des.NewTripleDESCipher(key)
if err != nil {
fmt.Printf("err=%v \n", err)
return ""
}
// pkcs5填充
data = pkcs5Padding(data, block.BlockSize())
blockMode := cipher.NewCBCEncrypter(block, key[:8])
cryptText := make([]byte, len(data))
blockMode.CryptBlocks(cryptText, data)
return base64.StdEncoding.EncodeToString(cryptText)
}
// pkcs5补码算法
func pkcs5Padding(ciphertext []byte, blockSize int) []byte {
padding := blockSize - len(ciphertext)%blockSize
padtext := bytes.Repeat([]byte{byte(padding)}, padding)
return append(ciphertext, padtext...)
}

java语言版本

public static String tripleDesEncrypt(String content, String key) throws Exception {
if (StringUtils.isEmpty(key)) {
return null;
}
byte[] keyBytes = key.getBytes(StandardCharsets.UTF_8);

byte[] icv = new byte[8];
System.arraycopy(keyBytes, 0, icv, 0, 8);
byte[] bytes = tripleDesEncrypt(content.getBytes(StandardCharsets.UTF_8), keyBytes, icv);
return new String(Base64.encodeBase64(bytes));
}
private static byte[] tripleDesEncrypt(byte[] content, byte[] key, byte[] icv) throws Exception {
final SecretKey secretKey = new SecretKeySpec(key, "DESede");
final Cipher cipher = Cipher.getInstance("DESede/CBC/PKCS5Padding");
final IvParameterSpec iv = new IvParameterSpec(icv);
cipher.init(Cipher.ENCRYPT_MODE, secretKey, iv);