我需要实现256位AES加密,但我在网上找到的所有示例都使用"KeyGenerator"生成256位密钥,但我想使用自己的密码.如何创建自己的密钥?我已经尝试将其填充为256位,但后来我得到一个错误,说密钥太长了.我确实安装了无限管辖区补丁,所以那不是问题:)
IE浏览器.KeyGenerator看起来像这样......
// Get the KeyGenerator
KeyGenerator kgen = KeyGenerator.getInstance("AES");
kgen.init(128); // 192 and 256 bits may not be available
// Generate the secret key specs.
SecretKey skey = kgen.generateKey();
byte[] raw = skey.getEncoded();
Run Code Online (Sandbox Code Playgroud)
编辑
我实际上是将密码填充到256个字节,而不是位,这太长了.以下是我现在使用的一些代码,我对此有更多的经验.
byte[] key = null; // TODO
byte[] input = null; // TODO
byte[] output = null;
SecretKeySpec keySpec = null;
keySpec = new SecretKeySpec(key, "AES");
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS7Padding");
cipher.init(Cipher.ENCRYPT_MODE, keySpec);
output = cipher.doFinal(input)
Run Code Online (Sandbox Code Playgroud)
您需要自己做的"TODO"位:-)