JavaDES加密解密算法
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);
}
}
本文由用戶 jopen 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!