Java 中的 AES SHA1PRNG 如何用 golang 实现?

/**
 *
 * AES CBC 256 位加密
 * @param content 加密内容字节数组
 * @param keyBytes 加密字节数组
 * @param iv 加密向量字节数组
 * @param encryptLength 仅支持 128、256 长度
 * @return 解密后字节内容
 * @throws NoSuchAlgorithmException
 * @throws NoSuchPaddingException
 * @throws InvalidKeyException
 * @throws InvalidAlgorithmParameterException
 * @throws IllegalBlockSizeException
 * @throws BadPaddingException
 */
public static byte[] encryptAESCBC( byte[] content, byte[] keyBytes,byte[] iv, int encryptLength )
{

	KeyGenerator	keyGenerator	= KeyGenerator.getInstance( "AES" );
	SecureRandom	secureRandom	= SecureRandom.getInstance( "SHA1PRNG" );
	secureRandom.setSeed( keyBytes );
	keyGenerator.init( encryptLength, secureRandom );
	SecretKey	key	= keyGenerator.generateKey();  
	// 以上应该是使用任意长度的 keyBytes,生成指定长度为 encryptLength 的 key
	// 后面再使用 AES/CBC/PKCS5Padding 算法,对 content 加密,加密角度是上面生成的固定长度的 key
	// 我的主要疑问就在这里,  如何用 golang 生成与 keyGenerator.generateKey() 一样的 key 呢?


	Cipher		cipher	= Cipher.getInstance( "AES/CBC/PKCS5Padding" );
	cipher.init( Cipher.ENCRYPT_MODE, key, new IvParameterSpec( iv ) );
	byte[] result = cipher.doFinal( content );
	return(result);
}

用下面的 golang 代码模拟出 128 bit / 32 byte 的生成方案了 但超过 160 bit / 20 byte 就不行了

// 模拟 Java 接口 generatorKey()
// 目前 encryptLength 仅支持 128bit 长度
// 因为 SHA1() 返回的长度固定为 20byte 160bit 
// 所以 encryptLength 超过这个长度,就无法生成了
// 因为不知道 java 中 AES SHA1PRNG 的生成逻辑
func AESSHA1PRNG(keyBytes []byte,  encryptLength int) ([]byte, *exterror.Error) {
	hashs := SHA1(SHA1(keyBytes))
	maxLen := len(hashs)
	realLen := encryptLength/8
	if realLen > maxLen {
		return nil, exterror.New1(fmt.Errorf("Not Support %d, Only Support Lower then %d [% x]", realLen, maxLen, hashs))
	}

	return hashs[0:realLen], nil
}

func SHA1(data []byte) []byte {
	h := sha1.New()
	h.Write(data)
	return h.Sum(nil)
}

原文:https://www.v2ex.com/t/459541

猜你喜欢

转载自blog.csdn.net/zhizhengguan/article/details/89283906