一、前言
通过sun.misc.BASE64Encoder、sun.misc.BASE64Decoder数据加密解密算法,实现3DES算法的encrypt加密/decrypt解密,详见代码示例说明。
二、代码示例
import javax.crypto.Cipher;@b@import javax.crypto.spec.SecretKeySpec; @b@import org.apache.commons.lang.StringUtils; @b@import sun.misc.BASE64Decoder;@b@import sun.misc.BASE64Encoder;@b@@b@@b@public class DES3Util {@b@ @b@ /**@b@ * @param content @b@ * @param desKey 3DES KEY@b@ * @return@b@ * @throws Exception@b@ */@b@ public static String encrypt(String content, String desKey) {@b@ String str = null;@b@ try {@b@ if(StringUtils.isEmpty(desKey) || desKey.length() != 24) {@b@ throw new Exception("3des key's length must be 24");@b@ }@b@ if(StringUtils.isEmpty(content)) {@b@ return "";@b@ }@b@ @b@ SecretKeySpec key = new SecretKeySpec(desKey.getBytes("utf-8"), "DESede");@b@ Cipher cipher = Cipher.getInstance("DESede");@b@ cipher.init(Cipher.ENCRYPT_MODE, key);@b@ byte [] encryptBytes = cipher.doFinal(content.getBytes("utf-8"));@b@ str = new BASE64Encoder().encode(encryptBytes);@b@ } catch (Exception e) {@b@ e.printStackTrace();@b@ }@b@ return str;@b@ }@b@ @b@ /**@b@ * @param content@b@ * @param desKey 3des key@b@ * @return@b@ * @throws Exception@b@ */@b@ public static String decrypt(String content, String desKey)throws Exception {@b@ try {@b@ if(StringUtils.isEmpty(desKey) || desKey.length() != 24) {@b@ throw new Exception("3des key's length must be 24");@b@ }@b@ if(StringUtils.isEmpty(content)) {@b@ return "";@b@ }@b@ @b@ byte [] decryptBytes = null;@b@ decryptBytes = new BASE64Decoder().decodeBuffer(content);@b@ @b@ SecretKeySpec key = new SecretKeySpec(desKey.getBytes("utf-8"), "DESede");@b@ Cipher cipher = Cipher.getInstance("DESede");@b@ cipher.init(Cipher.DECRYPT_MODE, key);@b@ @b@ return new String(cipher.doFinal(decryptBytes), "utf-8");@b@ } catch (Exception e) {@b@ throw e;@b@ }@b@ }@b@ @b@ public static void main(String[] args) throws Exception {@b@ String key = "F6011F0398F3461BA53D3A9B";@b@ String content = "11111111111111111111111111111111111111111111111111111";@b@ String jiami = DES3Util.encrypt(content, key);@b@ System.out.println("jiami = " + jiami);@b@ String jiemi = DES3Util.decrypt(jiami, key);@b@ System.out.println("jiemi = " + jiemi);@b@ }@b@}
控制台输出结果
jiami = Q9H/EbppfKxD0f8Ruml8rEPR/xG6aXysQ9H/EbppfKxD0f8Ruml8rEPR/xG6aXysGC8TwlWCEa4=@b@jiemi = 11111111111111111111111111111111111111111111111111111