1. 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;
}
}

2. 我想用c語言(不是C++)實現RSA加解密演算法,同時也用JAVA實現這個演算法,就是C加密的,可以用JAVA解密

這個好:
http://blog.sina.com.cn/s/blog_5fd1d47e0100dqyo.html

3. 如何實現c和java的des互相加解密

/*
* MD5 演算法
*/
public class MD5 {

// 全局數組
private final static String[] strDigits = { "0", "1", "2", "3", "4", "5",
"6", "7", "8", "9", "a", "b", "c", "d", "e", "f" };

public MD5() {
}

// 返回形式為數字跟字元串
private static String byteToArrayString(byte bByte) {
int iRet = bByte;
// System.out.println("iRet="+iRet);
if (iRet < 0) {
iRet += 256;
}
int iD1 = iRet / 16;
int iD2 = iRet % 16;
return strDigits[iD1] + strDigits[iD2];
}

// 返回形式只為數字
private static String byteToNum(byte bByte) {
int iRet = bByte;
System.out.println("iRet1=" + iRet);
if (iRet < 0) {
iRet += 256;
}
return String.valueOf(iRet);
}

// 轉換位元組數組為16進制字串
private static String byteToString(byte[] bByte) {
StringBuffer sBuffer = new StringBuffer();
for (int i = 0; i < bByte.length; i++) {
sBuffer.append(byteToArrayString(bByte[i]));
}
return sBuffer.toString();
}

public static String GetMD5Code(String strObj) {
String resultString = null;
try {
resultString = new String(strObj);
MessageDigest md = MessageDigest.getInstance("MD5");
// md.digest() 該函數返回值為存放哈希值結果的byte數組
resultString = byteToString(md.digest(strObj.getBytes()));
} catch (NoSuchAlgorithmException ex) {
ex.printStackTrace();
}
return resultString;
}

public static void main(String[] args) {
MD5 getMD5 = new MD5();
System.out.println(getMD5.GetMD5Code("000000"));
}
}

4. 用JAVA實現了AES128加密,求用C語言解密的代碼,謝謝各位大神了!

http://blog.chen777.com/2015/10/13/Java%E4%B8%8EC-AES%E5%8A%A0%E5%AF%86%E8%A7%A3%E5%AF%86/#more
不知道適合你用嗎,我以前是用這種方式實現的。

5. c語言的des加密,怎麼用java解密

密匙是一個密碼加密演算法是一種加密文件的方法這能有什麼可比性,一個是一段字元串,一個是一種演算法只能說特定的加密演算法是依據密匙按某種規則結合密匙和原文,形成密文如果是可逆演算法那麼還可以依據密文和密匙進行加密的逆運算還原出原文

6. 求RC6加密和解密的java代碼。。

