Import Java.security.securerandom;import Javax.crypto.cipher;import Javax.crypto.secretkey;import Javax.crypto.secretkeyfactory;import Javax.crypto.spec.deskeyspec;public class Cryptkit {private final static String Des = "des";p ublic static void Main (string args[]) throws Exception {string str = Encrypt ("The Cold Night", "12345678"); System.out.println (str); String str2 = Decrypt ("63b121c4ea212f8bc74e8113bdfbfb81", "12345678"); System.out.println (STR2);} Encrypt public static byte[] Encrypt (byte[] data, byte[] key) throws Exception {Cipher Cipher = cipher.getinstance (DES);D Eske Yspec ds = new Deskeyspec (key); securerandom sr = new SecureRandom (); Secretkeyfactory skfactory = secretkeyfactory.getinstance (DES); Secretkey skey = Skfactory.generatesecret (ds); Cipher.init (Cipher.encrypt_mode, Skey, SR); byte[] B = cipher.dofinal ( data); return b;} Encrypt public static string encrypt (string data, String key) throws Exception {return Byte2hex (Encrypt (data.getbytes (), key. GetBytes ()));} Decrypt public static byte[] Decrypt (byte[] data, byte[] key) throws Exception {Cipher Cipher = cipher.getinstance (DES);D eskeyspec ds = new Deskeyspec (key); securerandom sr = new SecureRandom (); Secretkeyfactory skfactory = secretkeyfactory.getinstance (DES); Secretkey skey = Skfactory.generatesecret (ds) Cipher.init (Cipher.decrypt_mode, Skey, SR); return cipher.dofinal (data) ;} Decrypt public static string decrypt (string data, String key) throws Exception {return new string (Decrypt (Hex2byte (Data.getby TES ()), Key.getbytes ()));} private static String Byte2hex (byte[] b) {StringBuilder hs = new StringBuilder (); String stmp;for (int n = 0; b! = null && n < b.length; n++) {stmp = Integer.tohexstring (B[n] & 0XFF); if (St Mp.length () = = 1) hs.append (' 0 '); hs.append (STMP);} Return hs.tostring (). toUpperCase ();} private static byte[] Hex2byte (byte[] b) {if ((b.length% 2)! = 0) throw new IllegalArgumentException (); byte[] B2 = new byt e[b.length/2];for (int n = 0; n < b.length; n + = 2) {String item = new string (b, n, 2); b2[n /2] = (byte) integer.parseint (item, 16);} return B2;}}
Java des encryption and decryption