求教,最近在做一个 java 项目集成的问题,用到了 AES 加密,他们给的工具类如下:
private static final int INIT_SIZE = 128;
private static final String SECRET_IALGORITHM = "AES";
private static final int ZERO = 0;
private static final int ONE = 1;
private static String derectory = "D:";
private static void doFile(int code, String sourceFilePath,String targetFilePath, String key) throws Exception{
File file = new File(sourceFilePath);
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(
file));
byte[] bytIn = new byte[(int) file.length()];
bis.read(bytIn);
bis.close();
//aes对称加密算法 加密和解密用到的密钥是相同的
//构造密钥生成器,指定为AES算法,不区分大小写
KeyGenerator kgen = KeyGenerator.getInstance(SECRET_IALGORITHM);
//根据key规则初始化密钥生成器
//生成一个128位的随机源,根据传入的字节数组
SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG");
secureRandom.setSeed(key.getBytes());
kgen.init(INIT_SIZE, secureRandom);
// kgen.init(INIT_SIZE, new SecureRandom(key.getBytes()));
//产生原始对称密钥
SecretKey skey = kgen.generateKey();
//获得原始对称密钥的字节数组
byte[] raw = skey.getEncoded();
//根据字节数组生成AES密钥
SecretKeySpec skeySpec = new SecretKeySpec(raw, SECRET_IALGORITHM);
//根据指定算法AES自成密码器
Cipher cipher = Cipher.getInstance(SECRET_IALGORITHM);
//初始化密码器,第一个参数为加密(ENCRYPT_MODE)或者解密(DECRYPT_MODE)操作,第二个参数为使用的KEY
if(0 == code){
cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
}else if(1 == code){
cipher.init(Cipher.DECRYPT_MODE, skeySpec);
}
//将数据加密或解密
byte[] bytOut = cipher.doFinal(bytIn);
BufferedOutputStream bos = new BufferedOutputStream(
new FileOutputStream(new File(targetFilePath)));
bos.write(bytOut);
bos.close();
}
然后,他们项目回复说用的是 128 位 AES/ECB/PKCS5Padding, 我研究了下,也看了相关的帖子,写的加密算法如下
def aes128_encrypt(data,key)
cipher = OpenSSL::Cipher.new 'aes-128-ecb'
cipher.encrypt
cipher.key = key
cipher.iv = ''
encrypted = cipher.update data
encrypted << cipher.final
end
基本翻遍了网上的帖子,加密后的数据怎么也对不上,是我遗漏了什么地方吗?求高人帮忙指点一下,感激不尽。