DES加解密例子
阿新 • • 發佈:2019-02-14
package com.gy.util; import org.junit.Test; import sun.misc.BASE64Decoder; import sun.misc.BASE64Encoder; import javax.crypto.Cipher; import javax.crypto.SecretKeyFactory; import javax.crypto.spec.DESedeKeySpec; import java.net.URLEncoder; import java.security.Key; import java.util.Date; public classDes3Util { private static String keys = "y321123geasy12345678901234567892"; private static byte[] kb = { 'a','b', 'c','d','e', 'f','g','h' }; @Test public void test() throws Exception { Long time = new Date().getTime(); String str = "des加解密校驗碼54088"+time; System.out.println("str:"+str); String s = encodeStr(str); System.out.println(s); System.out.println(decodeStr(s)); System.out.println("sss:" + URLEncoder.encode(s)); String st = DateUtil.getFormatStrFromTimestamp(time); System.out.println("st:"+st); } /*** 加密 * @param s 輸入字串 * @return */ public static String encodeStr(String s){ if(s==null)return null; try { byte[] key=new BASE64Decoder().decodeBuffer(keys); byte[] data=s.getBytes("UTF-8"); byte[] str = encodebyecb(key, data); String result = new BASE64Encoder().encode(str); return result; } catch (Exception e) { e.printStackTrace(); } return null; } public static String decodeStr(String s){ try { byte[] bs = new BASE64Decoder().decodeBuffer(s); byte[] key=new BASE64Decoder().decodeBuffer(keys); byte[] str = decodebyecb(key, bs); String result = new String(str, "UTF-8"); return result; } catch (Exception e) { e.printStackTrace(); } return null; } private static byte[] encodebyecb(byte[] key, byte[] data) throws Exception { Key deskey = null; DESedeKeySpec spec = new DESedeKeySpec(key); SecretKeyFactory keyfactory = SecretKeyFactory.getInstance("desede"); deskey = keyfactory.generateSecret(spec); Cipher cipher = Cipher.getInstance("desede" + "/ECB/PKCS5Padding"); cipher.init(Cipher.ENCRYPT_MODE, deskey); byte[] bOut = cipher.doFinal(data); return bOut; } private static byte[] decodebyecb(byte[] key, byte[] data) throws Exception { Key deskey = null; DESedeKeySpec spec = new DESedeKeySpec(key); SecretKeyFactory keyfactory = SecretKeyFactory.getInstance("desede"); deskey = keyfactory.generateSecret(spec); Cipher cipher = Cipher.getInstance("desede" + "/ECB/PKCS5Padding"); cipher.init(Cipher.DECRYPT_MODE, deskey); byte[] bOut = cipher.doFinal(data); return bOut; } }