PackageCom.cs99lzzs.shop.util;ImportJava.math.BigInteger;ImportJava.security.Key;Importjava.security.MessageDigest;Importjava.security.NoSuchAlgorithmException;ImportJava.security.spec.AlgorithmParameterSpec;ImportJavax.crypto.Cipher;Importjavax.crypto.SecretKeyFactory;ImportJavax.crypto.spec.DESKeySpec;ImportJavax.crypto.spec.IvParameterSpec;Importorg.apache.commons.lang.StringUtils;/*** Encryption Algorithm * *@version$Id: Descbcsecurity.java, v 0.1 July 24, 2017 am 9:41:59 chenxu Exp $*/ Public classdescbcsecurity { Public Static FinalString algorithm_des = "Des/cbc/pkcs5padding"; /** * * @paramData *@paramKey *@return * @throwsException*/ Public Staticstring encode (string data, string key)throwsException {if(Stringutils.isempty (key) | |stringutils.isempty (data)) { return NULL; } returnencode (Data.getbytes (), key); } /*** des algorithm, encryption * *@paramData * String to encrypt *@paramKey * Encrypts the private key, the length cannot be less than 8 bits *@returnencrypted byte array, commonly combined with BASE64 encoding using *@throwscryptexception * Exception*/ Private StaticString Encode (byte[] data, String key)throwsException {Try{deskeyspec DKs=NewDeskeyspec (Key.getbytes ()); Secretkeyfactory keyfactory= Secretkeyfactory.getinstance ("DES"); //the length of the key cannot be less than 8 bit bytesKey Secretkey =Keyfactory.generatesecret (DKS); Cipher Cipher=cipher.getinstance (algorithm_des); Ivparameterspec IV=NewIvparameterspec (Key.getbytes ()); Algorithmparameterspec Paramspec=IV; Cipher.init (Cipher.encrypt_mode, Secretkey, Paramspec); byte[] bytes =cipher.dofinal (data); returnAshex (bytes); } Catch(Exception e) {Throw NewException (e); } } Public StaticString MD5 (String input)throwsnosuchalgorithmexception {String result=input; if(Input! =NULL) {MessageDigest MD= Messagedigest.getinstance ("MD5");//or "SHA-1"md.update (Input.getbytes ()); BigInteger Hash=NewBigInteger (1, Md.digest ()); Result= Hash.tostring (16); while(Result.length () < 32) {//Max for SHA-1result = "0" +result; } } returnresult; } Public StaticString Ashex (bytebuf[]) {StringBuffer Strbuf=NewStringBuffer (Buf.length * 2); inti; for(i = 0; i < buf.length; i++) { if(((int) Buf[i] & 0xff) < 0x10) Strbuf.append ("0"); Strbuf.append (long.tostring (int) Buf[i] & 0xFF, 16)); } returnstrbuf.tostring (); } }
Java implementation of DES encryption algorithm