- 1
新建一个java项目,项目标名称为javades。
- 2
打开这个javades文件,在此中界说一个静态方式getkey,把des算法的key的8的字节生当作。
private static SecretKey getkey(byte[] key){
try {
DESKeySpec ks=new DESKeySpec(key);
SecretKeyFactory kf=SecretKeyFactory.getInstance("des");
SecretKey sk=kf.generateSecret(ks);
return sk;
} catch (InvalidKeyException | InvalidKeySpecException | NoSuchAlgorithmException ex) {
Logger.getLogger(Javades.class.getName()).log(Level.SEVERE, null, ex);
}
return null;
}
- 3
界说一个解密方式:
private static byte[] decrypt(byte[]data,String key){
try {
SecretKey sk=getkey(key.getBytes());
Cipher ch=Cipher.getInstance("des");
ch.init(Cipher.DECRYPT_MODE, sk);
return ch.doFinal(data);
} catch (NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException | IllegalBlockSizeException | BadPaddingException ex) {
Logger.getLogger(Javades.class.getName()).log(Level.SEVERE, null, ex);
}
return null;
}
- 4
界说加密方式:
try {
SecretKey sk=getkey(key.getBytes());
Cipher ch = Cipher.getInstance("des");
ch.init(Cipher.ENCRYPT_MODE, sk);
return ch.doFinal(data);
} catch (NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException | IllegalBlockSizeException | BadPaddingException ex) {
Logger.getLogger(Javades.class.getName()).log(Level.SEVERE, null, ex);
}
return null;
}
- 5
在main方式中加密一个字符串息争密一个字符串:
String key="12345678";
String data="abc123456890";
System.err.println("data:"+data);
byte[] jmdata=Javades.encrypt(data.getBytes(), key);
System.err.println(Arrays.toString(jmdata));
jm=Javades.decrypt(jm, pw);
System.err.println(new String(jm));
- 6
运行项目,成果把字符串des加密,还原字符串当作功。
- 7
这个在对文件加密:
String key="12345678";
try {
File fi=new File("c:/data.txt");
InputStream input = new FileInputStream(fi);
byte[] data = new byte[input.available()];
input.read(data);
System.err.println("data:"+data);
byte[] jmdata=Javades.encrypt(data, key);
System.err.println("加密数据:"+Arrays.toString(jmdata));
byte[] jmjm=Javades.decrypt(jmdata, key);
System.err.println("解密数据:"+new String(jmjm,"UTF-8"));
} catch (FileNotFoundException ex) {
Logger.getLogger(Javades.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(Javades.class.getName()).log(Level.SEVERE, null, ex);
}
- 8
运行项目,对文件byte[]的数据加密息争密当作功。