用于加密AES会话密钥的公钥/私钥

时间:2016-08-21 13:02:17

标签: java encryption aes

我一直致力于加密/解密程序。我正在使用AES。 我正在努力的是,删除string password并创建AES会话密钥。这个AES会话密钥是我实际想用来加密和解密数据的。然后使用私钥或公钥加密此AES会话密钥并在本地存储(例如用途)。

以下是目前完全用于使用纯文本字符串加密和解密数据的编码:

到目前为止的编码:

// password to encrypt the file
String password = "p@sswordDataNoW";

// salt is used for encoding
byte[] salt = new byte[8];
SecureRandom secureRandom = new SecureRandom();
secureRandom.nextBytes(salt);
FileOutputStream saltOutFile = new FileOutputStream("salt.enc");
saltOutFile.write(salt);
saltOutFile.close();

SecretKeyFactory factory = SecretKeyFactory
                .getInstance("PBKDF2WithHmacSHA1");
KeySpec keySpec = new PBEKeySpec(password.toCharArray(), salt, 65536,
                128);
SecretKey secretKey = factory.generateSecret(keySpec);
SecretKey secret = new SecretKeySpec(secretKey.getEncoded(), "AES");

//padding AES encryption
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, secret);
AlgorithmParameters params = cipher.getParameters();

// iv adds randomness to the text and just makes the mechanism more
// secure
// used while initializing the cipher
// file to store the iv
FileOutputStream ivOutFile = new FileOutputStream("iv.enc");
byte[] iv = params.getParameterSpec(IvParameterSpec.class).getIV();
ivOutFile.write(iv);
ivOutFile.close();

//file encryption
byte[] input = new byte[64];
int bytesRead;

while ((bytesRead = inFile.read(input)) != -1) {
        byte[] output = cipher.update(input, 0, bytesRead);
        if (output != null)
                outFile.write(output);
}

byte[] output = cipher.doFinal();
if (output != null)
        outFile.write(output);

inFile.close();
outFile.flush();
outFile.close();

在将string password更改为生成的会话密钥方面,请有人帮助我。然后使用公钥或私钥加密此会话密钥并存储在本地系统上。

我尝试了许多不同的方法,每次都没有解决。

1 个答案:

答案 0 :(得分:3)

AES密钥由16,24或32个字节组成,应该看起来像随机噪声。用户永远不会看到它。因此,您可以安全地生成它:

SecureRandom r = new SecureRandom();
byte[] aesKey = new byte[16];
r.nextBytes(aesKey);

这里我生成了一个16字节的密钥。您应该使用24或32字节以获得更高的安全性,但前提是您已为JRE / JDK安装了Unlimited Strength策略文件。

现在,剩下的加密很简单:

SecretKey secret = new SecretKeySpec(aesKey, "AES");
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, secret);
// everything else as before

除此之外,您可以使用公钥 加密 aesKey。如果你加密"使用私钥,您无法保护AES密钥免受监视。 "使用私钥加密"被称为签名,数据不是保密的。