bcprov-ext-jdk16-143.jar
應該放到你應用的classpath下。放ext中,修改java.security 我在windows系統下居然無效的。但在linux/unix下是好的
❷ java的 DES 加密解密方法 求對應php的加密解密方法!!!!急切
DES是一種標準的數據加密演算法,關於這個演算法的詳細介紹可以參考wiki和網路:
php中有一個擴展可以支持DES的加密演算法,是:extension=php_mcrypt.dll
在配置文件中將這個擴展打開還不能夠在windows環境下使用
需要將PHP文件夾下的 libmcrypt.dll 拷貝到系統的 system32 目錄下,這是通過phpinfo可以查看到mcrypt表示這個模塊可以正常試用了。
下面是PHP中使用DES加密解密的一個例子:
//$input-stufftodecrypt
//$key-thesecretkeytouse
functiondo_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);
returntrim(chop(base64_encode($encrypted_data)));
}
//$input-stufftodecrypt
//$key-thesecretkeytouse
functiondo_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);
returntrim(chop($decrypted_data));
}
參考自:http://www.cnblogs.com/cocowool/archive/2009/01/07/1371309.html
❸ Java中 DES加密演算法
package des;
import javax.crypto.Cipher;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import java.security.NoSuchAlgorithmException;
import sun.misc.*;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import javax.crypto.BadPaddingException;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.spec.SecretKeySpec;
import java.security.*;
import javax.crypto.SecretKeyFactory;
import java.security.spec.*;
import javax.crypto.spec.DESedeKeySpec;
/**
解密
*/
class DES {
private static String Algorithm = "DESede";//加密演算法的名稱
private static Cipher c;//密碼器
private static byte[] cipherByte;
private static SecretKey deskey;//密鑰
private static String keyString = "";//獲得密鑰的參數
//對base64編碼的string解碼成byte數組
public byte[] deBase64(String parm) throws IOException {
BASE64Decoder dec=new BASE64Decoder();
byte[] dnParm = dec.decodeBuffer(parm);
System.out.println(dnParm.length);
System.out.println(dnParm);
return dnParm;
}
//把密鑰參數轉為byte數組
public byte[] dBase64(String parm) throws IOException {
BASE64Decoder dec=new BASE64Decoder();
byte[] dnParm = dec.decodeBuffer(parm);
return dnParm;
}
/**
* 對 Byte 數組進行解密
* @param buff 要解密的數據
* @return 返回加密後的 String
*/
public static String createDecryptor(byte[] buff) throws
NoSuchPaddingException, NoSuchAlgorithmException,
UnsupportedEncodingException {
try {
c.init(Cipher.DECRYPT_MODE, deskey);//初始化密碼器,用密鑰deskey,進入解密模式
cipherByte = c.doFinal(buff);
}
catch(java.security.InvalidKeyException ex){
ex.printStackTrace();
}
catch(javax.crypto.BadPaddingException ex){
ex.printStackTrace();
}
catch(javax.crypto.IllegalBlockSizeException ex){
ex.printStackTrace();
}
return (new String(cipherByte,"UTF-8"));
}
public void getKey(String key) throws IOException, InvalidKeyException,
InvalidKeySpecException {
byte[] dKey = dBase64(key);
try {
deskey=new javax.crypto.spec.SecretKeySpec(dKey,Algorithm);
c = Cipher.getInstance(Algorithm);
}
catch (NoSuchPaddingException ex) {
}
catch (NoSuchAlgorithmException ex) {
}
}
public static void main(String args[]) throws IOException,
NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeySpecException,
InvalidKeyException, IOException {
DES des = new DES();
des.getKey(keyString);//獲取密鑰
byte[] dBy = des.deBase64("t0/fDOZ5NaQ=");//獲取需要解密的字元串
String dStr = des.createDecryptor(dBy);
System.out.println("解密:"+dStr);
}
}
❹ java DES加密
java可以調用C的dll,上網搜下用法,直接調用吧。
❺ java des加密,密鑰的長度是多少
3des演算法是指使用雙長度(16位元組)密鑰k=(kl||kr)將8位元組明文數據塊進行3次des加密/解密。如下所示:
y
=
des(kl)[des-1(kr)[des(kl[x])]]
解密方式為:
x
=
des-1
(kl)[des
(kr)[
des-1
(kl[y])]]
其中,des(kl[x])表示用密鑰k對數據x進行des加密,des-1
(kl[y])表示用密鑰k對數據y進行解密。
sessionkey的計算採用3des演算法,計算出單倍長度的密鑰。表示法為:sk
=
session(dk,data)
3des加密演算法為:
void
3des(byte
doublekeystr[16],
byte
data[8],
byte
out[8])
{
byte
buf1[8],
buf2[8];
des
(&doublekeystr[0],
data,
buf1);
udes(&doublekeystr[8],
buf1,
buf2);
des
(&doublekeystr[0],
buf2,
out);
}
❻ 用java實現DES加密演算法,細致點,要直接粘貼進平台能運行的!!
/*des密鑰生成代碼*/
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.spec.InvalidKeySpecException;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import com.huateng.util.common.Log;
public class GenKey {
private static final String DES = "DES";
public static final String SKEY_NAME = "key.des";
public static void genKey1(String path) {
// 密鑰
SecretKey skey = null;
// 密鑰隨機數生成
SecureRandom sr = new SecureRandom();
//生成密鑰文件
File file = genFile(path);
try {
// 獲取密鑰生成實例
KeyGenerator gen = KeyGenerator.getInstance(DES);
// 初始化密鑰生成器
gen.init(sr);
// 生成密鑰
skey = gen.generateKey();
// System.out.println(skey);
ObjectOutputStream oos = new ObjectOutputStream(
new FileOutputStream(file));
oos.writeObject(skey);
oos.close();
Log.sKeyPath(path);
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* @param file : 生成密鑰的路徑
* SecretKeyFactory 方式生成des密鑰
* */
public static void genKey2(String path) {
// 密鑰隨機數生成
SecureRandom sr = new SecureRandom();
// byte[] bytes = {11,12,44,99,76,45,1,8};
byte[] bytes = sr.generateSeed(20);
// 密鑰
SecretKey skey = null;
//生成密鑰文件路徑
File file = genFile(path);
try {
//創建deskeyspec對象
DESKeySpec desKeySpec = new DESKeySpec(bytes,9);
//實例化des密鑰工廠
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(DES);
//生成密鑰對象
skey = keyFactory.generateSecret(desKeySpec);
//寫出密鑰對象
ObjectOutputStream oos = new ObjectOutputStream(
new FileOutputStream(file));
oos.writeObject(skey);
oos.close();
Log.sKeyPath(path);
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (InvalidKeyException e) {
e.printStackTrace();
} catch (InvalidKeySpecException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
private static File genFile(String path) {
String temp = null;
File newFile = null;
if (path.endsWith("/") || path.endsWith("\\")) {
temp = path;
} else {
temp = path + "/";
}
File pathFile = new File(temp);
if (!pathFile.exists())
pathFile.mkdirs();
newFile = new File(temp+SKEY_NAME);
return newFile;
}
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
genKey2("E:/a/aa/");
}
}
/*加解密*/
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import javax.crypto.Cipher;
import javax.crypto.CipherInputStream;
import javax.crypto.SecretKey;
public class SecUtil {
public static void decrypt(String keyPath, String source, String dest) {
SecretKey key = null;
try
{
ObjectInputStream keyFile = new ObjectInputStream(
//讀取加密密鑰
new FileInputStream(keyPath));
key = (SecretKey) keyFile.readObject();
keyFile.close();
}
catch (FileNotFoundException ey1) {
throw new RuntimeException(ey1);
}
catch (Exception ey2) {
throw new RuntimeException(ey2);
}
//用key產生Cipher
Cipher cipher = null;
try {
//設置演算法,應該與加密時的設置一樣
cipher = Cipher.getInstance("DES");
//設置解密模式
cipher.init(Cipher.DECRYPT_MODE, key);
}
catch (Exception ey3) {
throw new RuntimeException(ey3);
}
//取得要解密的文件並解密
File file = new File(source);
String filename = file.getName();
try {
//輸出流,請注意文件名稱的獲取
BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(dest));
//輸入流
CipherInputStream in = new CipherInputStream(new BufferedInputStream(
new FileInputStream(file)), cipher);
int thebyte = 0;
while ( (thebyte = in.read()) != -1) {
out.write(thebyte);
}
in.close();
out.close();
}
catch (Exception ey5) {
throw new RuntimeException(ey5);
}
}
public static void encrypt(String keyPath, String source, String dest) {
SecretKey key = null;
try
{
ObjectInputStream keyFile = new ObjectInputStream(
//讀取加密密鑰
new FileInputStream(keyPath));
key = (SecretKey) keyFile.readObject();
keyFile.close();
}
catch (FileNotFoundException ey1) {
throw new RuntimeException(ey1);
}
catch (Exception ey2) {
throw new RuntimeException(ey2);
}
//用key產生Cipher
Cipher cipher = null;
try {
//設置演算法,應該與加密時的設置一樣
cipher = Cipher.getInstance("DES");
//設置解密模式
cipher.init(Cipher.ENCRYPT_MODE, key);
}
catch (Exception ey3) {
throw new RuntimeException(ey3);
}
//取得要解密的文件並解密
File file = new File(source);
String filename = file.getName();
try {
//輸出流,請注意文件名稱的獲取
BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(dest));
//輸入流
CipherInputStream in = new CipherInputStream(new BufferedInputStream(
new FileInputStream(file)), cipher);
int thebyte = 0;
while ( (thebyte = in.read()) != -1) {
out.write(thebyte);
}
in.close();
out.close();
}
catch (Exception ey5) {
throw new RuntimeException(ey5);
}
}
}
❼ Java 編寫的DES文件加密問題
DES 加密, 建議是將整個文件一次性加密 和 解密,中旅 而不州拆是每行。
每行的效率太低, 而安全性並沒賣跡凳有提高
❽ java des加密為什麼和網站
JAVA實現
加密
代碼有詳細解釋,不多廢話。
注意:DES加密和解密過程中,密鑰長度都必須是8的段行緩倍數
[java] view plain
public 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;
}
解密
代碼有詳細注釋,不多廢話
[java] view plain
private 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);
}
測試場景
例如,我們可以利用如上函數對字元串進行加密解密,也可以對文件進行加密解密,如:
[java] view plain
//待加密帶漏內容
String str = "測試內容";
//密碼,長度要是8的倍數
String password = "12345678";
byte[] result = DESCrypto.desCrypto(str.getBytes(),password);
System.out.println("加密後內容為:"+new String(result));
//直接將如上內容解密
try {
byte[] decryResult = des.decrypt(result, password);
System.out.println("加密後內容為:"+new String(decryResult));
} catch (Exception e1) {
e1.printStackTrace();
}
❾ java的 DES 加密解密方法 求對應C#的加密解密方法,急切
/*
* @param arrB 需要轉換的byte數組
* @return 轉換後的字元串
* @throws Exception 本方法不處理任何異常,所有異常全部拋出
*/
public static String byteArr2HexStr(byte[] arrB) throws Exception {
int iLen = arrB.length;
// 每個byte用兩個字元才能表示,所以字元串的長度是數組長度的兩倍
StringBuffer sb = new StringBuffer(iLen * 2);
for (int i = 0; i < iLen; i++) {
int intTmp = arrB[i];
// 把負數轉換為正數
while (intTmp < 0) {
intTmp = intTmp + 256;
}
// 小於0F的數需要在前面補0
if (intTmp < 16) {
sb.append("0");
}
sb.append(Integer.toString(intTmp, 16));
}
return sb.toString();
}
/*
* @param strIn 需要轉換的字元串
* @return 轉換後的byte數組
* @throws Exception 本方法不處理任何異常,所有異常全部拋出
*/
public static byte[] hexStr2ByteArr(String strIn) throws Exception {
byte[] arrB = strIn.getBytes();
int iLen = arrB.length;
// 兩個字元表示一個位元組,所以位元組數組長度是字元串長度除以2
byte[] arrOut = new byte[iLen / 2];
for (int i = 0; i < iLen; i = i + 2) {
String strTmp = new String(arrB, i, 2);
arrOut[i / 2] = (byte) Integer.parseInt(strTmp, 16);
}
return arrOut;
}
/**
* 加密位元組數組
*
* @param arrB
* 需加密的位元組數組
* @return 加密後的位元組數組
* @throws Exception
*/
@SuppressWarnings("restriction")
private static byte[] encrypt(byte[] arrB,String keyParameter) throws Exception {
Security.addProvider(new com.sun.crypto.provider.SunJCE());
Key key = getKey(keyParameter.getBytes());
Cipher encryptCipher = Cipher.getInstance("DES");
encryptCipher.init(Cipher.ENCRYPT_MODE, key);
return encryptCipher.doFinal(arrB);
}
/**
* 加密字元串
*
* @param strIn
* 需加密的字元串
* @return 加密後的字元串
* @throws Exception
*/
public static String encrypt(String strIn,String keyParameter) throws Exception {
return HexStrByteArrUtils.byteArr2HexStr(encrypt(strIn.getBytes(PiccConfig.PICC_INPUT_CHARSET),keyParameter));
}
/**
* 解密位元組數組
*
* @param arrB
* 需解密的位元組數組
* @return 解密後的位元組數組
* @throws Exception
*/
@SuppressWarnings("restriction")
private static byte[] decrypt(byte[] arrB,String keyParameter) throws Exception {
Security.addProvider(new com.sun.crypto.provider.SunJCE());
Key key = getKey(keyParameter.getBytes());
Cipher decryptCipher = Cipher.getInstance("DES");
decryptCipher.init(Cipher.DECRYPT_MODE, key);
return decryptCipher.doFinal(arrB);
}
/**
* 解密字元串
*
* @param strIn
* 需解密的字元串
* @return 解密後的字元串
* @throws Exception
*/
public static String decrypt(String strIn,String keyParameter) throws Exception {
return new String(decrypt(HexStrByteArrUtils.hexStr2ByteArr(strIn),keyParameter),PiccConfig.PICC_INPUT_CHARSET);
}
❿ 用java實現des演算法
分類: 電腦/網路 >> 程序設計 >> 其並運他編程語言
問題描述:
各位好,請求各位java學習者幫助釘解決這個問題。
我想用des演算法對我的名字進行加密
我也在網上下載了des演算法,包括FileDES,SubKey,Des各程序,
可能沒真正理解這些程序,所以我想調用都鍵讓不知道將這些東西
組合起來,有知道的請幫幫忙啊!
解析:
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 *** yzePath(){
String dirName;
int pos=srcFileNamestIndexOf("/稿蔽局");
dirName=srcFileName.substring(0,pos);
File dir=new File(dirName);
if (!dir.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=destFileNamestIndexOf("/");
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;
*** yzePath();
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);
}