php">ortjava.io.FileInputStream;
#importjava.io.FileOutputStream;
#importjava.io.IOException;
#importjava.io.ObjectInputStream;
#importjava.io.ObjectOutputStream;
#importjava.security.*;
#importjavax.crypto.Cipher;
#importjavax.crypto.KeyGenerator;
#importjavax.crypto.SecretKey;
#/**
#*加密解密
#*
#*@authorshy.qiu
#*@since
#*/
#publicclassCryptTest{
#/**
#*進行MD5加密
#*
#*@paraminfo
#*要加密的信息
#*@returnString加密後的字元串
#*/
#publicStringencryptToMD5(Stringinfo){
#byte[]digesta=null;
#try{
#//得到一個md5的消息摘要
#MessageDigestalga=MessageDigest.getInstance("MD5");
#//添加要進行計算摘要的信息
#alga.update(info.getBytes());
#//得到該摘要
#digesta=alga.digest();
#}catch(NoSuchAlgorithmExceptione){
#e.printStackTrace();
#}
#//將摘要轉為字元串
#Stringrs=byte2hex(digesta);
#returnrs;
#}
#/**
#*進行SHA加密
#*
#*@paraminfo
#*要加密的信息
#*@returnString加密後的字元串
#*/
#publicStringencryptToSHA(Stringinfo){
#byte[]digesta=null;
#try{
#//得到一個SHA-1的消息摘要
#MessageDigestalga=MessageDigest.getInstance("SHA-1");
#//添加要進行計算摘要的信息
#alga.update(info.getBytes());
#//得到該摘要
#digesta=alga.digest();
#}catch(NoSuchAlgorithmExceptione){
#e.printStackTrace();
#}
#//將摘要轉為字元串
#Stringrs=byte2hex(digesta);
#returnrs;
#}
#////////////////////////////////////////////////////////////////////////////
#/**
#*創建密匙
#*
#*@paramalgorithm
#*加密演算法,可用DES,DESede,Blowfish
#*@returnSecretKey秘密(對稱)密鑰
#*/
#(Stringalgorithm){
#//聲明KeyGenerator對象
#KeyGeneratorkeygen;
#//聲明密鑰對象
#SecretKeydeskey=null;
#try{
#//返回生成指定演算法的秘密密鑰的KeyGenerator對象
#keygen=KeyGenerator.getInstance(algorithm);
#//生成一個密鑰
#deskey=keygen.generateKey();
#}catch(NoSuchAlgorithmExceptione){
#e.printStackTrace();
#}
#//返回密匙
#returndeskey;
#}
#/**
#*根據密匙進行DES加密
#*
#*@paramkey
#*密匙
#*@paraminfo
#*要加密的信息
#*@returnString加密後的信息
#*/
#publicStringencryptToDES(SecretKeykey,Stringinfo){
#//定義加密演算法,可用DES,DESede,Blowfish
#StringAlgorithm="DES";
#//加密隨機數生成器(RNG),(可以不寫)
#SecureRandomsr=newSecureRandom();
#//定義要生成的密文
#byte[]cipherByte=null;
#try{
#//得到加密/解密器
#Cipherc1=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(Exceptione){
#e.printStackTrace();
#}
#//返回密文的十六進制形式
#returnbyte2hex(cipherByte);
#}
#/**
#*根據密匙進行DES解密
#*
#*@paramkey
#*密匙
#*@paramsInfo
#*要解密的密文
#*@returnString返回解密後信息
#*/
#publicStringdecryptByDES(SecretKeykey,StringsInfo){
#//定義加密演算法,
#StringAlgorithm="DES";
#//加密隨機數生成器(RNG)
#SecureRandomsr=newSecureRandom();
#byte[]cipherByte=null;
#try{
#//得到加密/解密器
#Cipherc1=Cipher.getInstance(Algorithm);
#//用指定的密鑰和模式初始化Cipher對象
#c1.init(Cipher.DECRYPT_MODE,key,sr);
#//對要解密的內容進行編碼處理
#cipherByte=c1.doFinal(hex2byte(sInfo));
#}catch(Exceptione){
#e.printStackTrace();
#}
#//returnbyte2hex(cipherByte);
#returnnewString(cipherByte);
#}
#///////////////////////////////////////////////////////////////////////////////
#/**
#*創建密匙組,並將公匙,私匙放入到指定文件中
#*
#*默認放入mykeys.bat文件中
#*/
#publicvoidcreatePairKey(){
#try{
#//根據特定的演算法一個密鑰對生成器
#KeyPairGeneratorkeygen=KeyPairGenerator.getInstance("DSA");
#//加密隨機數生成器(RNG)
#SecureRandomrandom=newSecureRandom();
#//重新設置此隨機對象的種子
#random.setSeed(1000);
#//使用給定的隨機源(和默認的參數集合)初始化確定密鑰大小的密鑰對生成器
#keygen.initialize(512,random);//keygen.initialize(512);
#//生成密鑰組
#KeyPairkeys=keygen.generateKeyPair();
#//得到公匙
#PublicKeypubkey=keys.getPublic();
#//得到私匙
#PrivateKeyprikey=keys.getPrivate();
#//將公匙私匙寫入到文件當中
#doObjToFile("mykeys.bat",newObject[]);
#}catch(NoSuchAlgorithmExceptione){
#e.printStackTrace();
#}
#}
#/**
#*利用私匙對信息進行簽名把簽名後的信息放入到指定的文件中
#*
#*@paraminfo
#*要簽名的信息
#*@paramsignfile
#*存入的文件
#*/
#publicvoidsignToInfo(Stringinfo,Stringsignfile){
#//從文件當中讀取私匙
#PrivateKeymyprikey=(PrivateKey)getObjFromFile("mykeys.bat",1);
#//從文件中讀取公匙
#PublicKeymypubkey=(PublicKey)getObjFromFile("mykeys.bat",2);
#try{
#//Signature對象可用來生成和驗證數字簽名
#Signaturesignet=Signature.getInstance("DSA");
#//初始化簽署簽名的私鑰
#signet.initSign(myprikey);
#//更新要由位元組簽名或驗證的數據
#signet.update(info.getBytes());
#//簽署或驗證所有更新位元組的簽名,返回簽名
#byte[]signed=signet.sign();
#//將數字簽名,公匙,信息放入文件中
#doObjToFile(signfile,newObject[]);
#}catch(Exceptione){
#e.printStackTrace();
#}
#}
#/**
#*讀取數字簽名文件根據公匙,簽名,信息驗證信息的合法性
#*
#*@returntrue驗證成功false驗證失敗
#*/
#publicbooleanvalidateSign(Stringsignfile){
#//讀取公匙
#PublicKeymypubkey=(PublicKey)getObjFromFile(signfile,2);
#//讀取簽名
#byte[]signed=(byte[])getObjFromFile(signfile,1);
#//讀取信息
#Stringinfo=(String)getObjFromFile(signfile,3);
#try{
#//初始一個Signature對象,並用公鑰和簽名進行驗證
#Signaturesignetcheck=Signature.getInstance("DSA");
#//初始化驗證簽名的公鑰
#signetcheck.initVerify(mypubkey);
#//使用指定的byte數組更新要簽名或驗證的數據
#signetcheck.update(info.getBytes());
#System.out.println(info);
#//驗證傳入的簽名
#returnsignetcheck.verify(signed);
#}catch(Exceptione){
#e.printStackTrace();
#returnfalse;
#}
#}
#/**
#*將二進制轉化為16進制字元串
#*
#*@paramb
#*二進制位元組數組
#*@returnString
#*/
#publicStringbyte2hex(byte[]b){
#Stringhs="";
#Stringstmp="";
#for(intn=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;
#}
#}

