加密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为生成的会话密钥方面。然后使用公钥或私钥加密此会话密钥,并将其存储在本地系统上。

我尝试了很多不同的方法,但每次都没有成功。

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

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

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

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

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密钥免受监视。"用私钥加密"称为签名,该数据不是机密的。

最新更新