java加密解密des
⑴ 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("解密");
}
以上方法親測可用。
⑵ JAVA對DES加密解密的實現
用JAD反編譯JCE的源代碼就行了。
⑶ des加解密 JAVA加密 C++解密
做過 。。
快忘了 明天再告訴你
為甚非要要 C++ 解密呢? Java 加解密的有
以前幫老師做過,不過是老師提供了一個 .DLL 加密介面,我用java調用它加密,然後再用java 解密,也就是說沒有 C++ 加密實現代碼。。。。
至於 C++ 解密,由於 DES 加解密不依賴具體實現,也就是說不管是java 還是 C++ 加密後的密文都應該是一樣的,你另外再問一個題目求C++大蝦們貼一個C++版本的解密程序應該不難的,反正也有的是分。。。
先給你一個 Java 版本的加解密實現吧,代碼全部來自於網路,現在整理了一下現在歸還網路,就不單獨發給你了:
使用方法:
try{
DESCipher cipher= new DESCipher("password".getBytes());
cipher.doDecrypt(cipher.doEncrypt("PlainText".getBytes()));
}catch(Exceptione E){}
/**<p>
* =============================================================================
* <p> Copyright (c) 2008,Ren Java Studio
* <p> All rights reserved.<p>
* =============================================================================
* <p> 文件名稱:DESCipher.java
* <p> 文件標識:見配置管理計劃書
* <p> 摘 要:DES 數據加密程序
* <p> 較前一個版本增加了文件加密流技術和3重DES加密技術
* <p> 當前版本:3.0
* <p> 作 者:Ren
* <p> 完成日期:2008年5月13日
*
* <p> 取代版本:2.0
* <p> 作 者:Ren
* <p> 完成日期:2007.4.29.<p>
=============================================================================*/
package common.ciphers.symmetry;
public class DESCipher
extends SymmetryCipher
{
/**<p>
* =========================================================================
* <p> 默認構造器: 使用默認隨機密鑰
* @exception Exception 如果系統沒有安裝此類密碼機.<p>
=========================================================================*/
public DESCipher()
throws Exception
{
super( null, "DES" );
}
/**<p>
* =========================================================================
*<p> 用指定密鑰構造DES密鑰
* @param pwd 指定 DES 密碼
* @exception Exception 如果系統沒有安裝此類密碼機.<p>
=========================================================================*/
public DESCipher( byte[] pwd )
throws Exception
{
super( pwd, "DES" );
}
/**<p>
* =========================================================================
* <p> 本DES密碼機的演算法描述
* @return String 本 DES 密碼機的演算法描述.<p>
=========================================================================*/
public String toString()
{
return "DES 密碼機 Verison 3.0 Made By Ren"
+ super.toString();
}
}
package common.ciphers.symmetry;
import java.security.*;
import javax.crypto.*;
import javax.crypto.spec.SecretKeySpec;
/**<p>
* =============================================================================
* <p> Copyright (c) 2008,Ren Java Studio
* <p> All rights reserved.<p>
* =============================================================================
* <p> 文件名稱:SymmetryCipher.java
* <p> 文件標識:見配置管理計劃書
* <p> 摘 要:對稱密碼機之底層超類
* <p> 當前版本:1.0
* <p> 作 者:Ren
* <p> 完成日期:2008年5月18日.<p>
=============================================================================*/
public class SymmetryCipher {
/** 本密碼機實現的演算法 */
protected final String algorithm;
/** 客戶指定的用於加解密的密碼 */
private byte[] password = null;
/** 根據指定密碼生成的秘密密鑰 */
private SecretKey secretKey = null;
/** 系統的密碼機 */
private Cipher cipher = null;
/**<p>
* =========================================================================
* <p> 構造函數: 指定本密碼機的實現的演算法和加解密密碼
* @param pwd byte[] 客戶指定的用於加解密的密碼
* @param algorithm String 本密碼機實現的演算法
* @throws Exception 如果沒有此演算法的實現.<p>
=========================================================================*/
protected SymmetryCipher(byte[] pwd, String algorithm) throws Exception {
//使用SUN公司提供的密碼機
java.security.Security.addProvider(new com.sun.crypto.provider.SunJCE());
this.algorithm = algorithm;
initKey(pwd);
cipher = Cipher.getInstance(algorithm);
}
/**<p>
* =========================================================================
* <p> 根據客戶提供的密碼初始化本密碼機的密鑰信息
* @param pwd byte[] 客戶指定的密碼
* @throws Exception 如果沒有此演算法的實現.<p>
=========================================================================*/
private void initKey(byte[] pwd) throws Exception {
if (pwd != null) {
password = pwd;
secretKey = this.usePwdGenSecretKey(password);
} else {
//客戶沒有指定密碼時,那麼系統生成一個隨機密碼
password = this.genRandomSecretKey().getEncoded();
secretKey = this.usePwdGenSecretKey(password);
}
}
/**<p>
* =========================================================================
* <p> 用本密碼機的秘密密鑰加密指定的明文信息
* @param plainInfo byte[] 要求加密的明文信息
* @return byte[] 加密後的信息
* @throws Exception 加密過程出現錯誤.<p>
=========================================================================*/
public byte[] doEncrypt(byte[] plainInfo) throws Exception {
cipher.init(Cipher.ENCRYPT_MODE, this.secretKey);
return cipher.doFinal(plainInfo);
}
/*<p>
* =========================================================================
* <p> 用指定 密碼 加密指定明文信息
* @param desKey DES 密碼
* @param plainInfo 要求加密的明文信息
* @return byte[] 用指定密碼加密明文後的信息
* @exception java.lang.Exception 如果系統沒有安裝此類密碼機.<p>
=========================================================================*/
public byte[] doEncrypt(byte[] plainInfo, byte[] pwd) throws Exception {
cipher.init(Cipher.ENCRYPT_MODE, this.usePwdGenSecretKey(pwd));
return cipher.doFinal(plainInfo);
}
/**<p>
* =========================================================================
* <p> 用本密碼機的密碼解密指定的密文信息
* @param encryptedInfo byte[] 加過密的密文信息
* @return byte[] 解密結果
* @throws Exception 解密過程出現錯誤.<p>
=========================================================================*/
public byte[] doDecrypt(byte[] encryptedInfo) throws Exception {
cipher.init(Cipher.DECRYPT_MODE, this.secretKey);
return cipher.doFinal(encryptedInfo);
}
/*<p>
* =========================================================================
* <p> 用指定密鑰加密指定解密密文內容
* @param desKey DES 密鑰
* @param encryptText DES 密文
* @param byte[] 用指定密鑰解密DES密文後的信息
* @exception java.lang.Exception 如果系統沒有安裝此類密碼機.<p>
=========================================================================*/
public byte[] doDecrypt(byte[] encryptedInfo, byte[] pwd) throws Exception {
cipher.init(Cipher.DECRYPT_MODE, this.usePwdGenSecretKey(pwd));
return cipher.doFinal(encryptedInfo);
}
/**<p>
* =========================================================================
* <p> 根據本密碼機的演算法生成一個隨機密鑰
* @return SecretKey 生成的隨機密鑰
* @throws Exception 如果系統沒有此演算法的實現.<p>
=========================================================================*/
public final SecretKey genRandomSecretKey() throws Exception {
return genRandomSecretKey(this.algorithm);
}
/**<p>
* =========================================================================
* <p> 根據指定的演算法生成一把隨機密鑰
* @param algorithm String 客戶指定的演算法
* @return SecretKey 生成的隨機密鑰
* @throws Exception 如果系統沒有此演算法的實現.<p>
=========================================================================*/
public final static SecretKey genRandomSecretKey(String algorithm) throws
Exception {
KeyGenerator keygen = KeyGenerator.getInstance(algorithm);
SecureRandom random = new SecureRandom();
keygen.init(random);
return keygen.generateKey();
}
/**<p>
* =========================================================================
* <p> 用客戶自己定義的 密碼 根據本密碼機的演算法生成一個密鑰信息
* @param pwd byte[] 密碼信息
* @return SecretKey 根據密碼生成的密鑰信息.<p>
* @exception Exception 如果系統沒有安裝此演算法的實現.<p>
=========================================================================*/
public SecretKey usePwdGenSecretKey(byte[] pwd) throws Exception {
return usePwdGenSecretKey(pwd, this.algorithm);
}
/**<p>
* =========================================================================
* <p> 用客戶自己定義的 密碼 和客戶定義的演算法生成一個密鑰信息
* @param pwd byte[] 客戶的密碼
* @param algorithm String 演算法名
* @return SecretKey 生成的秘密密鑰
* @throws Exception 如果系統沒有安裝此演算法的實現.<p>
=========================================================================*/
public final static SecretKey usePwdGenSecretKey(byte[] pwd,
String algorithm) throws Exception {
SecureRandom random = new SecureRandom(pwd);
KeyGenerator keygen = KeyGenerator.getInstance(algorithm);
keygen.init(random);
return keygen.generateKey();
}
/**<p>
* =========================================================================
* <p> 以指定 密鑰 位元組信息生成一個本密碼機指定的演算法的秘密密鑰
* @param rawKeys byte[] 密鑰位元組信息
* @return SecretKey 生成的密鑰信息
* @throws Exception 如果指定密鑰不符合此演算法規定的密鑰規范.<p>
=========================================================================*/
public final SecretKey useKeyGenecretKey(byte[] rawKeys) throws Exception {
return useKeyGenSecretKey(rawKeys, this.algorithm);
}
/**<p>
* =========================================================================
* <p> 以指定 密鑰 位元組信息生成一個秘密密鑰
* @param rawKeys byte[] 密鑰位元組信息
* @param algorithm 指定的演算法
* @return SecretKey 生成的密鑰信息
* @throws Exception 如果指定密鑰不符合此演算法規定的密鑰規范.<p>
=========================================================================*/
public final static SecretKey useKeyGenSecretKey(byte[] rawKeys,
String algorithm) throws Exception {
return SecretKeyFactory.getInstance(algorithm)
.generateSecret(new SecretKeySpec(rawKeys, algorithm));
}
/**<p>
* =========================================================================
* <p> 設置本密碼機的密碼,同時也會重新初始化密鑰信息
* @param pwd byte[] 客戶指定的密碼
* @throws Exception 密碼設置失敗.<p>
=========================================================================*/
public void setPassword(byte[] pwd) throws Exception {
initKey(pwd);
}
/**<p>
* =========================================================================
* <p> 用指定的密碼位元組信息生成本密碼機的秘密密鑰
* @param pwdKey byte[] 客戶指定的密碼信息
* @throws Exception 如果本密碼機未指定演算法.<p>
=========================================================================*/
public void setSecretKeyAsBytes(byte[] pwdKey) throws Exception {
this.setSecretKeyAsObj(this.usePwdGenSecretKey(pwdKey));
}
/**<p>
* =========================================================================
* <p> 用秘密密鑰指定本密碼機的秘密密鑰,對應的密碼設置為空
* @param sk SecretKey 客戶指定的秘密密鑰.<p>
=========================================================================*/
public void setSecretKeyAsObj(SecretKey sk) {
this.secretKey = sk;
password = null; //密碼復位,知道密鑰不能推知初始密碼;
}
/**<p>
* =========================================================================
* <p> 獲取秘密密鑰信息
* @return SecretKey 秘密密鑰.<p>
=========================================================================*/
public SecretKey getSecretKeyAsObj() {
return secretKey;
}
/**<p>
* =========================================================================
* <p> 獲取當前密鑰的位元組信息
* @return byte[] 密鑰位元組信息.<p>
=========================================================================*/
public byte[] getSecretKeyAsBytes() {
if (secretKey != null) {
return secretKey.getEncoded();
}
return null;
}
/**<p>
* =========================================================================
* <p> 獲取本密碼機的演算法
* @return String 本密碼機的演算法.<p>
=========================================================================*/
public String getAlgorithm() {
return this.algorithm;
}
/**<p>
* =========================================================================
* <p> 獲取客戶指定的密碼
* @return byte[] 客戶指定的密碼.<p>
=========================================================================*/
public byte[] getPassword() {
return password;
}
/**<p>
* =========================================================================
* <p> 獲取本密碼機的演算法描述
* @return String 本密碼機的演算法描述.<p>
=========================================================================*/
public String toString() {
return "本對稱密碼機實現之演算法: " + this.algorithm;
}
}
⑷ Java用Des方式加密之後,php怎麼解密
DES是一種標準的數據加密演算法,關於這個演算法的詳細介紹可以參考wiki和網路:
php中有一個擴展可以支持DES的加密演算法,是:extension=php_mcrypt.dll
在配置文件中將這個擴展打開還不能夠在windows環境下使用
需要將PHP文件夾下的 libmcrypt.dll 拷貝到系統的 system32 目錄下,這是通過phpinfo可以查看到mcrypt表示這個模塊可以正常試用了。
下面是PHP中使用DES加密解密的一個例子:
//$input - stuff to decrypt
//$key - the secret key to use
function do_mencrypt($input, $key)
{
$input = str_replace(""n", "", $input);
$input = str_replace(""t", "", $input);
$input = str_replace(""r", "", $input);
$key = substr(md5($key), 0, 24);
$td = mcrypt_mole_open('tripledes', '', 'ecb', '');
$iv = mcrypt_create_iv(mcrypt_enc_get_iv_size($td), MCRYPT_RAND);
mcrypt_generic_init($td, $key, $iv);
$encrypted_data = mcrypt_generic($td, $input);
mcrypt_generic_deinit($td);
mcrypt_mole_close($td);
return trim(chop(base64_encode($encrypted_data)));
}
//$input - stuff to decrypt
//$key - the secret key to use
function do_mdecrypt($input, $key)
{
$input = str_replace(""n", "", $input);
$input = str_replace(""t", "", $input);
$input = str_replace(""r", "", $input);
$input = trim(chop(base64_decode($input)));
$td = mcrypt_mole_open('tripledes', '', 'ecb', '');
$key = substr(md5($key), 0, 24);
$iv = mcrypt_create_iv(mcrypt_enc_get_iv_size($td), MCRYPT_RAND);
mcrypt_generic_init($td, $key, $iv);
$decrypted_data = mdecrypt_generic($td, $input);
mcrypt_generic_deinit($td);
mcrypt_mole_close($td);
return trim(chop($decrypted_data));
}
⑸ 求一個java des32加密解密演算法
packagecn.xinxi.des;
importjava.security.Key;
importjava.security.Security;
importjavax.crypto.Cipher;
importjavax.crypto.KeyGenerator;
importjavax.crypto.SecretKey;
importjavax.crypto.SecretKeyFactory;
importjavax.crypto.spec.DESKeySpec;
importorg.apache.commons.codec.binary.Hex;
importorg.bouncycastle.jce.provider.BouncyCastleProvider;
publicclassDES{
privatestaticfinalStringstr="xinxi";
publicstaticvoidmain(String[]args)throwsException{
();
bcDES();
}
publicstaticvoidjdkDES()throwsException{
//生成key
//KeyGenerator,密鑰生成器
KeyGeneratorkeyGenerator=KeyGenerator.getInstance("DES");
keyGenerator.init(56);//指定keysize這里使用默認值56位
//聲稱密鑰
SecretKeysecreKey=keyGenerator.generateKey();
byte[]bytesKey=secreKey.getEncoded();
//key轉換(恢復密鑰)
// SecretKeyconvertSecreKey=newSecretKeySpec(bytesKey,"DES");//與下面三行效果貌似差不多
DESKeySpecdesKeySpec=newDESKeySpec(bytesKey);
SecretKeyFactoryfactory=SecretKeyFactory.getInstance("DES");
// System.out.println(keyGenerator.getProvider());
KeyconvertSecreKey=factory.generateSecret(desKeySpec);
//加密
Ciphercipher=Cipher.getInstance("DES/ECB/PKCS5Padding");//加密演算法/工作方式/填充方式
cipher.init(Cipher.ENCRYPT_MODE,convertSecreKey);//模式(此處是加密模式)、key
byte[]result=cipher.doFinal(str.getBytes());//參數是要被加密的內容
System.out.println("JDKDES加密結果:"+Hex.encodeHexString(result));//轉成16進制
//解密生成key和key轉換與加密一樣
cipher.init(Cipher.DECRYPT_MODE,convertSecreKey);//模式(此處是解密模式)、key
result=cipher.doFinal(result);
System.out.println("JDKDES解密結果:"+newString(result));
}
publicstaticvoidbcDES()throwsException{
Security.addProvider(newBouncyCastleProvider());
//生成key
KeyGeneratorkeyGenerator=KeyGenerator.getInstance("DES","BC");
// System.out.println(keyGenerator.getProvider());
keyGenerator.init(56);//指定keysize這里使用默認值56位
SecretKeysecreKey=keyGenerator.generateKey();
byte[]bytesKey=secreKey.getEncoded();
//key轉換
DESKeySpecdesKeySpec=newDESKeySpec(bytesKey);
SecretKeyFactoryfactory=SecretKeyFactory.getInstance("DES");
KeyconvertSecreKey=factory.generateSecret(desKeySpec);
//加密
Ciphercipher=Cipher.getInstance("DES/ECB/PKCS5Padding");//加密演算法/工作方式/填充方式
cipher.init(Cipher.ENCRYPT_MODE,convertSecreKey);//模式(此處是加密模式)、key
byte[]result=cipher.doFinal(str.getBytes());//參數是要被加密的內容
System.out.println("BCDES加密結果:"+Hex.encodeHexString(result));//轉成16進制
//解密生成key和key轉換與加密一樣
cipher.init(Cipher.DECRYPT_MODE,convertSecreKey);//模式(此處是解密模式)、key
result=cipher.doFinal(result);
System.out.println("BCDES解密結果:"+newString(result));
}
}
是你想要的么?
⑹ Java中 DES加密演算法
三個文件:
一:skey_DES.java
//對稱秘鑰生成及對象化保存
import java.io.FileOutputStream;
import java.io.ObjectOutputStream;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
public class Skey_DES
{
public static void main(String args[])throws Exception
{
kg=KeyGenerator.getInstance("DESede");
kg.init(168);
SecretKey k=kg.generateKey();
FileOutputStream f=new FileOutputStream("key1.txt");
ObjectOutputStream b= new ObjectOutputStream(f);
b.writeObject(k);
}
};
二:SEnc.java
//對稱秘鑰加密,使用位元組碼
import java.io.*;
import java.security.*;
import javax.crypto.*;
public class SEnc
{
public static void main(String args[]) throws Exception
{
String s="";
FileInputStream f=new FileInputStream("key1.txt");
ObjectInputStream b=new ObjectInputStream(f);
Key k=(Key)b.readObject();
Cipher cp=Cipher.getInstance("DESede");
cp.init(Cipher.ENCRYPT_MODE,k);
byte ptext[]=s.getBytes("UTF8");
for(int i=0;i<ptext.length;i++)
{
System.out.print(ptext[i]+",");
}
System.out.println("");
byte ctext[]=cp.doFinal(ptext);
for(int i=0;i<ctext.length;i++)
{
System.out.print(ctext[i]+",");
}
FileOutputStream f2=new FileOutputStream("SEnc.txt");
f2.write(ctext);
}
};
三:SDec.java
//使用對稱秘鑰解密
import java.io.*;
import java.security.*;
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
public class SDec
{
public static void main(String args[])throws Exception
{
FileInputStream f=new FileInputStream("SEnc.txt");
int num=f.available();
byte[] ctext=new byte[num];
f.read(ctext);
FileInputStream f2=new FileInputStream("key1.txt");
ObjectInputStream b=new ObjectInputStream(f2);
Key k=(Key)b.readObject();
Cipher cp=Cipher.getInstance("DESede");
cp.init(Cipher.DECRYPT_MODE,k);
byte[] ptext=cp.doFinal(ctext);
String p=new String(ptext,"UTF8");
System.out.println(p);
}
};
⑺ Java DES加密解密演算法
package Encrypt;
import java.security.*;
import javax.crypto.*;
import sun.misc.*;
/**
* 使用DES加密與解密,可對byte[],String類型進行加密與解密
* 密文可使用String,byte[]存儲.
* 方法:
* void getKey(String strKey)從strKey的字條生成一個Key
* String getEncString(String strMing)對strMing進行加密,返回String密文
* String getDesString(String strMi)對strMin進行解密,返回String明文
* byte[] getEncCode(byte[] byteS)byte[]型的加密
* byte[] getDesCode(byte[] byteD)byte[]型的解密
*/
public class Encrypt{
private Key key;
private byte[] byteMi = null;
private byte[] byteMing = null;
private String strMi= "";
private String strM= "";
// 根據參數生成KEY
public void setKey(String strKey){
try{
KeyGenerator _generator = KeyGenerator.getInstance("DES");
_generator.init(new SecureRandom(strKey.getBytes()));
this.key = _generator.generateKey();
_generator=null;
}
catch(Exception e){
e.printStackTrace();
}
}
// 加密String明文輸入,String密文輸出
public void setEncString(String strMing){
BASE64Encoder base64en = new BASE64Encoder();
try {
this.byteMing = strMing.getBytes("UTF8");
this.byteMi = this.getEncCode(this.byteMing);
this.strMi = base64en.encode(this.byteMi);
}
catch(Exception e)
{
e.printStackTrace();
}
finally
{
this.byteMing = null;
this.byteMi = null;
}
}
//加密以byte[]明文輸入,byte[]密文輸出
private byte[] getEncCode(byte[] byteS){
byte[] byteFina = null;
Cipher cipher;
try
{
cipher = Cipher.getInstance("DES");
cipher.init(Cipher.ENCRYPT_MODE,key);
byteFina = cipher.doFinal(byteS);
}
catch(Exception e)
{
e.printStackTrace();
}
finally
{
cipher = null;
}
return byteFina;
}
// 解密:以String密文輸入,String明文輸出
public void setDesString(String strMi){
BASE64Decoder base64De = new BASE64Decoder();
try
{
this.byteMi = base64De.decodeBuffer(strMi);
this.byteMing = this.getDesCode(byteMi);
this.strM = new String(byteMing,"UTF8");
}
catch(Exception e)
{
e.printStackTrace();
}
finally
{
base64De = null;
byteMing = null;
byteMi = null;
}
}
// 解密以byte[]密文輸入,以byte[]明文輸出
private byte[] getDesCode(byte[] byteD){
Cipher cipher;
byte[] byteFina=null;
try{
cipher = Cipher.getInstance("DES");
cipher.init(Cipher.DECRYPT_MODE,key);
byteFina = cipher.doFinal(byteD);
}
catch(Exception e)
{
e.printStackTrace();
}
finally
{
cipher=null;
}
return byteFina;
}
//返回加密後的密文strMi
public String getStrMi()
{
return strMi;
}
//返回解密後的明文
public String getStrM()
{
return strM;
}
}
*注意:因為我用的時候是作為後台的BEAN來調用的,所以沒有寫main函數,也就不能直接運行了。必須加一個main()函數才能做為一個完成的JAVA程序使用。一個很簡單的 main()函數就ok了,不用我寫在這里了吧?呵呵!
在WEB前台調用這個BEAN文件時的語句:
<jsp:useBean id="abc" scope="page" class="oaweb.Encrypt" />
//id="abc" 用來初始化一個對象
<%
//明文加密:
String key = 「06」; //初始化密鑰。
abc.setKey(key); //調用set函數設置密鑰。
abc.setEncString(re[i][j]);//將要加密的明文傳送給Encrypt.java進行加密計算。
String Mi=abc.getStrMi(); //調用get函數獲取加密後密文。
%>
//變數Mi就是密文.
<%
//密文解密:
abc. setDesString(String Mi); //將要解密的密文傳送給Encrypt.java進行解密計算。
String M=abc. String getStrM(); //調用get函數獲取解密後明文。
%>
//變數M就是明文.
⑻ 用java實現des加密和解密
一個用來加密、解密的類
http://www.javanb.com/java/1/17816.html
import java.security.*;
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
/**
* 字元串工具集合
* @author Liudong
*/
public class StringUtils {
private static final String PASSWORD_CRYPT_KEY = "__jDlog_";
private final static String DES = "DES";
/**
* 加密
* @param src 數據源
* @param key 密鑰,長度必須是8的倍數
* @return 返回加密後的數據
* @throws Exception
*/
public static byte[] encrypt(byte[] src, byte[] key)throws Exception {
//DES演算法要求有一個可信任的隨機數源
SecureRandom sr = new SecureRandom();
// 從原始密匙數據創建DESKeySpec對象
DESKeySpec dks = new DESKeySpec(key);
// 創建一個密匙工廠,然後用它把DESKeySpec轉換成
// 一個SecretKey對象
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(DES);
SecretKey securekey = keyFactory.generateSecret(dks);
// Cipher對象實際完成加密操作
Cipher cipher = Cipher.getInstance(DES);
// 用密匙初始化Cipher對象
cipher.init(Cipher.ENCRYPT_MODE, securekey, sr);
// 現在,獲取數據並加密
// 正式執行加密操作
return cipher.doFinal(src);
}
/**
* 解密
* @param src 數據源
* @param key 密鑰,長度必須是8的倍數
* @return 返回解密後的原始數據
* @throws Exception
*/
public static byte[] decrypt(byte[] src, byte[] key)throws Exception {
// DES演算法要求有一個可信任的隨機數源
SecureRandom sr = new SecureRandom();
// 從原始密匙數據創建一個DESKeySpec對象
DESKeySpec dks = new DESKeySpec(key);
// 創建一個密匙工廠,然後用它把DESKeySpec對象轉換成
// 一個SecretKey對象
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(DES);
SecretKey securekey = keyFactory.generateSecret(dks);
// Cipher對象實際完成解密操作
Cipher cipher = Cipher.getInstance(DES);
// 用密匙初始化Cipher對象
cipher.init(Cipher.DECRYPT_MODE, securekey, sr);
// 現在,獲取數據並解密
// 正式執行解密操作
return cipher.doFinal(src);
}
/**
* 密碼解密
* @param data
* @return
* @throws Exception
*/
public final static String decrypt(String data){
try {
return new String(decrypt(hex2byte(data.getBytes()),
PASSWORD_CRYPT_KEY.getBytes()));
}catch(Exception e) {
}
return null;
}
/**
* 密碼加密
* @param password
* @return
* @throws Exception
*/
public final static String encrypt(String password){
try {
return byte2hex(encrypt(password.getBytes(),PASSWORD_CRYPT_KEY.getBytes())); }catch(Exception e) {
}
return null;
}
比較長, 轉了一部分.
⑼ DES加密演算法 java實現
package des;
import java.io.*;
import java.nio.*;
import java.nio.channels.FileChannel;
public class FileDES{
private static final boolean enc=true; //加密
private static final boolean dec=false; //解密
private String srcFileName;
private String destFileName;
private String inKey;
private boolean actionType;
private File srcFile;
private File destFile;
private Des des;
private void analyzePath(){
String dirName;
int pos=srcFileName.lastIndexOf("/");
dirName=srcFileName.substring(0,pos);
File dir=new File(dirName);
if (!.exists()){
System.err.println(dirName+" is not exist");
System.exit(1);
}else if(!dir.isDirectory()){
System.err.println(dirName+" is not a directory");
System.exit(1);
}
pos=destFileName.lastIndexOf("/");
dirName=destFileName.substring(0,pos);
dir=new File(dirName);
if (!dir.exists()){
if(!dir.mkdirs()){
System.out.println ("can not creat directory:"+dirName);
System.exit(1);
}
}else if(!dir.isDirectory()){
System.err.println(dirName+" is not a directory");
System.exit(1);
}
}
private static int replenish(FileChannel channel,ByteBuffer buf) throws IOException{
long byteLeft=channel.size()-channel.position();
if(byteLeft==0L)
return -1;
buf.position(0);
buf.limit(buf.position()+(byteLeft<8 ? (int)byteLeft :8));
return channel.read(buf);
}
private void file_operate(boolean flag){
des=new Des(inKey);
FileOutputStream outputFile=null;
try {
outputFile=new FileOutputStream(srcFile,true);
}catch (java.io.FileNotFoundException e) {
e.printStackTrace(System.err);
}
FileChannel outChannel=outputFile.getChannel();
try{
if(outChannel.size()%2!=0){
ByteBuffer bufTemp=ByteBuffer.allocate(1);
bufTemp.put((byte)32);
bufTemp.flip();
outChannel.position(outChannel.size());
outChannel.write(bufTemp);
bufTemp.clear();
}
}catch(Exception ex){
ex.printStackTrace(System.err);
System.exit(1);
}
FileInputStream inFile=null;
try{
inFile=new FileInputStream(srcFile);
}catch(java.io.FileNotFoundException e){
e.printStackTrace(System.err);
//System.exit(1);
}
outputFile=null;
try {
outputFile=new FileOutputStream(destFile,true);
}catch (java.io.FileNotFoundException e) {
e.printStackTrace(System.err);
}
FileChannel inChannel=inFile.getChannel();
outChannel=outputFile.getChannel();
ByteBuffer inBuf=ByteBuffer.allocate(8);
ByteBuffer outBuf=ByteBuffer.allocate(8);
try{
String srcStr;
String destStr;
while(true){
if (replenish(inChannel,inBuf)==-1) break;
srcStr=((ByteBuffer)(inBuf.flip())).asCharBuffer().toString();
inBuf.clear();
if (flag)
destStr=des.enc(srcStr,srcStr.length());
else
destStr=des.dec(srcStr,srcStr.length());
outBuf.clear();
if (destStr.length()==4){
for (int i = 0; i<4; i++) {
outBuf.putChar(destStr.charAt(i));
}
outBuf.flip();
}else{
outBuf.position(0);
outBuf.limit(2*destStr.length());
for (int i = 0; i<destStr.length(); i++) {
outBuf.putChar(destStr.charAt(i));
}
outBuf.flip();
}
try {
outChannel.write(outBuf);
outBuf.clear();
}catch (java.io.IOException ex) {
ex.printStackTrace(System.err);
}
}
System.out.println (inChannel.size());
System.out.println (outChannel.size());
System.out.println ("EoF reached.");
inFile.close();
outputFile.close();
}catch(java.io.IOException e){
e.printStackTrace(System.err);
System.exit(1);
}
}
public FileDES(String srcFileName,String destFileName,String inKey,boolean actionType){
this.srcFileName=srcFileName;
this.destFileName=destFileName;
this.actionType=actionType;
analyzePath();
srcFile=new File(srcFileName);
destFile=new File(destFileName);
this.inKey=inKey;
if (actionType==enc)
file_operate(enc);
else
file_operate(dec);
}
public static void main(String[] args){
String file1=System.getProperty("user.dir")+"/111.doc";
String file2=System.getProperty("user.dir")+"/222.doc";
String file3=System.getProperty("user.dir")+"/333.doc";
String passWord="1234ABCD";
FileDES fileDes=new FileDES(file1,file2,passWord,true);
FileDES fileDes1=new FileDES(file2,file3,passWord,false);
}
⑽ 如何使用JAVA實現對字元串的DES加密和解密
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 {
// 得到一個的消息摘要
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!");
}
}
}