JavaDES加密解密算法

来源:互联网 发布:阿里云订单退款 编辑:程序博客网 时间:2024/06/14 12:19

JavaDES加密解密算法

import java.nio.ByteBuffer;import java.security.SecureRandom;import javax.crypto.Cipher;import javax.crypto.SecretKey;import javax.crypto.SecretKeyFactory;import javax.crypto.spec.DESKeySpec;/** *  * @author whzhaochao *  * DES加密解密 * */public class Main {public static void main(String[] args) throws Exception {// TODO Auto-generated method stub// 待加密内容String str = "要加密的内容";// 密码,长度要是8的倍数String password = "9876543210";String codeStr=CodeStr(str, password);System.out.println("原始内容:"+str);System.out.println("加密内容:"+codeStr);String deCodeStr=DcodeStr(codeStr, password);System.out.println("解密内容:"+deCodeStr);}/** *  * @param str 待加密字符串 * @param password 密码 * @return */public static String CodeStr(String str,String password){byte[] result = desCrypto(str.getBytes(), password);char[] chreslut=new char[result.length];for(int i=0; i<result.length;i++){char ch=(char) result[i];chreslut[i]=ch;}String strres=new String(chreslut);return strres;}/** *  * @param strres  待解密字符串 * @param password  密码 * @return * @throws Exception */public static String DcodeStr(String strres,String password) throws Exception{byte [] decode=new byte[strres.length()];for(int i=0;i<strres.length();i++){char ch=strres.charAt(i);byte b=(byte) ch;decode[i]=b;}     byte[] decryResult = decrypt(decode, password);return new String(decryResult);}/** *  * @param datasource  * @param password * @return */public static byte[] desCrypto(byte[] datasource, String password) {try {SecureRandom random = new SecureRandom();DESKeySpec desKey = new DESKeySpec(password.getBytes());// 创建一个密匙工厂,然后用它把DESKeySpec转换成SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");SecretKey securekey = keyFactory.generateSecret(desKey);// Cipher对象实际完成加密操作Cipher cipher = Cipher.getInstance("DES");// 用密匙初始化Cipher对象cipher.init(Cipher.ENCRYPT_MODE, securekey, random);// 现在,获取数据并加密// 正式执行加密操作return cipher.doFinal(datasource);} catch (Throwable e) {e.printStackTrace();}return null;}/** *  * @param src * @param password * @return * @throws Exception */private static byte[] decrypt(byte[] src, String password) throws Exception {// DES算法要求有一个可信任的随机数源SecureRandom random = new SecureRandom();// 创建一个DESKeySpec对象DESKeySpec desKey = new DESKeySpec(password.getBytes());// 创建一个密匙工厂SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");// 将DESKeySpec对象转换成SecretKey对象SecretKey securekey = keyFactory.generateSecret(desKey);// Cipher对象实际完成解密操作Cipher cipher = Cipher.getInstance("DES");// 用密匙初始化Cipher对象cipher.init(Cipher.DECRYPT_MODE, securekey, random);// 真正开始解密操作return cipher.doFinal(src);}}

结果

原始内容:要加密的内容加密内容:ao?3"???<£r???解密内容:要加密的内容




0 0