50,549
社区成员
发帖
与我相关
我的任务
分享
static byte[] wrap(String algo,byte[] key,byte[] iv,byte[] data,int mode) throws Exception
{
Cipher cipher = Cipher.getInstance(algo + "/CBC/PKCS5PADDING");
SecretKeySpec skey = new SecretKeySpec(key,0,Math.min(key.length,Cipher.getMaxAllowedKeyLength(algo)/8),algo);
IvParameterSpec ivParam = new IvParameterSpec(iv,0,cipher.getBlockSize());
cipher.init(mode,skey,ivParam);
return cipher.doFinal(data);
}
static byte[] encrypt(String algo,byte[] key,byte[] iv,byte[] data) throws Exception
{
return wrap(algo,key,iv,data,Cipher.ENCRYPT_MODE);
}
static byte[] decrypt(String algo,byte[] key,byte[] iv,byte[] data) throws Exception
{
return wrap(algo,key,iv,data,Cipher.DECRYPT_MODE);
}
static byte[] key(String key) throws Exception
{
return MessageDigest.getInstance("MD5").digest(key.getBytes("UTF-8"));
}
static byte[] iv(long iv)
{
byte[] b = new byte[32];
ByteBuffer.wrap(b).putLong(iv);
return b;
}
static byte[] encrypt(String algo,String key,long iv,String text) throws Exception
{
return encrypt(algo,key(key),iv(iv),text.getBytes("UTF-8"));
}
static String decrypt(String algo,String key,long iv,byte[] data) throws Exception
{
return new String(decrypt(algo,key(key),iv(iv),data),"UTF-8");
}
public static void main(String[] args) throws Exception
{
//初始向量需要明文传递给解密者,以使相同的明文每次都产生不同的密文。
for(int i=0;i<8;i++)
{
String algo = i<4?"AES":"DES";
//long iv = System.nanoTime();
long iv = i; //每次运行都会输出相同结果
byte[] data = encrypt(algo,"mypassword",iv,algo +" encrypt/decrypt sample.");
System.out.print("iv=" + Long.toHexString(iv) + "\t");
for(byte b:data)
System.out.print(" " + Integer.toHexString(0x100|(0xff&b)).substring(1));
System.out.println();
String text = decrypt(algo,"mypassword",iv,data);
System.out.println(text);
}
}