java加密encrypt
朋友你好,很高興為你作答。
首先,Java加密能夠應對的風險包括以下幾個:
1、核心技術竊取
2、核心業務破解
3、通信模塊破解
4、API介面暴露
本人正在使用幾維安全Java加密方式,很不錯,向你推薦,希望能夠幫助到你。
幾維安全Java2C針對DEX文件進行加密保護,將DEX文件中標記的Java代碼翻譯為C代碼,編譯成加固後的SO文件。默認情況只加密activity中的onCreate函數,如果開發者想加密其它類和方法,只需對相關類或函數添加標記代碼,在APK加密時會自動對標記的代碼進行加密處理。
與傳統的APP加固方案相比,不涉及到自定義修改DEX文件的載入方式,所以其兼容性非常好;其次Java函數被完全轉化為C函數,直接在Native層執行,不存在Java層解密執行的步驟,其性能和執行效率更優。
如果操作上有不明白的地方,可以聯系技術支持人員幫你完成Java加密。
希望以上解答能夠幫助到你。
⑵ 漫談Java加密技術(二)
接下來我們介紹對稱加密演算法 最常用的莫過於DES數據加密演算法
DES
DES Data Encryption Standard 即數據加密演算法 是IBM公司於 年研究成功並公開發表的 DES演算法的入口參數有三個 Key Data Mode 其中Key為 個位元組共 位 是DES演算法的工作密鑰 Data也為 個位元組 位 是要被加密或被解密的數據 Mode為DES的工作方式 有兩種 加密或解密
DES演算法把 位的明文輸入塊變為 位的密文輸出塊 它所使用的密鑰也是 位
通過java代碼實現如下
importjava security Key;importjava security SecureRandom;importjavax crypto Cipher;importjavax crypto KeyGenerator;importjavax crypto SecretKey;importjavax crypto SecretKeyFactory;importjavax crypto spec DESKeySpec;/***//***DES安全編碼組件authorby;**<pre>*支持DES DESede(TripleDES 就是 DES) AES Blowfish RC RC (ARCFOUR)*DESkeysizemustbeequalto *DESede(TripleDES)keysizemustbeequalto or *AESkeysizemustbeequalto or but and bitsmaynotbeavailable* andcanonlyrangefrom to (inclusive)*RC keysizemustbebeeen and bits*RC (ARCFOUR)keysizemustbebeeen and bits*具體內容需要關注JDKDocument&///docs/technotes/guides/security/l*</pre>**@author梁棟*@version *@since */{/***//***ALGORITHM演算法<br>*可替換為以下任意一種演算法 同時key值的size相應改變 **<pre>*DESkeysizemustbeequalto *DESede(TripleDES)keysizemustbeequalto or *AESkeysizemustbeequalto or but and bitsmaynotbeavailable* andcanonlyrangefrom to (inclusive)*RC keysizemustbebeeen and bits*RC (ARCFOUR)keysizemustbebeeen and bits*</pre>**在KeytoKey(byte[]key)方法中使用下述代碼*<code>SecretKeysecretKey=newSecretKeySpec(key ALGORITHM);</code>替換*<code>*DESKeySpecdks=newDESKeySpec(key);*SecretKeyFactorykeyFactory=SecretKeyFactory getInstance(ALGORITHM);*SecretKeysecretKey=keyFactory generateSecret(dks);*</code>*/= DES ;/***//***轉換密鑰<br>**@paramkey*@return*@throwsException*/privatestaticKeytoKey(byte[]key)throwsException{DESKeySpecdks=newDESKeySpec(key);SecretKeyFactorykeyFactory=SecretKeyFactory getInstance(ALGORITHM);SecretKeysecretKey=keyFactory generateSecret(dks);//當使用其他對稱加密演算法時 如AES Blowfish等演算法時 用下述代碼替換上述三行代碼//SecretKeysecretKey=newSecretKeySpec(key ALGORITHM);returnsecretKey;}/***//***解密**@paramdata*@paramkey*@return*@throwsException*/publicstaticbyte[]decrypt(byte[]data Stringkey)throwsException{Keyk=toKey(decryptBASE (key));Ciphercipher=Cipher getInstance(ALGORITHM);cipher init(Cipher DECRYPT_MODE k);returncipher doFinal(data);}/***//***加密**@paramdata*@paramkey*@return*@throwsException*/publicstaticbyte[]encrypt(byte[]data Stringkey)throwsException{Keyk=toKey(decryptBASE (key));Ciphercipher=Cipher getInstance(ALGORITHM);cipher init(Cipher ENCRYPT_MODE k);returncipher doFinal(data);}/***//***生成密鑰**@return*@throwsException*/publicstaticStringinitKey()throwsException{returninitKey(null);}/***//***生成密鑰**@paramseed*@return*@throwsException*/publicstaticStringinitKey(Stringseed)throwsException{SecureRandomsecureRandom=null;if(seed!=null){secureRandom=newSecureRandom(decryptBASE (seed));}else{secureRandom=newSecureRandom();}KeyGeneratorkg=KeyGenerator getInstance(ALGORITHM);kg init(secureRandom);SecretKeysecretKey=kg generateKey();returnencryptBASE (secretKey getEncoded());}}
延續上一個類的實現 我們通過MD 以及SHA對字元串加密生成密鑰 這是比較常見的密鑰生成方式
再給出一個測試類
importstatic junit Assert *;import junit Test;/***//****@authorby;;*@version *@since */publicclassDESCoderTest{@Testpublicvoidtest()throwsException{StringinputStr= DES ;Stringkey=DESCoder initKey();System err println( 原文: +inputStr);System err println( 密鑰: +key);byte[]inputData=inputStr getBytes();inputData=DESCoder encrypt(inputData key);System err println( 加密後: +DESCoder encryptBASE (inputData));byte[]outputData=DESCoder decrypt(inputData key);StringoutputStr=newString(outputData);System err println( 解密後: +outputStr);assertEquals(inputStr outputStr);}}
得到的輸出內容如下
原文 DES
密鑰 f wEtRrV q =
加密後 C qe oNIzRY=
解密後 DES
由控制台得到的輸出 我們能夠比對加密 解密後結果一致 這是一種簡單的加密解密方式 只有一個密鑰
其實DES有很多同胞兄弟 如DESede(TripleDES) AES Blowfish RC RC (ARCFOUR) 這里就不過多闡述了 大同小異 只要換掉ALGORITHM換成對應的值 同時做一個代碼替換SecretKey secretKey = new SecretKeySpec(key ALGORITHM) 就可以了 此外就是密鑰長度不同了
/**
lishixin/Article/program/Java/gj/201311/27624
⑶ 如何用JAVA實現字元串簡單加密解密
java加密字元串可以使用des加密演算法,實例如下:
package test;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.security.*;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
/**
* 加密解密
*
* @author shy.qiu
* @since http://blog.csdn.net/qiushyfm
*/
public class CryptTest {
/**
* 進行MD5加密
*
* @param info
* 要加密的信息
* @return String 加密後的字元串
*/
public String encryptToMD5(String info) {
byte[] digesta = null;
try {
// 得到一個md5的消息摘要
MessageDigest alga = MessageDigest.getInstance("MD5");
// 添加要進行計算摘要的信息
alga.update(info.getBytes());
// 得到該摘要
digesta = alga.digest();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
// 將摘要轉為字元串
String rs = byte2hex(digesta);
return rs;
}
/**
* 進行SHA加密
*
* @param info
* 要加密的信息
* @return String 加密後的字元串
*/
public String encryptToSHA(String info) {
byte[] digesta = null;
try {
// 得到一個SHA-1的消息摘要
MessageDigest alga = MessageDigest.getInstance("SHA-1");
// 添加要進行計算摘要的信息
alga.update(info.getBytes());
// 得到該摘要
digesta = alga.digest();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
// 將摘要轉為字元串
String rs = byte2hex(digesta);
return rs;
}
// //////////////////////////////////////////////////////////////////////////
/**
* 創建密匙
*
* @param algorithm
* 加密演算法,可用 DES,DESede,Blowfish
* @return SecretKey 秘密(對稱)密鑰
*/
public SecretKey createSecretKey(String algorithm) {
// 聲明KeyGenerator對象
KeyGenerator keygen;
// 聲明 密鑰對象
SecretKey deskey = null;
try {
// 返回生成指定演算法的秘密密鑰的 KeyGenerator 對象
keygen = KeyGenerator.getInstance(algorithm);
// 生成一個密鑰
deskey = keygen.generateKey();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
// 返回密匙
return deskey;
}
/**
* 根據密匙進行DES加密
*
* @param key
* 密匙
* @param info
* 要加密的信息
* @return String 加密後的信息
*/
public String encryptToDES(SecretKey key, String info) {
// 定義 加密演算法,可用 DES,DESede,Blowfish
String Algorithm = "DES";
// 加密隨機數生成器 (RNG),(可以不寫)
SecureRandom sr = new SecureRandom();
// 定義要生成的密文
byte[] cipherByte = null;
try {
// 得到加密/解密器
Cipher c1 = Cipher.getInstance(Algorithm);
// 用指定的密鑰和模式初始化Cipher對象
// 參數:(ENCRYPT_MODE, DECRYPT_MODE, WRAP_MODE,UNWRAP_MODE)
c1.init(Cipher.ENCRYPT_MODE, key, sr);
// 對要加密的內容進行編碼處理,
cipherByte = c1.doFinal(info.getBytes());
} catch (Exception e) {
e.printStackTrace();
}
// 返回密文的十六進制形式
return byte2hex(cipherByte);
}
/**
* 根據密匙進行DES解密
*
* @param key
* 密匙
* @param sInfo
* 要解密的密文
* @return String 返回解密後信息
*/
public String decryptByDES(SecretKey key, String sInfo) {
// 定義 加密演算法,
String Algorithm = "DES";
// 加密隨機數生成器 (RNG)
SecureRandom sr = new SecureRandom();
byte[] cipherByte = null;
try {
// 得到加密/解密器
Cipher c1 = Cipher.getInstance(Algorithm);
// 用指定的密鑰和模式初始化Cipher對象
c1.init(Cipher.DECRYPT_MODE, key, sr);
// 對要解密的內容進行編碼處理
cipherByte = c1.doFinal(hex2byte(sInfo));
} catch (Exception e) {
e.printStackTrace();
}
// return byte2hex(cipherByte);
return new String(cipherByte);
}
// /////////////////////////////////////////////////////////////////////////////
/**
* 創建密匙組,並將公匙,私匙放入到指定文件中
*
* 默認放入mykeys.bat文件中
*/
public void createPairKey() {
try {
// 根據特定的演算法一個密鑰對生成器
KeyPairGenerator keygen = KeyPairGenerator.getInstance("DSA");
// 加密隨機數生成器 (RNG)
SecureRandom random = new SecureRandom();
// 重新設置此隨機對象的種子
random.setSeed(1000);
// 使用給定的隨機源(和默認的參數集合)初始化確定密鑰大小的密鑰對生成器
keygen.initialize(512, random);// keygen.initialize(512);
// 生成密鑰組
KeyPair keys = keygen.generateKeyPair();
// 得到公匙
PublicKey pubkey = keys.getPublic();
// 得到私匙
PrivateKey prikey = keys.getPrivate();
// 將公匙私匙寫入到文件當中
doObjToFile("mykeys.bat", new Object[] { prikey, pubkey });
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
}
/**
* 利用私匙對信息進行簽名 把簽名後的信息放入到指定的文件中
*
* @param info
* 要簽名的信息
* @param signfile
* 存入的文件
*/
public void signToInfo(String info, String signfile) {
// 從文件當中讀取私匙
PrivateKey myprikey = (PrivateKey) getObjFromFile("mykeys.bat", 1);
// 從文件中讀取公匙
PublicKey mypubkey = (PublicKey) getObjFromFile("mykeys.bat", 2);
try {
// Signature 對象可用來生成和驗證數字簽名
Signature signet = Signature.getInstance("DSA");
// 初始化簽署簽名的私鑰
signet.initSign(myprikey);
// 更新要由位元組簽名或驗證的數據
signet.update(info.getBytes());
// 簽署或驗證所有更新位元組的簽名,返回簽名
byte[] signed = signet.sign();
// 將數字簽名,公匙,信息放入文件中
doObjToFile(signfile, new Object[] { signed, mypubkey, info });
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 讀取數字簽名文件 根據公匙,簽名,信息驗證信息的合法性
*
* @return true 驗證成功 false 驗證失敗
*/
public boolean validateSign(String signfile) {
// 讀取公匙
PublicKey mypubkey = (PublicKey) getObjFromFile(signfile, 2);
// 讀取簽名
byte[] signed = (byte[]) getObjFromFile(signfile, 1);
// 讀取信息
String info = (String) getObjFromFile(signfile, 3);
try {
// 初始一個Signature對象,並用公鑰和簽名進行驗證
Signature signetcheck = Signature.getInstance("DSA");
// 初始化驗證簽名的公鑰
signetcheck.initVerify(mypubkey);
// 使用指定的 byte 數組更新要簽名或驗證的數據
signetcheck.update(info.getBytes());
System.out.println(info);
// 驗證傳入的簽名
return signetcheck.verify(signed);
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 將二進制轉化為16進制字元串
*
* @param b
* 二進制位元組數組
* @return String
*/
public String byte2hex(byte[] b) {
String hs = "";
String stmp = "";
for (int n = 0; n < b.length; n++) {
stmp = (java.lang.Integer.toHexString(b[n] & 0XFF));
if (stmp.length() == 1) {
hs = hs + "0" + stmp;
} else {
hs = hs + stmp;
}
}
return hs.toUpperCase();
}
/**
* 十六進制字元串轉化為2進制
*
* @param hex
* @return
*/
public byte[] hex2byte(String hex) {
byte[] ret = new byte[8];
byte[] tmp = hex.getBytes();
for (int i = 0; i < 8; i++) {
ret[i] = uniteBytes(tmp[i * 2], tmp[i * 2 + 1]);
}
return ret;
}
/**
* 將兩個ASCII字元合成一個位元組; 如:"EF"--> 0xEF
*
* @param src0
* byte
* @param src1
* byte
* @return byte
*/
public static byte uniteBytes(byte src0, byte src1) {
byte _b0 = Byte.decode("0x" + new String(new byte[] { src0 }))
.byteValue();
_b0 = (byte) (_b0 << 4);
byte _b1 = Byte.decode("0x" + new String(new byte[] { src1 }))
.byteValue();
byte ret = (byte) (_b0 ^ _b1);
return ret;
}
/**
* 將指定的對象寫入指定的文件
*
* @param file
* 指定寫入的文件
* @param objs
* 要寫入的對象
*/
public void doObjToFile(String file, Object[] objs) {
ObjectOutputStream oos = null;
try {
FileOutputStream fos = new FileOutputStream(file);
oos = new ObjectOutputStream(fos);
for (int i = 0; i < objs.length; i++) {
oos.writeObject(objs[i]);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
oos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* 返回在文件中指定位置的對象
*
* @param file
* 指定的文件
* @param i
* 從1開始
* @return
*/
public Object getObjFromFile(String file, int i) {
ObjectInputStream ois = null;
Object obj = null;
try {
FileInputStream fis = new FileInputStream(file);
ois = new ObjectInputStream(fis);
for (int j = 0; j < i; j++) {
obj = ois.readObject();
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
ois.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return obj;
}
/**
* 測試
*
* @param args
*/
public static void main(String[] args) {
CryptTest jiami = new CryptTest();
// 執行MD5加密"Hello world!"
System.out.println("Hello經過MD5:" + jiami.encryptToMD5("Hello"));
// 生成一個DES演算法的密匙
SecretKey key = jiami.createSecretKey("DES");
// 用密匙加密信息"Hello world!"
String str1 = jiami.encryptToDES(key, "Hello");
System.out.println("使用des加密信息Hello為:" + str1);
// 使用這個密匙解密
String str2 = jiami.decryptByDES(key, str1);
System.out.println("解密後為:" + str2);
// 創建公匙和私匙
jiami.createPairKey();
// 對Hello world!使用私匙進行簽名
jiami.signToInfo("Hello", "mysign.bat");
// 利用公匙對簽名進行驗證。
if (jiami.validateSign("mysign.bat")) {
System.out.println("Success!");
} else {
System.out.println("Fail!");
}
}
}
⑷ 怎麼對加密的JAVA class文件進行解密
JAVA class文件加密解密
package com..encrypt;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.RandomAccessFile;
public class FileEncryptAndDecrypt {
/**
* 文件file進行加密
* @param fileUrl 文件路徑
* @param key 密碼
* @throws Exception
*/
public static void encrypt(String fileUrl, String key) throws Exception {
File file = new File(fileUrl);
String path = file.getPath();
if(!file.exists()){
return;
}
int index = path.lastIndexOf("迅掘雀\\");
String destFile = path.substring(0, index)+"\\"+"abc";
File dest = new File(destFile);
InputStream in = new FileInputStream(fileUrl);
OutputStream out = new FileOutputStream(destFile);
byte[] buffer = new byte[1024];
int r;
byte[] buffer2=new byte[1024];
while (( r= in.read(buffer)) > 0) {
for(int i=0;i<r;i++)
{
byte b=buffer[i];
buffer2[i]=b==255?0:++b;
}
out.write(buffer2, 0, r);
out.flush();
}
in.close();
out.close();
file.delete();
dest.renameTo(new File(fileUrl));
appendMethodA(fileUrl, key);
System.out.println("加密成功"散野);
}
/**
*
* @param fileName
* @param content 密鑰
*/
public static void appendMethodA(String fileName, String content) {
try {
// 打開一個隨畝早機訪問文件流,按讀寫方式
RandomAccessFile randomFile = new RandomAccessFile(fileName, "rw");
// 文件長度,位元組數
long fileLength = randomFile.length();
//將寫文件指針移到文件尾。
randomFile.seek(fileLength);
randomFile.writeBytes(content);
randomFile.close();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 解密
* @param fileUrl 源文件
* @param tempUrl 臨時文件
* @param ketLength 密碼長度
* @return
* @throws Exception
*/
public static String decrypt(String fileUrl, String tempUrl, int keyLength) throws Exception{
File file = new File(fileUrl);
if (!file.exists()) {
return null;
}
File dest = new File(tempUrl);
if (!dest.getParentFile().exists()) {
dest.getParentFile().mkdirs();
}
InputStream is = new FileInputStream(fileUrl);
OutputStream out = new FileOutputStream(tempUrl);
byte[] buffer = new byte[1024];
byte[] buffer2=new byte[1024];
byte bMax=(byte)255;
long size = file.length() - keyLength;
int mod = (int) (size%1024);
int div = (int) (size>>10);
int count = mod==0?div:(div+1);
int k = 1, r;
while ((k <= count && ( r = is.read(buffer)) > 0)) {
if(mod != 0 && k==count) {
r = mod;
}
for(int i = 0;i < r;i++)
{
byte b=buffer[i];
buffer2[i]=b==0?bMax:--b;
}
out.write(buffer2, 0, r);
k++;
}
out.close();
is.close();
return tempUrl;
}
/**
* 判斷文件是否加密
* @param fileName
* @return
*/
public static String readFileLastByte(String fileName, int keyLength) {
File file = new File(fileName);
if(!file.exists())return null;
StringBuffer str = new StringBuffer();
try {
// 打開一個隨機訪問文件流,按讀寫方式
RandomAccessFile randomFile = new RandomAccessFile(fileName, "r");
// 文件長度,位元組數
long fileLength = randomFile.length();
//將寫文件指針移到文件尾。
for(int i = keyLength ; i>=1 ; i--){
randomFile.seek(fileLength-i);
str.append((char)randomFile.read());
}
randomFile.close();
return str.toString();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
⑸ 用java寫個文件加密的代碼該怎麼寫
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.io.*;
import java.security.*;
import javax.crypto.*;
import javax.crypto.spec.*;
/**
文件名:FileEncrypter.java
JDK:1.40以上
說明:文件加密
加密方法:三重DES加密
加密過程:對選中的文件加密後在同文件夾下生成一個增加了".tdes"
擴展名的加密文件
解密過程:對選中的加密文件(必須有".tdes"擴展名)進行解密
*/
public class FileEncrypter extends JFrame{
public static final int WIDTH = 550;
public static final int HEIGHT = 200;
public static void main(String args[]) {
FileEncrypter fe = new FileEncrypter();
fe.show();
}
FileEncrypter(){
this.setSize(WIDTH,HEIGHT);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setResizable(false);
Toolkit tk = Toolkit.getDefaultToolkit();
Dimension screenSize = tk.getScreenSize();
this.setLocation((screenSize.width - WIDTH)/2,
(screenSize.height - HEIGHT)/2);
this.setTitle("文件加密器(TriDES)");
Container c = this.getContentPane();
c.setLayout( new FlowLayout());
final FilePanel fp = new FilePanel("文件選擇");
c.add(fp);
final KeyPanel pp = new KeyPanel("密碼");
c.add(pp);
JButton jbE = new JButton("加密");
c.add(jbE);
jbE.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent event){
File file = new File(fp.getFileName());
if (file.exists())
encrypt(file.getAbsoluteFile(),pp.getKey());
else
JOptionPane.showMessageDialog(
null,"請選擇文件!","提示",JOptionPane.OK_OPTION);
}
});
JButton jbD = new JButton("解密");
c.add(jbD);
jbD.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent event){
File file = new File(fp.getFileName());
if (file.exists())
decrypt(file.getAbsoluteFile(),pp.getKey());
else
JOptionPane.showMessageDialog(
null,"請選擇文件!","提示",JOptionPane.OK_OPTION);
}
});
}
/**
加密函數
輸入:
要加密的文件,密碼(由0-F組成,共48個字元,表示3個8位的密碼)如:
其中:
AD67EA2F3BE6E5AD DES密碼一
D368DFE03120B5DF DES密碼二
92A8FD8FEC2F0746 DES密碼三
輸出:
對輸入的文件加密後,保存到同一文件夾下增加了".tdes"擴展名的文件中。
*/
private void encrypt(File fileIn,String sKey){
try{
if(sKey.length() == 48){
byte[] bytK1 = getKeyByStr(sKey.substring(0,16));
byte[] bytK2 = getKeyByStr(sKey.substring(16,32));
byte[] bytK3 = getKeyByStr(sKey.substring(32,48));
FileInputStream fis = new FileInputStream(fileIn);
byte[] bytIn = new byte[(int)fileIn.length()];
for(int i = 0;i<FILEIN.LENGTH();I++){
bytIn[i] = (byte)fis.read();
}
//加密
byte[] bytOut = encryptByDES(encryptByDES(
encryptByDES(bytIn,bytK1),bytK2),bytK3);
String fileOut = fileIn.getPath() + ".tdes";
FileOutputStream fos = new FileOutputStream(fileOut);
for(int i = 0;i<BYTOUT.LENGTH;I++){
fos.write((int)bytOut[i]);
}
fos.close();
JOptionPane.showMessageDialog(
this,"加密成功!","提示",JOptionPane.OK_OPTION);
}else
JOptionPane.showMessageDialog(
this,"密碼長度必須等於48!","錯誤信息",JOptionPane.ERROR_MESSAGE);
}catch(Exception e){
e.printStackTrace();
}
}
/**
解密函數
輸入:
要解密的文件,密碼(由0-F組成,共48個字元,表示3個8位的密碼)如:
其中:
AD67EA2F3BE6E5AD DES密碼一
D368DFE03120B5DF DES密碼二
92A8FD8FEC2F0746 DES密碼三
輸出:
對輸入的文件解密後,保存到用戶指定的文件中。
*/
private void decrypt(File fileIn,String sKey){
try{
if(sKey.length() == 48){
String strPath = fileIn.getPath();
if(strPath.substring(strPath.length()-5).toLowerCase().equals(".tdes"))
strPath = strPath.substring(0,strPath.length()-5);
else{
JOptionPane.showMessageDialog(
this,"不是合法的加密文件!","提示",JOptionPane.OK_OPTION);
return;
}
JFileChooser chooser = new JFileChooser();
chooser.setCurrentDirectory(new File("."));
chooser.setSelectedFile(new File(strPath));
//用戶指定要保存的文件
int ret = chooser.showSaveDialog(this);
if(ret==JFileChooser.APPROVE_OPTION){
byte[] bytK1 = getKeyByStr(sKey.substring(0,16));
byte[] bytK2 = getKeyByStr(sKey.substring(16,32));
byte[] bytK3 = getKeyByStr(sKey.substring(32,48));
FileInputStream fis = new FileInputStream(fileIn);
byte[] bytIn = new byte[(int)fileIn.length()];
for(int i = 0;i<FILEIN.LENGTH();I++){
bytIn[i] = (byte)fis.read();
}
//解密
byte[] bytOut = decryptByDES(decryptByDES(
decryptByDES(bytIn,bytK3),bytK2),bytK1);
File fileOut = chooser.getSelectedFile();
fileOut.createNewFile();
FileOutputStream fos = new FileOutputStream(fileOut);
for(int i = 0;i<BYTOUT.LENGTH;I++){
fos.write((int)bytOut[i]);
}
fos.close();
JOptionPane.showMessageDialog(
this,"解密成功!","提示",JOptionPane.OK_OPTION);
}
}else
JOptionPane.showMessageDialog(
this,"密碼長度必須等於48!","錯誤信息",JOptionPane.ERROR_MESSAGE);
}catch(Exception e){
JOptionPane.showMessageDialog(
this,"解密失敗,請核對密碼!","提示",JOptionPane.OK_OPTION);
}
}
/**
用DES方法加密輸入的位元組
bytKey需為8位元組長,是加密的密碼
*/
private byte[] encryptByDES(byte[] bytP,byte[] bytKey) throws Exception{
DESKeySpec desKS = new DESKeySpec(bytKey);
SecretKeyFactory skf = SecretKeyFactory.getInstance("DES");
SecretKey sk = skf.generateSecret(desKS);
Cipher cip = Cipher.getInstance("DES");
cip.init(Cipher.ENCRYPT_MODE,sk);
return cip.doFinal(bytP);
}
/**
用DES方法解密輸入的位元組
bytKey需為8位元組長,是解密的密碼
*/
private byte[] decryptByDES(byte[] bytE,byte[] bytKey) throws Exception{
DESKeySpec desKS = new DESKeySpec(bytKey);
SecretKeyFactory skf = SecretKeyFactory.getInstance("DES");
SecretKey sk = skf.generateSecret(desKS);
Cipher cip = Cipher.getInstance("DES");
cip.init(Cipher.DECRYPT_MODE,sk);
return cip.doFinal(bytE);
}
/**
輸入密碼的字元形式,返回位元組數組形式。
如輸入字元串:AD67EA2F3BE6E5AD
返回位元組數組:{173,103,234,47,59,230,229,173}
*/
private byte[] getKeyByStr(String str){
byte[] bRet = new byte[str.length()/2];
for(int i=0;i<STR.LENGTH()
Integer itg =
new Integer(16*getChrInt(str.charAt(2*i)) + getChrInt(str.charAt(2*i+1)));
bRet[i] = itg.byteValue();
}
return bRet;
}
/**
計算一個16進制字元的10進制值
輸入:0-F
*/
private int getChrInt(char chr){
int iRet=0;
if(chr=="0".charAt(0)) iRet = 0;
if(chr=="1".charAt(0)) iRet = 1;
if(chr=="2".charAt(0)) iRet = 2;
if(chr=="3".charAt(0)) iRet = 3;
if(chr=="4".charAt(0)) iRet = 4;
if(chr=="5".charAt(0)) iRet = 5;
if(chr=="6".charAt(0)) iRet = 6;
if(chr=="7".charAt(0)) iRet = 7;
if(chr=="8".charAt(0)) iRet = 8;
if(chr=="9".charAt(0)) iRet = 9;
if(chr=="A".charAt(0)) iRet = 10;
if(chr=="B".charAt(0)) iRet = 11;
if(chr=="C".charAt(0)) iRet = 12;
if(chr=="D".charAt(0)) iRet = 13;
if(chr=="E".charAt(0)) iRet = 14;
if(chr=="F".charAt(0)) iRet = 15;
return iRet;
}
}
/**
文件選擇組件。
*/
class FilePanel extends JPanel{
FilePanel(String str){
JLabel label = new JLabel(str);
JTextField fileText = new JTextField(35);
JButton chooseButton = new JButton("瀏覽...");
this.add(label);
this.add(fileText);
this.add(chooseButton);
clickAction ca = new clickAction(this);
chooseButton.addActionListener(ca);
}
public String getFileName(){
JTextField jtf = (JTextField)this.getComponent(1);
return jtf.getText();
}
private class clickAction implements ActionListener{
clickAction(Component c){
cmpt = c;
}
public void actionPerformed(ActionEvent event){
JFileChooser chooser = new JFileChooser();
chooser.setCurrentDirectory(new File("."));
int ret = chooser.showOpenDialog(cmpt);
if(ret==JFileChooser.APPROVE_OPTION){
JPanel jp = (JPanel)cmpt;
JTextField jtf = (JTextField)jp.getComponent(1);
jtf.setText(chooser.getSelectedFile().getPath());
}
}
private Component cmpt;
}
}
/**
密碼生成組件。
*/
class KeyPanel extends JPanel{
KeyPanel(String str){
JLabel label = new JLabel(str);
JTextField fileText = new JTextField(35);
JButton chooseButton = new JButton("隨機產生");
this.add(label);
this.add(fileText);
this.add(chooseButton);
clickAction ca = new clickAction(this);
chooseButton.addActionListener(ca);
}
//返回生成的密碼(48個字元長度)
public String getKey(){
JTextField jtf = (JTextField)this.getComponent(1);
return jtf.getText();
}
private class clickAction implements ActionListener{
clickAction(Component c){
cmpt = c;
}
public void actionPerformed(ActionEvent event){
try{
KeyGenerator kg = KeyGenerator.getInstance("DES");
kg.init(56);
Key ke = kg.generateKey();
byte[] bytK1 = ke.getEncoded();
ke = kg.generateKey();
byte[] bytK2 = ke.getEncoded();
ke = kg.generateKey();
byte[] bytK3 = ke.getEncoded();
JPanel jp = (JPanel)cmpt;
JTextField jtf = (JTextField)jp.getComponent(1);
jtf.setText(getByteStr(bytK1)+getByteStr(bytK2)+getByteStr(bytK3));
}catch(Exception e){
e.printStackTrace();
}
}
private String getByteStr(byte[] byt){
String strRet = "";
for(int i=0;i<BYT.LENGTH;I++){
//System.out.println(byt[i]);
strRet += getHexValue((byt[i]&240)/16);
strRet += getHexValue(byt[i]&15);
}
return strRet;
}
private String getHexValue(int s){
String sRet=null;
switch (s){
case 0: sRet = "0";break;
case 1: sRet = "1";break;
case 2: sRet = "2";break;
case 3: sRet = "3";break;
case 4: sRet = "4";break;
case 5: sRet = "5";break;
case 6: sRet = "6";break;
case 7: sRet = "7";break;
case 8: sRet = "8";break;
case 9: sRet = "9";break;
case 10: sRet = "A";break;
case 11: sRet = "B";break;
case 12: sRet = "C";break;
case 13: sRet = "D";break;
case 14: sRet = "E";break;
case 15: sRet = "F";
}
return sRet;
}
private Component cmpt;
}
}
⑹ 如何通過JAVA對電腦中的文本文檔進行加密,最好能夠詳細的說一下!
package com.test.zc;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import javax.crypto.Cipher;
public class RSAEncrypt {
private KeyPairGenerator keyPairGen;
private KeyPair keyPair;
private RSAPrivateKey privateKey;
private RSAPublicKey publicKey;
public RSAEncrypt() {
try {
keyPairGen = KeyPairGenerator.getInstance("RSA");
keyPairGen.initialize(512);
keyPair = keyPairGen.generateKeyPair();
// Generate keys
privateKey = (RSAPrivateKey) keyPair.getPrivate();
publicKey = (RSAPublicKey) keyPair.getPublic();
} catch (NoSuchAlgorithmException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void main(String[] args) {
RSAEncrypt encrypt = new RSAEncrypt();
File file = new File(
"C:\\Documents and Settings\\Administrator.DCB5E0D91E0D436\\桌面\\test.txt");
File newFile = new File(
"C:\\Documents and Settings\\Administrator.DCB5E0D91E0D436\\桌面\\test1.txt");
encrypt.encryptFile(encrypt, file, newFile);
File file1 = new File(
"C:\\Documents and Settings\\Administrator.DCB5E0D91E0D436\\桌面\\test1.txt");
File newFile1 = new File(
"C:\\Documents and Settings\\Administrator.DCB5E0D91E0D436\\桌面\\test2.txt");
encrypt.decryptFile(encrypt, file1, newFile1);
}
public void encryptFile(RSAEncrypt encrypt, File file, File newFile) {
try {
InputStream is = new FileInputStream(file);
OutputStream os = new FileOutputStream(newFile);
byte[] bytes = new byte[53];
while (is.read(bytes) > 0) {
byte[] e = encrypt.encrypt(encrypt.publicKey, bytes);
bytes = new byte[53];
os.write(e, 0, e.length);
}
os.close();
is.close();
System.out.println("write success");
} catch (Exception e) {
e.printStackTrace();
}
}
public void decryptFile(RSAEncrypt encrypt, File file, File newFile) {
try {
InputStream is = new FileInputStream(
new File(
"C:\\Documents and Settings\\Administrator.DCB5E0D91E0D436\\桌面\\test1.txt"));
OutputStream os = new FileOutputStream(
"C:\\Documents and Settings\\Administrator.DCB5E0D91E0D436\\桌面\\test2.txt");
byte[] bytes1 = new byte[64];
while (is.read(bytes1) > 0) {
byte[] de = encrypt.decrypt(encrypt.privateKey, bytes1);
bytes1 = new byte[64];
os.write(de, 0, de.length);
}
os.close();
is.close();
System.out.println("write success");
} catch (Exception e) {
e.printStackTrace();
}
}
/** */
/**
* * Encrypt String. *
*
* @return byte[]
*/
protected byte[] encrypt(RSAPublicKey publicKey, byte[] obj) {
if (publicKey != null) {
try {
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.ENCRYPT_MODE, publicKey);
return cipher.doFinal(obj);
} catch (Exception e) {
e.printStackTrace();
}
}
return null;
}
/** */
/**
* * Basic decrypt method *
*
* @return byte[]
*/
protected byte[] decrypt(RSAPrivateKey privateKey, byte[] obj) {
if (privateKey != null) {
try {
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.DECRYPT_MODE, privateKey);
return cipher.doFinal(obj);
} catch (Exception e) {
e.printStackTrace();
}
}
return null;
}
}
注意,RSAPrivateKey與RSAPublicKey在加密和解密中需保持一致,如果加密與解密需要分開進行,則需要把RSAPrivateKey與RSAPublicKey寫入文件或其他方式保存進行解密
⑺ java密碼加密與解密
以下兩個類可以很方便的完成字元串的加密和解密
加密 CryptHelper encrypt(password)
解密 CrypHelper decrypt(password)
代碼如下
CryptUtils java
[java]
package gdie lab crypt;
import java io IOException;
import javax crypto Cipher;
import javax crypto KeyGenerator;
import javax crypto SecretKey;
import apache xerces internal impl dv util Base ;
public class CryptUtils {
private static String Algorithm = DES ;
private static byte[] DEFAULT_KEY=new byte[] { };
private static String VALUE_ENCODING= UTF ;
/**
* 生成密鑰
*
* @return byte[] 返回生成的密鑰
* @throws exception
* 扔出異常
*/
public static byte[] getSecretKey() throws Exception {
KeyGenerator keygen = KeyGenerator getInstance(Algorithm)
SecretKey deskey = keygen generateKey()
// if (debug ) System out println ( 生成密鑰 +byte hex (deskey getEncoded
// ()))
return deskey getEncoded()
}
/**
* 將指定的數據根據提供的密鑰進行加密
*
* @param input
* 需要加密的數據
* @param key
* 密鑰
* @return byte[] 加密後的數據
* @throws Exception
*/
public static byte[] encryptData(byte[] input byte[] key) throws Exception {
SecretKey deskey = new javax crypto spec SecretKeySpec(key Algorithm)
// if (debug )
// {
// System out println ( 加密前的二進串 +byte hex (input ))
// System out println ( 加密前的字元串 +new String (input ))
//
// }
Cipher c = Cipher getInstance(Algorithm)
c init(Cipher ENCRYPT_MODE deskey)
byte[] cipherByte = c doFinal(input)
// if (debug ) System out println ( 加密後的二進串 +byte hex (cipherByte ))
return cipherByte;
}
public static byte[] encryptData(byte[] input) throws Exception {
return encryptData(input DEFAULT_KEY)
}
/**
* 將給定的已加密的數據通過指定的密鑰進行解密
*
* @param input
* 待解密的數據
* @param key
* 密鑰
* @return byte[] 解密後的數據
* @throws Exception
*/
public static byte[] decryptData(byte[] input byte[] key) throws Exception {
SecretKey deskey = new javax crypto spec SecretKeySpec(key Algorithm)
// if (debug ) System out println ( 解密前的信息 +byte hex (input ))
Cipher c = Cipher getInstance(Algorithm)
c init(Cipher DECRYPT_MODE deskey)
byte[] clearByte = c doFinal(input)
// if (debug )
// {
// System out println ( 解密後的二進串 +byte hex (clearByte ))
// System out println ( 解密後的字元串 +(new String (clearByte )))
//
// }
return clearByte;
}
public static byte[] decryptData(byte[] input) throws Exception {
return decryptData(input DEFAULT_KEY)
}
/**
* 位元組碼轉換成 進制字元串
*
* @param byte[] b 輸入要轉換的位元組碼
* @return String 返回轉換後的 進制字元串
*/
public static String byte hex(byte[] bytes) {
StringBuilder hs = new StringBuilder()
for(byte b : bytes)
hs append(String format( % $ X b))
return hs toString()
}
public static byte[] hex byte(String content) {
int l=content length()》 ;
byte[] result=new byte[l];
for(int i= ;i<l;i++) {
int j=i《 ;
String s=content substring(j j+ )
result[i]=Integer valueOf(s ) byteValue()
}
return result;
}
/**
* 將位元組數組轉換為base 編碼字元串
* @param buffer
* @return
*/
public static String bytesToBase (byte[] buffer) {
//BASE Encoder en=new BASE Encoder()
return Base encode(buffer)
// return encoder encode(buffer)
}
/**
* 將base 編碼的字元串解碼為位元組數組
* @param value
* @return
* @throws IOException
*/
public static byte[] base ToBytes(String value) throws IOException {
//return Base decodeToByteArray(value)
// System out println(decoder decodeBuffer(value))
// return decoder decodeBuffer(value)
return Base decode(value)
}
/**
* 加密給定的字元串
* @param value
* @return 加密後的base 字元串
*/
public static String encryptString(String value) {
return encryptString(value DEFAULT_KEY)
}
/**
* 根據給定的密鑰加密字元串
* @param value 待加密的字元串
* @param key 以BASE 形式存在的密鑰
* @return 加密後的base 字元串
* @throws IOException
*/
public static String encryptString(String value String key) throws IOException {
return encryptString(value base ToBytes(key))
}
/**
* 根據給定的密鑰加密字元串
* @param value 待加密的字元串
* @param key 位元組數組形式的密鑰
* @return 加密後的base 字元串
*/
public static String encryptString(String value byte[] key) {
try {
byte[] data=value getBytes(VALUE_ENCODING)
data=CryptUtils encryptData(data key)
return bytesToBase (data)
} catch (Exception e) {
// TODO Auto generated catch block
e printStackTrace()
return null;
}
}
/**
* 解密字元串
* @param value base 形式存在的密文
* @return 明文
*/
public static String decryptString(String value) {
return decryptString(value DEFAULT_KEY)
}
/**
* 解密字元串
* @param value base 形式存在的密文
* @param key base 形式存在的密鑰
* @return 明文
* @throws IOException
*/
public static String decryptString(String value String key) throws IOException {
String s=decryptString(value base ToBytes(key))
return s;
}
/**
* 解密字元串
* @param value base 形式存在的密文
* @param key 位元組數據形式存在的密鑰
* @return 明文
*/
public static String decryptString(String value byte[] key) {
try {
byte[] data=base ToBytes(value)
data=CryptUtils decryptData(data key)
return new String(data VALUE_ENCODING)
}catch(Exception e) {
e printStackTrace()
return null;
}
}
}
package gdie lab crypt;
import java io IOException;
import javax crypto Cipher;
import javax crypto KeyGenerator;
import javax crypto SecretKey;
import apache xerces internal impl dv util Base ;
public class CryptUtils {
private static String Algorithm = DES ;
private static byte[] DEFAULT_KEY=new byte[] { };
private static String VALUE_ENCODING= UTF ;
/**
* 生成密鑰
*
* @return byte[] 返回生成的密鑰
* @throws exception
* 扔出異常
*/
public static byte[] getSecretKey() throws Exception {
KeyGenerator keygen = KeyGenerator getInstance(Algorithm)
SecretKey deskey = keygen generateKey()
// if (debug ) System out println ( 生成密鑰 +byte hex (deskey getEncoded
// ()))
return deskey getEncoded()
}
/**
* 將指定的數據根據提供的密鑰進行加密
*
* @param input
* 需要加密的數據
* @param key
* 密鑰
* @return byte[] 加密後的數據
* @throws Exception
*/
public static byte[] encryptData(byte[] input byte[] key) throws Exception {
SecretKey deskey = new javax crypto spec SecretKeySpec(key Algorithm)
// if (debug )
// {
// System out println ( 加密前的二進串 +byte hex (input ))
// System out println ( 加密前的字元串 +new String (input ))
//
// }
Cipher c = Cipher getInstance(Algorithm)
c init(Cipher ENCRYPT_MODE deskey)
byte[] cipherByte = c doFinal(input)
// if (debug ) System out println ( 加密後的二進串 +byte hex (cipherByte ))
return cipherByte;
}
public static byte[] encryptData(byte[] input) throws Exception {
return encryptData(input DEFAULT_KEY)
}
/**
* 將給定的已加密的數據通過指定的密鑰進行解密
*
* @param input
* 待解密的數據
* @param key
* 密鑰
* @return byte[] 解密後的數據
* @throws Exception
*/
public static byte[] decryptData(byte[] input byte[] key) throws Exception {
SecretKey deskey = new javax crypto spec SecretKeySpec(key Algorithm)
// if (debug ) System out println ( 解密前的信息 +byte hex (input ))
Cipher c = Cipher getInstance(Algorithm)
c init(Cipher DECRYPT_MODE deskey)
byte[] clearByte = c doFinal(input)
// if (debug )
// {
// System out println ( 解密後的二進串 +byte hex (clearByte ))
// System out println ( 解密後的字元串 +(new String (clearByte )))
//
// }
return clearByte;
}
public static byte[] decryptData(byte[] input) throws Exception {
return decryptData(input DEFAULT_KEY)
}
/**
* 位元組碼轉換成 進制字元串
*
* @param byte[] b 輸入要轉換的位元組碼
* @return String 返回轉換後的 進制字元串
*/
public static String byte hex(byte[] bytes) {
StringBuilder hs = new StringBuilder()
for(byte b : bytes)
hs append(String format( % $ X b))
return hs toString()
}
public static byte[] hex byte(String content) {
int l=content length()》 ;
byte[] result=new byte[l];
for(int i= ;i<l;i++) {
int j=i《 ;
String s=content substring(j j+ )
result[i]=Integer valueOf(s ) byteValue()
}
return result;
}
/**
* 將位元組數組轉換為base 編碼字元串
* @param buffer
* @return
*/
public static String bytesToBase (byte[] buffer) {
//BASE Encoder en=new BASE Encoder()
return Base encode(buffer)
// return encoder encode(buffer)
}
/**
* 將base 編碼的字元串解碼為位元組數組
* @param value
* @return
* @throws IOException
*/
public static byte[] base ToBytes(String value) throws IOException {
//return Base decodeToByteArray(value)
// System out println(decoder decodeBuffer(value))
// return decoder decodeBuffer(value)
return Base decode(value)
}
/**
* 加密給定的字元串
* @param value
* @return 加密後的base 字元串
*/
public static String encryptString(String value) {
return encryptString(value DEFAULT_KEY)
}
/**
* 根據給定的密鑰加密字元串
* @param value 待加密的字元串
* @param key 以BASE 形式存在的密鑰
* @return 加密後的base 字元串
* @throws IOException
*/
public static String encryptString(String value String key) throws IOException {
return encryptString(value base ToBytes(key))
}
/**
* 根據給定的密鑰加密字元串
* @param value 待加密的字元串
* @param key 位元組數組形式的密鑰
* @return 加密後的base 字元串
*/
public static String encryptString(String value byte[] key) {
try {
byte[] data=value getBytes(VALUE_ENCODING)
data=CryptUtils encryptData(data key)
return bytesToBase (data)
} catch (Exception e) {
// TODO Auto generated catch block
e printStackTrace()
return null;
}
}
/**
* 解密字元串
* @param value base 形式存在的密文
* @return 明文
*/
public static String decryptString(String value) {
return decryptString(value DEFAULT_KEY)
}
/**
* 解密字元串
* @param value base 形式存在的密文
* @param key base 形式存在的密鑰
* @return 明文
* @throws IOException
*/
public static String decryptString(String value String key) throws IOException {
String s=decryptString(value base ToBytes(key))
return s;
}
/**
* 解密字元串
* @param value base 形式存在的密文
* @param key 位元組數據形式存在的密鑰
* @return 明文
*/
public static String decryptString(String value byte[] key) {
try {
byte[] data=base ToBytes(value)
data=CryptUtils decryptData(data key)
return new String(data VALUE_ENCODING)
}catch(Exception e) {
e printStackTrace()
return null;
}
}
}
CryptHelper java
[java]
package gdie lab crypt;
import javax crypto Cipher;
import javax crypto SecretKey;
import javax crypto SecretKeyFactory;
import javax crypto spec DESKeySpec;
import javax crypto spec IvParameterSpec;
import springframework util DigestUtils;
public class CryptHelper{
private static String CRYPT_KEY = zhongqian ;
//加密
private static Cipher ecip;
//解密
private static Cipher dcip;
static {
try {
String KEY = DigestUtils md DigestAsHex(CRYPT_KEY getBytes()) toUpperCase()
KEY = KEY substring( )
byte[] bytes = KEY getBytes()
DESKeySpec ks = new DESKeySpec(bytes)
SecretKeyFactory skf = SecretKeyFactory getInstance( DES )
SecretKey sk = skf generateSecret(ks)
IvParameterSpec iv = new IvParameterSpec(bytes)
ecip = Cipher getInstance( DES/CBC/PKCS Padding )
ecip init(Cipher ENCRYPT_MODE sk iv )
dcip = Cipher getInstance( DES/CBC/PKCS Padding )
dcip init(Cipher DECRYPT_MODE sk iv )
}catch(Exception ex) {
ex printStackTrace()
}
}
public static String encrypt(String content) throws Exception {
byte[] bytes = ecip doFinal(content getBytes( ascii ))
return CryptUtils byte hex(bytes)
}
public static String decrypt(String content) throws Exception {
byte[] bytes = CryptUtils hex byte(content)
bytes = dcip doFinal(bytes)
return new String(bytes ascii )
}
//test
public static void main(String[] args) throws Exception {
String password = gly ;
String en = encrypt(password)
System out println(en)
System out println(decrypt(en))
}
}
package gdie lab crypt;
import javax crypto Cipher;
import javax crypto SecretKey;
import javax crypto SecretKeyFactory;
import javax crypto spec DESKeySpec;
import javax crypto spec IvParameterSpec;
import springframework util DigestUtils;
public class CryptHelper{
private static String CRYPT_KEY = zhongqian ;
//加密
private static Cipher ecip;
//解密
private static Cipher dcip;
static {
try {
String KEY = DigestUtils md DigestAsHex(CRYPT_KEY getBytes()) toUpperCase()
KEY = KEY substring( )
byte[] bytes = KEY getBytes()
DESKeySpec ks = new DESKeySpec(bytes)
SecretKeyFactory skf = SecretKeyFactory getInstance( DES )
SecretKey sk = skf generateSecret(ks)
IvParameterSpec iv = new IvParameterSpec(bytes)
ecip = Cipher getInstance( DES/CBC/PKCS Padding )
ecip init(Cipher ENCRYPT_MODE sk iv )
dcip = Cipher getInstance( DES/CBC/PKCS Padding )
dcip init(Cipher DECRYPT_MODE sk iv )
}catch(Exception ex) {
ex printStackTrace()
}
}
public static String encrypt(String content) throws Exception {
byte[] bytes = ecip doFinal(content getBytes( ascii ))
return CryptUtils byte hex(bytes)
}
public static String decrypt(String content) throws Exception {
byte[] bytes = CryptUtils hex byte(content)
bytes = dcip doFinal(bytes)
return new String(bytes ascii )
}
//test
public static void main(String[] args) throws Exception {
String password = gly ;
String en = encrypt(password)
System out println(en)
System out println(decrypt(en))
}
lishixin/Article/program/Java/hx/201311/26449
⑻ java des 加密 解密 密鑰隨機取得方法
java DES 加密 解密 生成隨機密鑰
舉例說明:
//保存生成的key
public static void saveDesKey() {
try {
SecureRandom sr = new SecureRandom();
// 選擇的DES演算法生成一個KeyGenerator對象
KeyGenerator kg = KeyGenerator.getInstance("DES");
kg.init(sr);
// 相對路徑 需要新建 conf 文件夾
// String fileName = "conf/DesKey.xml";
// 絕對路徑
String fileName = "d:/DesKey.xml";
FileOutputStream fos = new FileOutputStream(fileName);
ObjectOutputStream oos = new ObjectOutputStream(fos);
// 生成密鑰
Key key = kg.generateKey();
oos.writeObject(key);
oos.close();
} catch (Exception e) {
e.printStackTrace();
}
}
//獲取生成的key
public static Key getKey() {
Key kp = null;
try {
// 相對路徑 需要新建 conf 文件夾
// String fileName = "conf/DesKey.xml";
// InputStream is = Encrypt.class.getClassLoader().getResourceAsStream(fileName);
// 絕對路徑
String fileName = "d:/DesKey.xml";
FileInputStream is = new FileInputStream(fileName);
ObjectInputStream oos = new ObjectInputStream(is);
kp = (Key) oos.readObject();
oos.close();
} catch (Exception e) {
e.printStackTrace();
}
return kp;
}
//加密開始
public static void encrypt(String file, String dest) throws Exception {
Cipher cipher = Cipher.getInstance("DES");
cipher.init(Cipher.ENCRYPT_MODE, getKey());
InputStream is = new FileInputStream(file);
OutputStream out = new FileOutputStream(dest);
CipherInputStream cis = new CipherInputStream(is, cipher);
byte[] buffer = new byte[1024];
int r;
while ((r = cis.read(buffer)) > 0) {
out.write(buffer, 0, r);
}
cis.close();
is.close();
out.close();
}
//解密開始
public static void decrypt(String file, String dest) throws Exception {
Cipher cipher = Cipher.getInstance("DES");
cipher.init(Cipher.DECRYPT_MODE, getKey());
InputStream is = new FileInputStream(file);
OutputStream out = new FileOutputStream(dest);
CipherOutputStream cos = new CipherOutputStream(out, cipher);
byte[] buffer = new byte[1024];
int r;
while ((r = is.read(buffer)) >= 0) {
cos.write(buffer, 0, r);
}
cos.close();
out.close();
is.close();
}
}
//des加密主方法
public class DES {
public static void main(String[] args) throws Exception {
Encrypt.saveDesKey();
System.out.println("生成key");
Encrypt.getKey();
System.out.println("獲取key");
Encrypt.encrypt("d:\\hello.txt", "d:\\encrypt.txt");
System.out.println("加密");
Encrypt.decrypt("d:\\encrypt.txt", "d:\\decrypt.txt");
System.out.println("解密");
}
以上方法親測可用。