AES加密/解密java bouncy castle解释?
有人能解释一下这个项目的作用,指出一些要点吗?我正在看代码,我完全迷路了。我只需要解释一下加密/解密阶段。我认为它会在某一点上生成AES 192密钥,但我不是100%确定。我也不确定byte/ivBytes用于什么
import java.security.Key;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.spec.IvParameterSpec;
public class RandomKey
{
public static void main(String[] args) throws Exception
{
byte[] input = new byte[] {
0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07 };
byte[] ivBytes = new byte[] {
0x00, 0x00, 0x00, 0x01, 0x04, 0x05, 0x06, 0x07,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01 };
//initializing a new initialization vector
IvParameterSpec ivSpec = new IvParameterSpec(ivBytes);
//what does this actually do?
Cipher cipher = Cipher.getInstance("AES/CTR/NoPadding", "BC");
//what does this do?
KeyGenerator generator = KeyGenerator.getInstance("AES","BC");
//I assume this generates a key size of 192 bits
generator.init(192);
//does this generate a random key?
Key encryptKey = generator.generateKey();
System.out.println("input: " +toHex(input));
//encryption phase
cipher.init(Cipher.ENCRYPT_MODE, encryptKey, ivSpec);
//what is this doing?
byte[] cipherText = new byte[cipher.getOutputSize(input.length)];
//what is this doing?
int ctLength = cipher.update(input, 0, input.length, cipherText,0);
//getting the cipher text length i assume?
ctLength += cipher.doFinal (cipherText, ctLength );
System.out.println ("Cipher: " +toHex(cipherText) + " bytes: " + ctLength);
//decryption phase
cipher.init(Cipher.DECRYPT_MODE, encryptKey, ivSpec);
//storing the ciphertext in plaintext i'm assuming?
byte[] plainText = new byte[cipher.getOutputSize(ctLength)];
int ptLength = cipher.update(cipherText, 0, ctLength, plainText, 0);
//getting plaintextLength i think?
ptLength= cipher.doFinal (plainText, ptLength);
System.out.println("plain: " + toHex(plainText, ptLength));
}
private static String digits = "0123456789abcdef";
public static String toHex(byte[] data, int length)
{
StringBuffer buf = new StringBuffer();
for (int i=0; i!= length; i++)
{
int v = data[i] & 0xff;
buf.append(digits.charAt(v >>4));
buf.append(digits.charAt(v & 0xf));
}
return buf.toString();
}
public static String toHex(byte[] data)
{
return toHex(data, data.length);
}
}
# 1 楼答案
你试过看这里吗
http://docs.oracle.com/javase/6/docs/api/javax/crypto/Cipher.html
http://docs.oracle.com/javase/6/docs/api/javax/crypto/KeyGenerator.html
您的代码是一个关于如何在Java中加密和解密字节数据的非常简单的代码示例
阅读完类文档后,您可以更好地表达有关此代码行为的问题
# 2 楼答案
这将使用Bouncy Castle(“BC”)提供程序获取AES密码的实例,该密码在计数器模式(CTR)下设置,没有填充(NoPadding)。有关Block Cypher modes和Padding的信息,请参见维基百科。Javadoc也将帮助您
同样,它使用Bouncy Castle提供程序为AES设置密钥生成器。您可以阅读Javadoc以了解更多信息
它设置一个字节数组,其大小足以容纳加密的输出
它实际上是在做百科全书。检查Javadoc中的
update()
方法以获得良好的解释不。看那
+=
它正在更新密码文本长度。再次阅读Javadoc,了解update()
和doFinal()
方法之间的差异