7. 求 Java的C/S模式中 遠程數據傳輸的「加密、解密」技術

常用API
java.security.KeyPairGenerator 密鑰生成器類
public static KeyPairGenerator getInstance(String algorithm) throws NoSuchAlgorithmException
以指定的演算法返回一個KeyPairGenerator 對象
參數: algorithm 演算法名.如:"DSA","RSA"

public void initialize(int keysize)

以指定的長度初始化KeyPairGenerator對象,如果沒有初始化系統以1024長度默認設置

參數:keysize 演算法位長.其范圍必須在 512 到 1024 之間,且必須為 64 的倍數

public void initialize(int keysize, SecureRandom random)
以指定的長度初始化和隨機發生器初始化KeyPairGenerator對象
參數:keysize 演算法位長.其范圍必須在 512 到 1024 之間,且必須為 64 的倍數
random 一個隨機位的來源(對於initialize(int keysize)使用了默認隨機器

public abstract KeyPair generateKeyPair()
產生新密鑰對

java.security.KeyPair 密鑰對類
public PrivateKey getPrivate()
返回私鑰

public PublicKey getPublic()
返回公鑰

java.security.Signature 簽名類
public static Signature getInstance(String algorithm) throws NoSuchAlgorithmException
返回一個指定演算法的Signature對象
參數 algorithm 如:"DSA"

public final void initSign(PrivateKey privateKey)
throws InvalidKeyException
用指定的私鑰初始化
參數:privateKey 所進行簽名時用的私鑰

public final void update(byte data)
throws SignatureException
public final void update(byte[] data)
throws SignatureException
public final void update(byte[] data, int off, int len)
throws SignatureException
添加要簽名的信息

public final byte[] sign()
throws SignatureException
返回簽名的數組,前提是initSign和update

public final void initVerify(PublicKey publicKey)
throws InvalidKeyException
用指定的公鑰初始化
參數:publicKey 驗證時用的公鑰

public final boolean verify(byte[] signature)
throws SignatureException
驗證簽名是否有效,前提是已initVerify初始化
參數: signature 簽名數組

8. C#加密Java解密

DES加密 java與 C# 可以相互加密解密
這里的KEY採用Base64編碼,便用分發,因為Java的Byte范圍為-128至127,c#的Byte范圍是0-255
核心是確定Mode和Padding,關於這兩個的意思可以搜索3DES演算法相關文章
一個是C#採用CBC Mode,PKCS7 Padding,Java採用CBC Mode,PKCS5Padding Padding,
另一個是C#採用ECB Mode,PKCS7 Padding,Java採用ECB Mode,PKCS5Padding Padding,
Java的ECB模式不需要IV
對字元加密時,雙方採用的都是UTF-8編碼
C# 代碼

/// <summary>
/// DES3加密解密
/// </summary>
public class Des3
{
#region CBC模式**
/// <summary>
/// DES3 CBC模式加密
/// </summary>
/// <param name="key">密鑰</param>
/// <param name="iv">IV</param>
/// <param name="data">明文的byte數組</param>
/// <returns>密文的byte數組</returns>
public static byte[] Des3EncodeCBC( byte[] key, byte[] iv, byte[] data )
{
//復制於MSDN
try
{
// Create a MemoryStream.
MemoryStream mStream = new MemoryStream();
tdsp = new ();
tdsp.Mode = CipherMode.CBC; //默認值
tdsp.Padding = PaddingMode.PKCS7; //默認值
// Create a CryptoStream using the MemoryStream
// and the passed key and initialization vector (IV).
CryptoStream cStream = new CryptoStream( mStream,
tdsp.CreateEncryptor( key, iv ),
CryptoStreamMode.Write );
// Write the byte array to the crypto stream and flush it.
cStream.Write( data, 0, data.Length );
cStream.FlushFinalBlock();
// Get an array of bytes from the
// MemoryStream that holds the
// encrypted data.
byte[] ret = mStream.ToArray();
// Close the streams.
cStream.Close();
mStream.Close();
// Return the encrypted buffer.
return ret;
}
catch ( CryptographicException e )
{
Console.WriteLine( "A Cryptographic error occurred: {0}", e.Message );
return null;
}
}
/// <summary>
/// DES3 CBC模式解密
/// </summary>
/// <param name="key">密鑰</param>
/// <param name="iv">IV</param>
/// <param name="data">密文的byte數組</param>
/// <returns>明文的byte數組</returns>
public static byte[] Des3DecodeCBC( byte[] key, byte[] iv, byte[] data )
{
try
{
// Create a new MemoryStream using the passed
// array of encrypted data.
MemoryStream msDecrypt = new MemoryStream( data );
tdsp = new ();
tdsp.Mode = CipherMode.CBC;
tdsp.Padding = PaddingMode.PKCS7;
// Create a CryptoStream using the MemoryStream
// and the passed key and initialization vector (IV).
CryptoStream csDecrypt = new CryptoStream( msDecrypt,
tdsp.CreateDecryptor( key, iv ),
CryptoStreamMode.Read );
// Create buffer to hold the decrypted data.
byte[] fromEncrypt = new byte[data.Length];
// Read the decrypted data out of the crypto stream
// and place it into the temporary buffer.
csDecrypt.Read( fromEncrypt, 0, fromEncrypt.Length );
//Convert the buffer into a string and return it.
return fromEncrypt;
}
catch ( CryptographicException e )
{
Console.WriteLine( "A Cryptographic error occurred: {0}", e.Message );
return null;
}
}
#endregion
#region ECB模式
/// <summary>
/// DES3 ECB模式加密
/// </summary>
/// <param name="key">密鑰</param>
/// <param name="iv">IV(當模式為ECB時,IV無用)</param>
/// <param name="str">明文的byte數組</param>
/// <returns>密文的byte數組</returns>
public static byte[] Des3EncodeECB( byte[] key, byte[] iv, byte[] data )
{
try
{
// Create a MemoryStream.
MemoryStream mStream = new MemoryStream();
tdsp = new ();
tdsp.Mode = CipherMode.ECB;
tdsp.Padding = PaddingMode.PKCS7;
// Create a CryptoStream using the MemoryStream
// and the passed key and initialization vector (IV).
CryptoStream cStream = new CryptoStream( mStream,
tdsp.CreateEncryptor( key, iv ),
CryptoStreamMode.Write );
// Write the byte array to the crypto stream and flush it.
cStream.Write( data, 0, data.Length );
cStream.FlushFinalBlock();
// Get an array of bytes from the
// MemoryStream that holds the
// encrypted data.
byte[] ret = mStream.ToArray();
// Close the streams.
cStream.Close();
mStream.Close();
// Return the encrypted buffer.
return ret;
}
catch ( CryptographicException e )
{
Console.WriteLine( "A Cryptographic error occurred: {0}", e.Message );
return null;
}
}
/// <summary>
/// DES3 ECB模式解密
/// </summary>
/// <param name="key">密鑰</param>
/// <param name="iv">IV(當模式為ECB時,IV無用)</param>
/// <param name="str">密文的byte數組</param>
/// <returns>明文的byte數組</returns>
public static byte[] Des3DecodeECB( byte[] key, byte[] iv, byte[] data )
{
try
{
// Create a new MemoryStream using the passed
// array of encrypted data.
MemoryStream msDecrypt = new MemoryStream( data );
tdsp = new ();
tdsp.Mode = CipherMode.ECB;
tdsp.Padding = PaddingMode.PKCS7;
// Create a CryptoStream using the MemoryStream
// and the passed key and initialization vector (IV).
CryptoStream csDecrypt = new CryptoStream( msDecrypt,
tdsp.CreateDecryptor( key, iv ),
CryptoStreamMode.Read );
// Create buffer to hold the decrypted data.
byte[] fromEncrypt = new byte[data.Length];
// Read the decrypted data out of the crypto stream
// and place it into the temporary buffer.
csDecrypt.Read( fromEncrypt, 0, fromEncrypt.Length );
//Convert the buffer into a string and return it.
return fromEncrypt;
}
catch ( CryptographicException e )
{
Console.WriteLine( "A Cryptographic error occurred: {0}", e.Message );
return null;
}
}
#endregion
/// <summary>
/// 類測試
/// </summary>
public static void Test()
{
System.Text.Encoding utf8 = System.Text.Encoding.UTF8;
//key為abcdefghijklmnopqrstuvwx的Base64編碼
byte[] key = Convert.FromBase64String( "" );
byte[] iv = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8 }; //當模式為ECB時,IV無用
byte[] data = utf8.GetBytes( "中國ABCabc123" );
System.Console.WriteLine( "ECB模式:" );
byte[] str1 = Des3.Des3EncodeECB( key, iv, data );
byte[] str2 = Des3.Des3DecodeECB( key, iv, str1 );
System.Console.WriteLine( Convert.ToBase64String( str1 ) );
System.Console.WriteLine( System.Text.Encoding.UTF8.GetString( str2 ) );
System.Console.WriteLine();
System.Console.WriteLine( "CBC模式:" );
byte[] str3 = Des3.Des3EncodeCBC( key, iv, data );
byte[] str4 = Des3.Des3DecodeCBC( key, iv, str3 );
System.Console.WriteLine( Convert.ToBase64String( str3 ) );
System.Console.WriteLine( utf8.GetString( str4 ) );
System.Console.WriteLine();
}
}
java 代碼:
import java.security.Key;
import javax.crypto.Cipher;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESedeKeySpec;
import javax.crypto.spec.IvParameterSpec;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;
public class Des3 {
public static void main(String[] args) throws Exception {
byte[] key=new BASE64Decoder().decodeBuffer("");
byte[] keyiv = { 1, 2, 3, 4, 5, 6, 7, 8 };
byte[] data="中國ABCabc123".getBytes("UTF-8");

System.out.println("ECB加密解密");
byte[] str3 = des3EncodeECB(key,data );
byte[] str4 = ees3DecodeECB(key, str3);
System.out.println(new BASE64Encoder().encode(str3));
System.out.println(new String(str4, "UTF-8"));
System.out.println();
System.out.println("CBC加密解密");
byte[] str5 = des3EncodeCBC(key, keyiv, data);
byte[] str6 = des3DecodeCBC(key, keyiv, str5);
System.out.println(new BASE64Encoder().encode(str5));
System.out.println(new String(str6, "UTF-8"));
}
/**
* ECB加密,不要IV
* @param key 密鑰
* @param data 明文
* @return Base64編碼的密文
* @throws Exception
*/
public static byte[] des3EncodeECB(byte[] key, byte[] data)
throws Exception {
Key deskey = null;
DESedeKeySpec spec = new DESedeKeySpec(key);
SecretKeyFactory keyfactory = SecretKeyFactory.getInstance("desede");
deskey = keyfactory.generateSecret(spec);
Cipher cipher = Cipher.getInstance("desede" + "/ECB/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, deskey);
byte[] bOut = cipher.doFinal(data);
return bOut;
}
/**
* ECB解密,不要IV
* @param key 密鑰
* @param data Base64編碼的密文
* @return 明文
* @throws Exception
*/
public static byte[] ees3DecodeECB(byte[] key, byte[] data)
throws Exception {
Key deskey = null;
DESedeKeySpec spec = new DESedeKeySpec(key);
SecretKeyFactory keyfactory = SecretKeyFactory.getInstance("desede");
deskey = keyfactory.generateSecret(spec);
Cipher cipher = Cipher.getInstance("desede" + "/ECB/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE, deskey);
byte[] bOut = cipher.doFinal(data);
return bOut;
}
/**
* CBC加密
* @param key 密鑰
* @param keyiv IV
* @param data 明文
* @return Base64編碼的密文
* @throws Exception
*/
public static byte[] des3EncodeCBC(byte[] key, byte[] keyiv, byte[] data)
throws Exception {
Key deskey = null;
DESedeKeySpec spec = new DESedeKeySpec(key);
SecretKeyFactory keyfactory = SecretKeyFactory.getInstance("desede");
deskey = keyfactory.generateSecret(spec);
Cipher cipher = Cipher.getInstance("desede" + "/CBC/PKCS5Padding");
IvParameterSpec ips = new IvParameterSpec(keyiv);
cipher.init(Cipher.ENCRYPT_MODE, deskey, ips);
byte[] bOut = cipher.doFinal(data);
return bOut;
}
/**
* CBC解密
* @param key 密鑰
* @param keyiv IV
* @param data Base64編碼的密文
* @return 明文
* @throws Exception
*/
public static byte[] des3DecodeCBC(byte[] key, byte[] keyiv, byte[] data)
throws Exception {
Key deskey = null;
DESedeKeySpec spec = new DESedeKeySpec(key);
SecretKeyFactory keyfactory = SecretKeyFactory.getInstance("desede");
deskey = keyfactory.generateSecret(spec);
Cipher cipher = Cipher.getInstance("desede" + "/CBC/PKCS5Padding");
IvParameterSpec ips = new IvParameterSpec(keyiv);
cipher.init(Cipher.DECRYPT_MODE, deskey, ips);
byte[] bOut = cipher.doFinal(data);
return bOut;
}
}

9. des解密演算法,利用C語言解密JAVA語言加密的密碼。。密鑰為12345678,加密後的密文為:26d086be3a3a62fc

// C 語言 DES用的是 ECB模式, 沒有填充
// 因此Java端要對應, 你的明文是 liubiao 嗎?
// 另外 DES已經不安全了, 如果可以改為 3DES或者 AES吧。
public class LearnDes {

public static void main(String[] args) {
try {
System.out.println(encrypt("liubiao", "12345678"));

System.out.println(decrypt("26d086be3a3a62fc", "12345678"));
} catch (Exception e) {
e.printStackTrace();
}
}
public static String encrypt(String message, String key) throws Exception {
//Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
Cipher cipher = Cipher.getInstance("DES/ECB/NOPADDING");

DESKeySpec desKeySpec = new DESKeySpec(key.getBytes("UTF-8"));

SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
SecretKey secretKey = keyFactory.generateSecret(desKeySpec);
IvParameterSpec iv = new IvParameterSpec(key.getBytes("UTF-8"));
//cipher.init(Cipher.ENCRYPT_MODE, secretKey, iv);
cipher.init(Cipher.ENCRYPT_MODE, secretKey );

return toHexString(cipher.doFinal(message.getBytes("UTF-8")));
}

public static String decrypt(String message, String key) throws Exception {

byte[] bytesrc = convertHexString(message);

//Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
Cipher cipher = Cipher.getInstance("DES/ECB/NOPADDING");
DESKeySpec desKeySpec = new DESKeySpec(key.getBytes("UTF-8"));
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
SecretKey secretKey = keyFactory.generateSecret(desKeySpec);
IvParameterSpec iv = new IvParameterSpec(key.getBytes("UTF-8"));

//cipher.init(Cipher.DECRYPT_MODE, secretKey, iv);
cipher.init(Cipher.DECRYPT_MODE, secretKey );

byte[] retByte = cipher.doFinal(bytesrc);
return new String(retByte);
}

public static byte[] convertHexString(String ss) {
byte digest[] = new byte[ss.length() / 2];
for (int i = 0; i < digest.length; i++) {
String byteString = ss.substring(2 * i, 2 * i + 2);
int byteValue = Integer.parseInt(byteString, 16);
digest[i] = (byte) byteValue;
}

return digest;
}
public static String toHexString(byte b[]) {
StringBuffer hexString = new StringBuffer();
for (int i = 0; i < b.length; i++) {
String plainText = Integer.toHexString(0xff & b[i]);
if (plainText.length() < 2)
plainText = "0" + plainText;
hexString.append(plainText);
}

return hexString.toString();
}
}