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();
}
}