3des加密解密java
<?php
/**
* 3DES加解密類
* @Author: 黎志斌
* @version: v1.0
* 2016年7月21日
*/
class Encrypt
{
//加密秘鑰,
private $_key;
private $_iv;
public function __construct($key, $iv)
{
$this->_key = $key;
$this->_iv = $iv;
}
/**
* 對字元串進行3DES加密
* @param string 要加密的字元串
* @return mixed 加密成功返回加密後的字元串,否則返回false
*/
public function encrypt3DES($str)
{
$td = mcrypt_mole_open(MCRYPT_3DES, "", MCRYPT_MODE_CBC, "");
if ($td === false) {
return false;
}
//檢查加密key,iv的長度是否符合演算法要求
$key = $this->fixLen($this->_key, mcrypt_enc_get_key_size($td));
$iv = $this->fixLen($this->_iv, mcrypt_enc_get_iv_size($td));
//加密數據長度處理
$str = $this->strPad($str, mcrypt_enc_get_block_size($td));
if (mcrypt_generic_init($td, $key, $iv) !== 0) {
return false;
}
$result = mcrypt_generic($td, $str);
mcrypt_generic_deinit($td);
mcrypt_mole_close($td);
return $result;
}
/**
* 對加密的字元串進行3DES解密
* @param string 要解密的字元串
* @return mixed 加密成功返回加密後的字元串,否則返回false
*/
public function decrypt3DES($str)
{
$td = mcrypt_mole_open(MCRYPT_3DES, "", MCRYPT_MODE_CBC, "");
if ($td === false) {
return false;
}
//檢查加密key,iv的長度是否符合演算法要求
$key = $this->fixLen($this->_key, mcrypt_enc_get_key_size($td));
$iv = $this->fixLen($this->_iv, mcrypt_enc_get_iv_size($td));
if (mcrypt_generic_init($td, $key, $iv) !== 0) {
return false;
}
$result = mdecrypt_generic($td, $str);
mcrypt_generic_deinit($td);
mcrypt_mole_close($td);
return $this->strUnPad($result);
}
/**
* 返回適合演算法長度的key,iv字元串
* @param string $str key或iv的值
* @param int $td_len 符合條件的key或iv長度
* @return string 返回處理後的key或iv值
*/
private function fixLen($str, $td_len)
{
$str_len = strlen($str);
if ($str_len > $td_len) {
return substr($str, 0, $td_len);
} else if($str_len < $td_len) {
return str_pad($str, $td_len, '0');
}
return $str;
}
/**
* 返回適合演算法的分組大小的字元串長度,末尾使用\0補齊
* @param string $str 要加密的字元串
* @param int $td_group_len 符合演算法的分組長度
* @return string 返回處理後字元串
*/
private function strPad($str, $td_group_len)
{
$padding_len = $td_group_len - (strlen($str) % $td_group_len);
return str_pad($str, strlen($str) + $padding_len, "\0");
}
/**
* 返回適合演算法的分組大小的字元串長度,末尾使用\0補齊
* @param string $str 要加密的字元串
* @return string 返回處理後字元串
*/
private function strUnPad($str)
{
return rtrim($str);
}
}
$key = 'ABCEDFGHIJKLMNOPQ';
$iv = '0123456789';
$des = new Encrypt($key, $iv);
$str = "abcdefghijklmnopq";
echo "source: {$str},len: ",strlen($str),"\r\n";
$e_str = $des->encrypt3DES($str);
echo "entrypt: ", $e_str, "\r\n";
$d_str = $des->decrypt3DES($e_str);
echo "dntrypt: {$d_str},len: ",strlen($d_str),"\r\n";
2. 如何用Java進行3DES加密解密
這里是例子,直接拿來用就可以了。
package com.nnff.des;
import java.security.Security;
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
/*字元串 DESede(3DES) 加密
* ECB模式/使用PKCS7方式填充不足位,目前給的密鑰是192位
* 3DES(即Triple DES)是DES向AES過渡的加密演算法(1999年,NIST將3-DES指定為過渡的
* 加密標准),是DES的一個更安全的變形。它以DES為基本模塊,通過組合分組方法設計出分組加
* 密演算法,其具體實現如下:設Ek()和Dk()代表DES演算法的加密和解密過程,K代表DES演算法使用的
* 密鑰,P代表明文,C代表密表,這樣,
* 3DES加密過程為:C=Ek3(Dk2(Ek1(P)))
* 3DES解密過程為:P=Dk1((EK2(Dk3(C)))
* */
public class ThreeDes {
/**
* @param args在java中調用sun公司提供的3DES加密解密演算法時,需要使
* 用到$JAVA_HOME/jre/lib/目錄下如下的4個jar包:
*jce.jar
*security/US_export_policy.jar
*security/local_policy.jar
*ext/sunjce_provider.jar
*/
private static final String Algorithm = "DESede"; //定義加密演算法,可用 DES,DESede,Blowfish
//keybyte為加密密鑰,長度為24位元組
//src為被加密的數據緩沖區(源)
public static byte[] encryptMode(byte[] keybyte,byte[] src){
try {
//生成密鑰
SecretKey deskey = new SecretKeySpec(keybyte, Algorithm);
//加密
Cipher c1 = Cipher.getInstance(Algorithm);
c1.init(Cipher.ENCRYPT_MODE, deskey);
return c1.doFinal(src);//在單一方面的加密或解密
} catch (java.security.NoSuchAlgorithmException e1) {
// TODO: handle exception
e1.printStackTrace();
}catch(javax.crypto.NoSuchPaddingException e2){
e2.printStackTrace();
}catch(java.lang.Exception e3){
e3.printStackTrace();
}
return null;
}
//keybyte為加密密鑰,長度為24位元組
//src為加密後的緩沖區
public static byte[] decryptMode(byte[] keybyte,byte[] src){
try {
//生成密鑰
SecretKey deskey = new SecretKeySpec(keybyte, Algorithm);
//解密
Cipher c1 = Cipher.getInstance(Algorithm);
c1.init(Cipher.DECRYPT_MODE, deskey);
return c1.doFinal(src);
} catch (java.security.NoSuchAlgorithmException e1) {
// TODO: handle exception
e1.printStackTrace();
}catch(javax.crypto.NoSuchPaddingException e2){
e2.printStackTrace();
}catch(java.lang.Exception e3){
e3.printStackTrace();
}
return null;
}
//轉換成十六進制字元串
public static 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;
}
if(n<b.length-1)hs=hs+":";
}
return hs.toUpperCase();
}
public static void main(String[] args) {
// TODO Auto-generated method stub
//添加新安全演算法,如果用JCE就要把它添加進去
Security.addProvider(new com.sun.crypto.provider.SunJCE());
final byte[] keyBytes = {0x11, 0x22, 0x4F, 0x58,
(byte)0x88, 0x10, 0x40, 0x38, 0x28, 0x25, 0x79, 0x51,
(byte)0xCB,
(byte)0xDD, 0x55, 0x66, 0x77, 0x29, 0x74,
(byte)0x98, 0x30, 0x40, 0x36,
(byte)0xE2
}; //24位元組的密鑰
String szSrc = "This is a 3DES test. 測試";
System.out.println("加密前的字元串:" + szSrc);
byte[] encoded = encryptMode(keyBytes,szSrc.getBytes());
System.out.println("加密後的字元串:" + new String(encoded));
byte[] srcBytes = decryptMode(keyBytes,encoded);
System.out.println("解密後的字元串:" + (new String(srcBytes)));
}
}
3. java 進行3DES 加密解密
【Java使用3DES加密解密的流程】
①傳入共同約定的密鑰(keyBytes)以及演算法(Algorithm),來構建SecretKey密鑰對象
SecretKey deskey = new SecretKeySpec(keyBytes, Algorithm);
②根據演算法實例化Cipher對象。它負責加密/解密
Cipher c1 = Cipher.getInstance(Algorithm);
③傳入加密/解密模式以及SecretKey密鑰對象,實例化Cipher對象
c1.init(Cipher.ENCRYPT_MODE, deskey);
④傳入位元組數組,調用Cipher.doFinal()方法,實現加密/解密,並返回一個byte位元組數組
c1.doFinal(src);
參考了:http://www.cnblogs.com/lianghuilin/archive/2013/04/15/3des.html
4. 如何用Java進行3DES加密解密
這里是例子,直接拿來用就可以了。
package com.nnff.des;
import java.security.Security;
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
/*字元串 DESede(3DES) 加密
* ECB模式/使用PKCS7方式填充不足位,目前給的密鑰是192位
* 3DES(即Triple DES)是DES向AES過渡的加密演算法(1999年,NIST將3-DES指定為過渡的
* 加密標准),是DES的一個更安全的變形。它以DES為基本模塊,通過組合分組方法設計出分組加
* 密演算法,其具體實現如下:設Ek()和Dk()代表DES演算法的加密和解密過程,K代表DES演算法使用的
* 密鑰,P代表明文,C代表密表,這樣,
* 3DES加密過程為:C=Ek3(Dk2(Ek1(P)))
* 3DES解密過程為:P=Dk1((EK2(Dk3(C)))
* */
public class ThreeDes {
/**
* @param args在java中調用sun公司提供的3DES加密解密演算法時,需要使
* 用到$JAVA_HOME/jre/lib/目錄下如下的4個jar包:
*jce.jar
*security/US_export_policy.jar
*security/local_policy.jar
*ext/sunjce_provider.jar
*/
private static final String Algorithm = "DESede"; //定義加密演算法,可用 DES,DESede,Blowfish
//keybyte為加密密鑰,長度為24位元組
//src為被加密的數據緩沖區(源)
public static byte[] encryptMode(byte[] keybyte,byte[] src){
try {
//生成密鑰
SecretKey deskey = new SecretKeySpec(keybyte, Algorithm);
//加密
Cipher c1 = Cipher.getInstance(Algorithm);
c1.init(Cipher.ENCRYPT_MODE, deskey);
return c1.doFinal(src);//在單一方面的加密或解密
} catch (java.security.NoSuchAlgorithmException e1) {
// TODO: handle exception
e1.printStackTrace();
}catch(javax.crypto.NoSuchPaddingException e2){
e2.printStackTrace();
}catch(java.lang.Exception e3){
e3.printStackTrace();
}
return null;
}
//keybyte為加密密鑰,長度為24位元組
//src為加密後的緩沖區
public static byte[] decryptMode(byte[] keybyte,byte[] src){
try {
//生成密鑰
SecretKey deskey = new SecretKeySpec(keybyte, Algorithm);
//解密
Cipher c1 = Cipher.getInstance(Algorithm);
c1.init(Cipher.DECRYPT_MODE, deskey);
return c1.doFinal(src);
} catch (java.security.NoSuchAlgorithmException e1) {
// TODO: handle exception
e1.printStackTrace();
}catch(javax.crypto.NoSuchPaddingException e2){
e2.printStackTrace();
}catch(java.lang.Exception e3){
e3.printStackTrace();
}
return null;
}
//轉換成十六進制字元串
public static 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;
}
if(n<b.length-1)hs=hs+":";
}
return hs.toUpperCase();
}
public static void main(String[] args) {
// TODO Auto-generated method stub
//添加新安全演算法,如果用JCE就要把它添加進去
Security.addProvider(new com.sun.crypto.provider.SunJCE());
final byte[] keyBytes = {0x11, 0x22, 0x4F, 0x58,
(byte)0x88, 0x10, 0x40, 0x38, 0x28, 0x25, 0x79, 0x51,
(byte)0xCB,
(byte)0xDD, 0x55, 0x66, 0x77, 0x29, 0x74,
(byte)0x98, 0x30, 0x40, 0x36,
(byte)0xE2
}; //24位元組的密鑰
String szSrc = "This is a 3DES test. 測試";
System.out.println("加密前的字元串:" + szSrc);
byte[] encoded = encryptMode(keyBytes,szSrc.getBytes());
System.out.println("加密後的字元串:" + new String(encoded));
byte[] srcBytes = decryptMode(keyBytes,encoded);
System.out.println("解密後的字元串:" + (new String(srcBytes)));
}
}
5. java 3des 解密
3DES(或稱為Triple DES)是三重數據加密演算法(TDEA,Triple Data Encryption Algorithm)塊密碼的通稱。它相當於是對每個數據塊應用三次DES加密演算法。由於計算機運算能力的增強,原版DES密碼的密鑰長度變得容易被暴力破解;3DES即是設計用來提供一種相對簡單的方法,即通過增加DES的密鑰長度來避免類似的攻擊,而不是設計一種全新的塊密碼演算法。
3DES是三重數據加密,且可以逆推的一種演算法方案。但由於3DES的演算法是公開的,所以演算法本身沒什麼秘密可言,主要依靠唯一密鑰來確保數據加密解密的安全。有人可能會問,那3DES到底安不安全呢?!目前為止,還沒有人能破解3DES,所以你要是能破解它,都足以震驚整個信息安全界了……
[Java使用3DES加解密流程]
①傳入共同約定的密鑰(keyBytes)以及演算法(Algorithm),來構建SecretKey密鑰對象
SecretKey deskey = new SecretKeySpec(keyBytes, Algorithm);
②根據演算法實例化Cipher對象。它負責加密/解密
Cipher c1 = Cipher.getInstance(Algorithm);
③傳入加密/解密模式以及SecretKey密鑰對象,實例化Cipher對象
c1.init(Cipher.ENCRYPT_MODE, deskey);
④傳入位元組數組,調用Cipher.doFinal()方法,實現加密/解密,並返回一個byte位元組數組
c1.doFinal(src);
6. 如何用Java進行3DES加密解密
public static String encryptKey(String mainKey,String plainKey){ String encryptKey = ""; try{ Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider()); String Algorithm = "DESede/ECB/NoPadding"; byte[] hb = hex2byte(mainKey.getBytes()); byte[] k = new byte[24]; System.array(hb,0,k,0,16); System.array(hb,0,k,16,8); SecretKey deskey = new SecretKeySpec(k, Algorithm); Cipher c1 = Cipher.getInstance(Algorithm); c1.init(Cipher.ENCRYPT_MODE, deskey); encryptKey = byte2hex(c1.doFinal(hex2byte(plainKey.getBytes()))); }catch(Exception e){ e.printStackTrace(); } return encryptKey; }public static String byte2hex(byte[] b) { String hs = ""; String stmp = ""; for (int n = 0; n < b.length; n++) { stmp = Integer.toHexString(b[n] & 0xFF); if (stmp.length() == 1) hs += ("0" + stmp); else hs += stmp; } return hs.toUpperCase(); } 3DES的加密密鑰長度要求是24個位元組,本例中因為給定的密鑰只有16個位元組,所以需要填補至24個位元組。
7. 求java中3des加密解密示例
在java中調用sun公司提供的3DES加密解密演算法時,需要使用到$JAVA_HOME/jre/lib/目錄下如下的4個jar包:
jce.jar
security/US_export_policy.jar
security/local_policy.jar
ext/sunjce_provider.jar
Java運行時會自動載入這些包,因此對於帶main函數的應用程序不需要設置到CLASSPATH環境變數中。對於WEB應用,不需要把這些包加到WEB-INF/lib目錄下。
以下是java中調用sun公司提供的3DES加密解密演算法的樣本代碼:
加密解密代碼
import java.security.Security;
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
/*字元串 DESede(3DES) 加密*/
public class ThreeDes {
/**
* @param args在java中調用sun公司提供的3DES加密解密演算法時,需要使
* 用到$JAVA_HOME/jre/lib/目錄下如下的4個jar包:
*jce.jar
*security/US_export_policy.jar
*security/local_policy.jar
*ext/sunjce_provider.jar
*/
private static final String Algorithm ="DESede"; //定義加密演算法,可用 DES,DESede,Blowfish
//keybyte為加密密鑰,長度為24位元組
//src為被加密的數據緩沖區(源)
public static byte[] encryptMode(byte[] keybyte,byte[] src){
try {
//生成密鑰
SecretKey deskey = new SecretKeySpec(keybyte, Algorithm);
//加密
Cipher c1 = Cipher.getInstance(Algorithm);
c1.init(Cipher.ENCRYPT_MODE, deskey);
return c1.doFinal(src);//在單一方面的加密或解密
} catch (java.security.NoSuchAlgorithmException e1) {
// TODO: handle exception
e1.printStackTrace();
}catch(javax.crypto.NoSuchPaddingException e2){
e2.printStackTrace();
}catch(java.lang.Exception e3){
e3.printStackTrace();
}
return null;
}
//keybyte為加密密鑰,長度為24位元組
//src為加密後的緩沖區
public static byte[] decryptMode(byte[] keybyte,byte[] src){
try {
//生成密鑰
SecretKey deskey = new SecretKeySpec(keybyte, Algorithm);
//解密
Cipher c1 = Cipher.getInstance(Algorithm);
c1.init(Cipher.DECRYPT_MODE, deskey);
return c1.doFinal(src);
} catch (java.security.NoSuchAlgorithmException e1) {
// TODO: handle exception
e1.printStackTrace();
}catch(javax.crypto.NoSuchPaddingException e2){
e2.printStackTrace();
}catch(java.lang.Exception e3){
e3.printStackTrace();
}
return null;
}
//轉換成十六進制字元串
public static 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;
}
if(n<b.length-1)hs=hs+":";
}
return hs.toUpperCase();
}
public static void main(String[] args) {
// TODO Auto-generated method stub
//添加新安全演算法,如果用JCE就要把它添加進去
Security.addProvider(new com.sun.crypto.provider.SunJCE());
final byte[] keyBytes = {0x11, 0x22, 0x4F, 0x58,
(byte)0x88, 0x10, 0x40, 0x38, 0x28, 0x25, 0x79,0x51,
(byte)0xCB,
(byte)0xDD, 0x55, 0x66, 0x77, 0x29, 0x74,
(byte)0x98, 0x30, 0x40, 0x36,
(byte)0xE2
}; //24位元組的密鑰
String szSrc = "This is a 3DES test. 測試";
System.out.println("加密前的字元串:" + szSrc);
byte[] encoded = encryptMode(keyBytes,szSrc.getBytes());
System.out.println("加密後的字元串:" + new String(encoded));
byte[] srcBytes = decryptMode(keyBytes,encoded);
System.out.println("解密後的字元串:" + (new String(srcBytes)));
}
}
8. 如何用Java進行3DES加密解
importjava.io.File;importjava.io.FileInputStream;importjava.io.FileOutputStream;importjava.io.InputStream;importjava.io.OutputStream;importjava.security.KeyPair;importjava.security.KeyPairGenerator;importjava.security.NoSuchAlgorithmException;importjava.security.interfaces.RSAPrivateKey;importjava.security.interfaces.RSAPublicKey;importjavax.crypto.Cipher;publicclassRSAEncrypt{;staticKeyPairkeyPair;staticRSAPrivateKeyprivateKey;staticRSAPublicKeypublicKey;static{try{keyPairGen=KeyPairGenerator.getInstance("RSA");keyPairGen.initialize(512);keyPair=keyPairGen.generateKeyPair();//GeneratekeysprivateKey=(RSAPrivateKey)keyPair.getPrivate();publicKey=(RSAPublicKey)keyPair.getPublic();}catch(NoSuchAlgorithmExceptione){//TODOAuto-generatedcatchblocke.printStackTrace();}}publicstaticvoidmain(String[]args){RSAEncryptencrypt=newRSAEncrypt();Filefile=newFile("C:\\DocumentsandSettings\\Administrator.DCB5E0D91E0D436\\桌面\\sdf.txt");FilenewFile=newFile("C:\\DocumentsandSettings\\Administrator.DCB5E0D91E0D436\\桌面\\sdf1.txt");encrypt.encryptFile(encrypt,file,newFile);Filefile1=newFile("C:\\DocumentsandSettings\\Administrator.DCB5E0D91E0D436\\桌面\\sdf1.txt");FilenewFile1=newFile("C:\\DocumentsandSettings\\Administrator.DCB5E0D91E0D436\\桌面\\sdf2.txt");encrypt.decryptFile(encrypt,file1,newFile1);}publicvoidencryptFile(RSAEncryptencrypt,Filefile,FilenewFile){try{InputStreamis=newFileInputStream(file);OutputStreamos=newFileOutputStream(newFile);byte[]bytes=newbyte[53];while(is.read(bytes)>0){byte[]e=encrypt.encrypt(RSAEncrypt.publicKey,bytes);bytes=newbyte[53];os.write(e,0,e.length);}os.close();is.close();System.out.println("writesuccess");}catch(Exceptione){e.printStackTrace();}}publicvoiddecryptFile(RSAEncryptencrypt,Filefile,FilenewFile){try{InputStreamis=newFileInputStream(file);OutputStreamos=newFileOutputStream(newFile);byte[]bytes1=newbyte[64];while(is.read(bytes1)>0){byte[]de=encrypt.decrypt(RSAEncrypt.privateKey,bytes1);bytes1=newbyte[64];os.write(de,0,de.length);}os.close();is.close();System.out.println("writesuccess");}catch(Exceptione){e.printStackTrace();}}/***//****EncryptString.***@returnbyte[]*/protectedbyte[]encrypt(RSAPublicKeypublicKey,byte[]obj){if(publicKey!=null){try{Ciphercipher=Cipher.getInstance("RSA");cipher.init(Cipher.ENCRYPT_MODE,publicKey);returncipher.doFinal(obj);}catch(Exceptione){e.printStackTrace();}}returnnull;}/***//****Basicdecryptmethod***@returnbyte[]*/protectedbyte[]decrypt(RSAPrivateKeyprivateKey,byte[]obj){if(privateKey!=null){try{Ciphercipher=Cipher.getInstance("RSA");cipher.init(Cipher.DECRYPT_MODE,privateKey);returncipher.doFinal(obj);}catch(Exceptione){e.printStackTrace();}}returnnull;}}加解密需要依靠以下四個屬性,你可以把它存文件,存資料庫都無所謂:;staticKeyPairkeyPair;staticRSAPrivateKeyprivateKey;staticRSAPublicKeypublicKey;以上只是示例,怎麼存放根據自己情況追問:你能具體的注釋下么,追答:每一句話都注釋?追問:不用每一句,每個方法注釋下,還有就是怎麼使用哇,哪個文件時本來存在的,哪個是加密之後的,這個類我運行了之後,還出現了文檔打不開的問題追答:哦,好的importjava.io.File;importjava.io.FileInputStream;importjava.io.FileOutputStream;importjava.io.InputStream;importjava.io.OutputStream;importjava.security.KeyPair;importjava.security.KeyPairGenerator;importjava.security.NoSuchAlgorithmException;importjava.security.interfaces.RSAPrivateKey;importjava.security.interfaces.RSAPublicKey;importjavax.crypto.Cipher;publicclassRSAEncrypt{;staticKeyPairkeyPair;staticRSAPrivateKeyprivateKey;staticRSAPublicKeypublicKey;static{try{//實例類型keyPairGen=KeyPairGenerator.getInstance("RSA");//初始化長度keyPairGen.initialize(512);//生成KeyPairkeyPair=keyPairGen.generateKeyPair();//GeneratekeysprivateKey=(RSAPrivateKey)keyPair.getPrivate();publicKey=(RSAPublicKey)keyPair.getPublic();}catch(NoSuchAlgorithmExceptione){//TODOAuto-generatedcatchblocke.printStackTrace();}}/***加密文件*@paramencryptRSAEncrypt對象*@paramfile源文件*@paramnewFile目標文件*/publicvoidencryptFile(RSAEncryptencrypt,Filefile,FilenewFile);/***解密文件*@paramencryptRSAEncrypt對象*@paramfile源文件*@paramnewFile目標文件*/publicvoiddecryptFile(RSAEncryptencrypt,Filefile,FilenewFile);/***加密實現**@returnbyte[]加密後的位元組數組*/protectedbyte[]encrypt(RSAPublicKeypublicKey,byte[]obj);/***解密實現**@returnbyte[]解密後的位元組數組*/protectedbyte[]decrypt(RSAPrivateKeyprivateKey,byte[]obj)我測試了下,.doc.txt均可以加密因為加密解密均是根據那四個屬性來的,所以你需要寫個每次運行先讀取屬性,你可以寫入文件若文件不存在則新生成一組,當加密完成後把四個屬性寫入文件。我以上寫的只是測試,加解密未分開的
9. 如何用Java進行3DES加密解
最近一個合作商提出使用3DES交換數據,本來他們有現成的代碼,可惜只有.net版本,我們的伺服器都是linux,而且應用都是Java。於是對照他們提供的代碼改了一個Java的版本出來,主要是不熟悉3DES,折騰了一天,終於搞定。
所謂3DES,就是把DES做三次,當然不是簡單地DES DES DES就行了,中途有些特定的排列。這個我可不關心,呵呵,我的目的是使用它。
在網上搜索了一下3DES,找到很少資料。經過朋友介紹,找到GNU Crypto和Bouncy Castle兩個Java擴充包,裡面應該有3DES的實現吧。
從GNU Crypto入手,找到一個TripleDES的實現類,發現原來3DES還有一個名字叫DESede,在網上搜索TripleDES和DESede,呵呵,終於發現更多的資料了。
Java的安全API始終那麼難用,先創建一個cipher看看演算法在不在吧
Cipher cipher = Cipher.getInstance("DESede");
如果沒有拋異常的話,就證明這個演算法是有效的
突然想看看JDK有沒有內置DESede,於是撇開Crypto,直接測試,發現可以正確運行。在jce.jar裡面找到相關的類,JDK內置了。
於是直接用DES的代碼來改&測試,最後代碼變成這樣
SecureRandom sr = new SecureRandom();
DESedeKeySpec dks = new DESedeKeySpec(PASSWORD_CRYPT_KEY.getBytes());
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DESede");
SecretKey securekey = keyFactory.generateSecret(dks);
Cipher cipher = Cipher.getInstance("DESede");
cipher.init(Cipher.ENCRYPT_MODE, securekey, sr);
return new String(Hex.encodeHex(cipher.doFinal(str.getBytes())));
需要留意的是,要使用DESede的Spec、Factory和Cipher才行
事情還沒完結,合作商給過來的除了密鑰之外,還有一個IV向量。搜索了一下,發現有一個IvParameterSpec類,於是代碼變成這樣
SecureRandom sr = new SecureRandom();
DESedeKeySpec dks = new DESedeKeySpec(PASSWORD_CRYPT_KEY.getBytes());
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DESede");
SecretKey securekey = keyFactory.generateSecret(dks);
IvParameterSpec iv = new IvParameterSpec(PASSWORD_IV.getBytes());
Cipher cipher = Cipher.getInstance("DESede");
cipher.init(Cipher.ENCRYPT_MODE, securekey, iv, sr);
return new String(Hex.encodeHex(cipher.doFinal(str.getBytes())));
但是,運行報錯了
java.security.: ECB mode cannot use IV
ECB是什麼呢?我的代碼完全沒有寫ECB什麼的
又上網搜索,結果把DES的來龍去脈都搞清楚了
http://www.tropsoft.com/strongenc/des.htm
ECB是其中一種字串分割方式,除了DES以外,其他加密方式也會使用這種分割方式的,而Java默認產生的DES演算法就是用ECB方法,ECB不需要向量,當然也就不支持向量了
除了ECB,DES還支持CBC、CFB、OFB,而3DES只支持ECB和CBC兩種
http://www.tropsoft.com/strongenc/des3.htm
CBC支持並且必須有向量,具體演算法這里就不說了。合作商給的.net代碼沒有聲明CBC模式,似乎是.net默認的方式就是CBC的
於是把模式改成CBC
Cipher cipher = Cipher.getInstance("DESede/CBC/PKCS5Padding");
成功運行了
後話:
搜索的過程中,找到一個不錯的討論
http://www.lslnet.com/linux/dosc1/21/linux-197579.htm
在CBC(不光是DES演算法)模式下,iv通過隨機數(或偽隨機)機制產生是一種比較常見的方法。iv的作用主要是用於產生密文的第一個block,以使
最終生成的密文產生差異(明文相同的情況下),使密碼攻擊變得更為困難,除此之外iv並無其它用途。因此iv通過隨機方式產生是一種十分簡便、有效的途
徑。此外,在IPsec中採用了DES-CBC作為預設的加密方式,其使用的iv是通訊包的時間戳。從原理上來說,這與隨機數機制並無二致。
看來,向量的作用其實就是salt
最大的好處是,可以令到即使相同的明文,相同的密鑰,能產生不同的密文
例如,我們用DES方式在數據保存用戶密碼的時候,可以另外增加一列,把向量同時保存下來,並且每次用不同的向量。這樣的好處是,即使兩個用戶的密碼是一樣的,資料庫保存的密文,也會不一樣,就能降低猜測的可能性
另外一種用法,就是類似IPsec的做法,兩部主機互傳數據,保證兩部機的時鍾同步的前提下(可以取樣到分鍾或更高的單位避免偏差),用時鍾的變化值作為向量,就能增加被sniffer數據的解密難度
10. java 3des和c 3des加密通訊
在java中要注意幾個問題:
1、填充方式
2、加密方式, 比如:CBC
3、密碼以及密碼位元組順序
三種都一樣才可,如果差一點還能得到一樣的結果,那就不叫加密了。