51,396
社区成员




package security.crypt.aes;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
/**
* 如果還需要改進的話,還可以增加設置加解密算法的方法
* @author sta
*
*/
public class EncrypImpl implements Encryp {
SecretKey deskey = null;// 加解密必须使用相同的key,所以需要用实例变量控制
public String decryption(byte[] s) {
System.out.println("解密开始...");
Cipher c = null;
byte[] enc = null;
try {
// c = Cipher.getInstance("DESede");
c = Cipher.getInstance("AES");
} catch (Exception e) {
e.printStackTrace();
}
try {
c.init(Cipher.DECRYPT_MODE, deskey);
enc = c.doFinal(s);
System.out.println("\t解密之后的明文是:" + new String(enc));
} catch (Exception e) {
e.printStackTrace();
}
return new String(enc);
}
public byte[] encryption(String s) {
System.out.println("加密开始...");
System.out.println("\t原文:" + s);
KeyGenerator keygen;
Cipher c = null;
try {
// keygen = KeyGenerator.getInstance("DESede");
keygen = KeyGenerator.getInstance("AES");
deskey = keygen.generateKey();
// c = Cipher.getInstance("DESede");
c = Cipher.getInstance("AES");
} catch (Exception e) {
e.printStackTrace();
}
byte[] dec = null;
try {
c.init(Cipher.ENCRYPT_MODE, deskey);
dec = c.doFinal(s.getBytes());
System.out.print("\t加密后密文是:");
for (byte b : dec) {
System.out.print(b + ",");
}
System.out.println();
} catch (Exception e) {
e.printStackTrace();
}
return dec;
}
}
package security.crypt.aes;
public class Tester {
/**
* @param args
*/
public static void main(String[] args) {
Encryp encryp = new EncrypImpl();
String str ="abc";
byte[] de = encryp.encryption(str);
String str1 = encryp.decryption(de);
}
}