【发布时间】:2016-03-10 04:54:27
【问题描述】:
我在我的应用程序中使用下面的 (E.1),显然我认识到并理解其中存在一个巨大的明显安全漏洞。我对加密越来越感兴趣并希望更好地理解它,我需要生成一个随机密钥和一个 IV,但我不确定如何正确地这样做) 所以我以后能更好地理解和应用我的知识,本质上我只是想让代码更安全,谢谢。
(E.1)
byte[] key = "mykey".getBytes("UTF-8");
private byte[] getKeyBytes(final byte[] key) throws Exception {
byte[] keyBytes = new byte[16];
System.arraycopy(key, 0, keyBytes, 0, Math.min(key.length, keyBytes.length));
return keyBytes;
}
public Cipher getCipherEncrypt(final byte[] key) throws Exception {
byte[] keyBytes = getKeyBytes(key);
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
SecretKeySpec secretKeySpec = new SecretKeySpec(keyBytes, "AES");
IvParameterSpec ivParameterSpec = new IvParameterSpec(keyBytes);
cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec, ivParameterSpec);
return cipher;
}
public void encrypt(File in, File output, byte[] key) throws Exception {
Cipher cipher = getCipherEncrypt(key);
FileOutputStream fos = null;
CipherOutputStream cos = null;
FileInputStream fis = null;
try {
fis = new FileInputStream(in);
fos = new FileOutputStream(output);
cos = new CipherOutputStream(fos, cipher);
byte[] data = new byte[1024];
int read = fis.read(data);
while (read != -1) {
cos.write(data, 0, read);
read = fis.read(data);
System.out.println(new String(data, "UTF-8").trim());
}
cos.flush();
} finally {
System.out.println("performed encrypt method now closing streams:\n" + output.toString());
cos.close();
fos.close();
fis.close();
}
}
public void watchMeEncrypt(){
encrypt(file, new File ("example.txt),key);
【问题讨论】:
-
IV 不需要保密,通常不需要。从加密 PRNG 创建一个随机位 IV,用于加密并添加到加密文本。解密时,从加密数据的前面抓取 IV 并用于解密并跳过它以获取加密数据。
-
请注意,使用 GCM 等经过身份验证的模式通常更有意义。 CBC 模式不提供完整性/真实性,仅提供机密性,并且仅用于就地加密(由于填充 oracle 攻击)。
-
感谢您的回复,您能否告诉我如何在 IV 的上下文中进行测试?
标签: java encryption cryptography byte aes