des 加密解密

下面为代码示例

import com.fasterxml.jackson.databind.ObjectMapper;

import org.apache.commons.codec.binary.Base64;

import javax.crypto.Cipher;

import javax.crypto.SecretKey;

import javax.crypto.SecretKeyFactory;

import javax.crypto.spec.DESKeySpec;

import javax.crypto.spec.IvParameterSpec;

import java.math.BigInteger;

import java.security.MessageDigest;

import java.security.NoSuchAlgorithmException;

public class Test {

private static Ciphercipher ;

private static SecretKeysecretKey ;

private static IvParameterSpeciv  ;

private static StringsaltKey ="e89fb754" ;

static {

try {

DESKeySpec keySpec=new DESKeySpec(saltKey.getBytes());

iv =new IvParameterSpec(keySpec.getKey());

cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");

SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");

secretKey = keyFactory.generateSecret(keySpec);

}catch (Exception e) {

e.printStackTrace();

}

}

//加密des+base64

    public static String encrypt(String content, String saltKey)throws Exception {

byte[] encrypted =DES(content.getBytes(),Cipher.ENCRYPT_MODE);

return Base64.encodeBase64String(encrypted);

//return URLEncoder.encode(base64String, "UTF-8");

    }

//解密base64+des

    public static byte[] decrypt(String content)throws Exception {

byte[] decodeBase64 = Base64.decodeBase64(content);

return DES(decodeBase64,Cipher.DECRYPT_MODE);

}

//des加密解密

    public static byte[] DES(byte[] content,int cryptMode)throws Exception{

cipher.init(cryptMode,secretKey,iv);

return cipher.doFinal(content);

}

//md5加密

    public static String md5(String from)throws NoSuchAlgorithmException {

MessageDigest md = MessageDigest.getInstance("MD5");

md.update(from.getBytes());

return new BigInteger(1, md.digest()).toString(16);

}

public static void main(String[] args)throws Exception {

ObjectMapperjackson =new ObjectMapper();

String account ="123456";

String content ="{\"account\":\""+account+"\"}";

String param =encrypt(content,saltKey);

System.out.println("des + base64 加密后的parad: "+param);

System.out.println("base64 + des 解密后的parad: "+new String(decrypt(param)));

String sign =md5(content);

System.out.println("md5加密后的sign:  "+sign);

}

}

你可能感兴趣的:(des 加密解密)