当前位置:首页 » 密码管理 » cdes加密java解密

cdes加密java解密

发布时间: 2023-04-23 04:37:01

⑴ DES加密解密问题 java与C 通讯

经测试应该是如下问题:

1.注意取字符串bytes是编码保持一致,c的和java的保存一直,问一下c开发用的是那个。
2.key和Iv保持一致
3.加密模式和填充方式保持一致----------------------------这点的可能性比较大
比如C#里
algo.Mode=CipherMode.ECB;
algo.Padding=PaddingMode.None;
则java里对应的为
final Cipher algo=Cipher.getInstance("DES/ECB/NoPadding");

import java.io.IOException;
import java.security.SecureRandom;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

public class DesUtil {

private final static String DES = "DES";

public static void main(String[] args) throws Exception {
String data = "fff";//原字符
String key = "80825cf7fedff723";//加密key
System.err.println(encrypt(data, key));
System.err.println(decrypt("FAQXWvLnsSA=", key));//进行解密“FAQXWvLnsSA=”

}

/**
* Description 根据键值进行加密
* @param data
* @param key 加密键byte数组
* @return
* @throws Exception
*/
public static String encrypt(String data, String key) throws Exception {
byte[] bt = encrypt(data.getBytes(), key.getBytes());
String strs = new BASE64Encoder().encode(bt);
return strs;
}

/**
* Description 根据键值进行解密
* @param data
* @param key 加密键byte数组
* @return
* @throws IOException
* @throws Exception
*/
public static String decrypt(String data, String key) throws IOException,
Exception {
if (data == null)
return null;
BASE64Decoder decoder = new BASE64Decoder();
byte[] buf = decoder.decodeBuffer(data);
byte[] bt = decrypt(buf,key.getBytes());
return new String(bt);
}

/**
* Description 根据键值进行加密
* @param data
* @param key 加密键byte数组
* @return
* @throws Exception
*/
private static byte[] encrypt(byte[] data, byte[] key) throws Exception {
// 生成一个可信任的随机数源
SecureRandom sr = new SecureRandom();

// 从原始密钥数据创建DESKeySpec对象
DESKeySpec dks = new DESKeySpec(key);

// 创建一个密钥工厂,然后用它把DESKeySpec转换成SecretKey对象
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(DES);
SecretKey securekey = keyFactory.generateSecret(dks);

// Cipher对象实际完成加密操作
Cipher cipher = Cipher.getInstance(DES);

// 用密钥初始化Cipher对象
cipher.init(Cipher.ENCRYPT_MODE, securekey, sr);

return cipher.doFinal(data);
}

/**
* Description 根据键值进行解密
* @param data
* @param key 加密键byte数组
* @return
* @throws Exception
*/
private static byte[] decrypt(byte[] data, byte[] key) throws Exception {
// 生成一个可信任的随机数源
SecureRandom sr = new SecureRandom();

// 从原始密钥数据创建DESKeySpec对象
DESKeySpec dks = new DESKeySpec(key);

// 创建一个密钥工厂,然后用它把DESKeySpec转换成SecretKey对象
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(DES);
SecretKey securekey = keyFactory.generateSecret(dks);

// Cipher对象实际完成解密操作
Cipher cipher = Cipher.getInstance(DES);

// 用密钥初始化Cipher对象
cipher.init(Cipher.DECRYPT_MODE, securekey, sr);

return cipher.doFinal(data);
}
}

⑵ Des加密解密方法 用java C#和C++三种方式实现

Solaris下的系统,有一个用C做的加密工具,调用Sunwcry的des(1)对文件进行加密,然后在java中对文件进行解密。java中用的是标准的DES/CBC/NoPadding算法,可是解密后发现开头有8byte的数据出错了,请高人指点一下。

cbc_encrypt.c : 加密用的C程序

cbc_decrypt.c:解密用的C程序

TestDescbc.java:解密用的java程序

Test01.dat原始文件
Test03.dat cbc_encrypt加密后的文件
Test05.dat cbc_decrypt解密后的文件

Test06.dat TestDescbc解密后的文件

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

⑷ 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;
}
}

⑸ 如题,求Java的DES算法代码,可以用于解密用C语言写的DES加密算法!其中C语言代码见问题补充

俺就是来帮助你这样可爱的人。俺可是花了几年的时间费了多大的力气才能把这个东西弄出来!

DES加密还没有AES严密:

packagecom.palic.pss.afcs.worldthrough.common.util;
importjavax.crypto.Cipher;
importjavax.crypto.spec.SecretKeySpec;
importrepack.com.thoughtworks.xstream.core.util.Base64Encoder;
/**
*AES加密解密
*@author
*
*/
publicclassAesUtils{
publicstaticfinalStringcKey="assistant7654321";
/**
*加密--把加密后的byte数组先进行二进制转16进制在进行base64编码
*@paramsSrc
*@paramsKey
*@return
*@throwsException
*/
publicstaticStringencrypt(StringsSrc,StringsKey)throwsException{
if(sKey==null){
("ArgumentsKeyisnull.");
}
if(sKey.length()!=16){
(
"ArgumentsKey'lengthisnot16.");
}
byte[]raw=sKey.getBytes("ASCII");
SecretKeySpecskeySpec=newSecretKeySpec(raw,"AES");

Ciphercipher=Cipher.getInstance("AES");
cipher.init(Cipher.ENCRYPT_MODE,skeySpec);

byte[]encrypted=cipher.doFinal(sSrc.getBytes("UTF-8"));
StringtempStr=parseByte2HexStr(encrypted);

Base64Encoderencoder=newBase64Encoder();
returnencoder.encode(tempStr.getBytes("UTF-8"));
}

/**
*解密--先进行base64解码,在进行16进制转为2进制然后再解码
*@paramsSrc
*@paramsKey
*@return
*@throwsException
*/
publicstaticStringdecrypt(StringsSrc,StringsKey)throwsException{

if(sKey==null){
("499");
}
if(sKey.length()!=16){
("498");
}

byte[]raw=sKey.getBytes("ASCII");
SecretKeySpecskeySpec=newSecretKeySpec(raw,"AES");

Ciphercipher=Cipher.getInstance("AES");
cipher.init(Cipher.DECRYPT_MODE,skeySpec);

Base64Encoderencoder=newBase64Encoder();
byte[]encrypted1=encoder.decode(sSrc);

StringtempStr=newString(encrypted1,"utf-8");
encrypted1=parseHexStr2Byte(tempStr);
byte[]original=cipher.doFinal(encrypted1);
StringoriginalString=newString(original,"utf-8");
returnoriginalString;
}

/**
*将二进制转换成16进制
*
*@parambuf
*@return
*/
(bytebuf[]){
StringBuffersb=newStringBuffer();
for(inti=0;i<buf.length;i++){
Stringhex=Integer.toHexString(buf[i]&0xFF);
if(hex.length()==1){
hex='0'+hex;
}
sb.append(hex.toUpperCase());
}
returnsb.toString();
}

/**
*将16进制转换为二进制
*
*@paramhexStr
*@return
*/
publicstaticbyte[]parseHexStr2Byte(StringhexStr){
if(hexStr.length()<1)
returnnull;
byte[]result=newbyte[hexStr.length()/2];
for(inti=0;i<hexStr.length()/2;i++){
inthigh=Integer.parseInt(hexStr.substring(i*2,i*2+1),16);
intlow=Integer.parseInt(hexStr.substring(i*2+1,i*2+2),
16);
result[i]=(byte)(high*16+low);
}
returnresult;
}
publicstaticvoidmain(String[]args)throwsException{
/*
*加密用的Key可以用26个字母和数字组成,最好不要用保留字符,虽然不会错,至于怎么裁决,个人看情况而定
*/
StringcKey="assistant7654321";
//需要加密的字串
StringcSrc="123456";
//加密
longlStart=System.currentTimeMillis();
StringenString=encrypt(cSrc,cKey);
System.out.println("加密后的字串是:"+enString);
longlUseTime=System.currentTimeMillis()-lStart;
System.out.println("加密耗时:"+lUseTime+"毫秒");
//解密
lStart=System.currentTimeMillis();
StringDeString=decrypt(enString,cKey);
System.out.println("解密后的字串是:"+DeString);
lUseTime=System.currentTimeMillis()-lStart;
System.out.println("解密耗时:"+lUseTime+"毫秒");
}
}

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

⑺ DES加密解密问题,java 和 C#

usingSystem;
usingSystem.Collections.Generic;
usingSystem.Text;
usingSystem.IO;
usingSystem.Security;
usingSystem.Security.Cryptography;
/*----------------------------------------------
*DES加密、解密类库,字符串加密结果使用BASE64编码返回,支持文件的加密和解密
*作者:三角猫/DeltaCat
*网址:

*转载务必保留此信息
*---------------------------------------------
*/
namespaceZU14
{
publicsealedclassDES
{
stringiv="1234的yzo";
stringkey="123在yzo";
///<summary>
///DES加密偏移量,必须是>=8位长的字符串
///</summary>
publicstringIV
{
get{returniv;}
set{iv=value;}
}
///<summary>
///DES加密的私钥,必须是8位长的字符串
///</summary>
publicstringKey
{
get{returnkey;}
set{key=value;}
}
///<summary>
///对字符串进行DES加密
///</summary>
///<paramname="sourceString">待加密的字符串</param>
///<returns>加密后的BASE64编码的字符串</returns>
publicstringEncrypt(stringsourceString)
{
byte[]btKey=Encoding.Default.GetBytes(key);
byte[]btIV=Encoding.Default.GetBytes(iv);
DESCryptoServiceProviderdes=newDESCryptoServiceProvider();
using(MemoryStreamms=newMemoryStream())
{
byte[]inData=Encoding.Default.GetBytes(sourceString);
try
{
using(CryptoStreamcs=newCryptoStream(ms,des.CreateEncryptor(btKey,btIV),CryptoStreamMode.Write))
{
cs.Write(inData,0,inData.Length);
cs.FlushFinalBlock();
}
returnConvert.ToBase64String(ms.ToArray());
}
catch
{
throw;
}
}
}
///<summary>
///对DES加密后的字符串进行解密
///</summary>
///<paramname="encryptedString">待解密的字符串</param>
///<returns>解密后的字符串</returns>
publicstringDecrypt(stringencryptedString)
{
byte[]btKey=Encoding.Default.GetBytes(key);
byte[]btIV=Encoding.Default.GetBytes(iv);
DESCryptoServiceProviderdes=newDESCryptoServiceProvider();
using(MemoryStreamms=newMemoryStream())
{
byte[]inData=Convert.FromBase64String(encryptedString);
try
{
using(CryptoStreamcs=newCryptoStream(ms,des.CreateDecryptor(btKey,btIV),CryptoStreamMode.Write))
{
cs.Write(inData,0,inData.Length);
cs.FlushFinalBlock();
}
returnEncoding.Default.GetString(ms.ToArray());
}
catch
{
throw;
}
}
}
///<summary>
///对文件内容进行DES加密
///</summary>
///<paramname="sourceFile">待加密的文件绝对路径</param>
///<paramname="destFile">加密后的文件保存的绝对路径</param>
publicvoidEncryptFile(stringsourceFile,stringdestFile)
{
if(!File.Exists(sourceFile))thrownewFileNotFoundException("指定的文件路径不存在!",sourceFile);
byte[]btKey=Encoding.Default.GetBytes(key);
byte[]btIV=Encoding.Default.GetBytes(iv);
DESCryptoServiceProviderdes=newDESCryptoServiceProvider();
byte[]btFile=File.ReadAllBytes(sourceFile);
using(FileStreamfs=newFileStream(destFile,FileMode.Create,FileAccess.Write))
{
try
{
using(CryptoStreamcs=newCryptoStream(fs,des.CreateEncryptor(btKey,btIV),CryptoStreamMode.Write))
{
cs.Write(btFile,0,btFile.Length);
cs.FlushFinalBlock();
}
}
catch
{
throw;
}
finally
{
fs.Close();
}
}
}
///<summary>
///对文件内容进行DES加密,加密后覆盖掉原来的文件
///</summary>
///<paramname="sourceFile">待加密的文件的绝对路径</param>
publicvoidEncryptFile(stringsourceFile)
{
EncryptFile(sourceFile,sourceFile);
}
///<summary>
///对文件内容进行DES解密
///</summary>
///<paramname="sourceFile">待解密的文件绝对路径</param>
///<paramname="destFile">解密后的文件保存的绝对路径</param>
publicvoidDecryptFile(stringsourceFile,stringdestFile)
{
if(!File.Exists(sourceFile))thrownewFileNotFoundException("指定的文件路径不存在!",sourceFile);
byte[]btKey=Encoding.Default.GetBytes(key);
byte[]btIV=Encoding.Default.GetBytes(iv);
DESCryptoServiceProviderdes=newDESCryptoServiceProvider();
byte[]btFile=File.ReadAllBytes(sourceFile);
using(FileStreamfs=newFileStream(destFile,FileMode.Create,FileAccess.Write))
{
try
{
using(CryptoStreamcs=newCryptoStream(fs,des.CreateDecryptor(btKey,btIV),CryptoStreamMode.Write))
{
cs.Write(btFile,0,btFile.Length);
cs.FlushFinalBlock();
}
}
catch
{
throw;
}
finally
{
fs.Close();
}
}
}
///<summary>
///对文件内容进行DES解密,加密后覆盖掉原来的文件
///</summary>
///<paramname="sourceFile">待解密的文件的绝对路径</param>
publicvoidDecryptFile(stringsourceFile)
{
DecryptFile(sourceFile,sourceFile);
}
}
}

⑻ C#与JAVA的DES加密解密

本来就是没有初始化向量这个东西。。。。。可能是C#运行自己提供P盒或者S盒,而java使用ANSI默认的P盒和S盒了。。。你得去看C#的文档说明。。

加密过程本来就是只需要明文和密钥,C#估计只是多给一个参数罢了。。。看看文档去

###################################
什么叫“初始化向量”?我记得上密码学的时候DES里面没有这个概念~~~

DES算法流程就是固定的。可变的只有P盒和S盒。不知道你说的“初始化向量”是不是S盒

加密和解密只是密钥扩展的顺序颠倒,其他算法完全一样。

P盒不是保密的,S盒设计方式保密但是可以在网上美国安全局网站上找到设计好的S盒。

如果你说真有什么“初始化向量”,那可能你用的是前向反馈模式产生序列密码,不过这样的话,保持相同的初始向量也是可能的啊。估计是你程序写的问题。。。而且这样安全性可能你没有办法考证吧。。。

还有。。。你没有搞错吧。。。DES是64位的。。。。你用8位能搞什么。。。

还有。。看样子你是用C#自带的工具来加密的。。。DES概念里面确实没有什么“初始化向量”,具体怎么搞你找密码学的书看看吧。。。

还有一点。。。。是不是C#里面可以选择轮迭次数???默认是16次,还有你要看好是DES还是3DES。

⑼ C++与JAVA通过DES及BASE64 互相加密解密

我运戚猜你大概想要旁档陵将加密的东西应用在android手机上,同时困扰你的还有转码的问题,当时这个也困扰了我很久,特别是后面的补位方式,最后多看书,看几个开源的算法就搞定了。网上有几个可以解决的例子都是错的,蠢誉我自己写了一个,和你说的一样
PKU-一夫

⑽ 如何用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)));
}
}

热点内容
c语言大小写转换程序 发布:2025-02-12 18:55:23 浏览:523
三星耳机坏了怎么配置 发布:2025-02-12 18:54:46 浏览:974
简易编程语言 发布:2025-02-12 18:48:07 浏览:522
咋上传视频 发布:2025-02-12 18:45:50 浏览:287
python的包机制 发布:2025-02-12 18:45:49 浏览:447
sqlserver网络实用工具 发布:2025-02-12 18:38:56 浏览:766
剑与家园新服务器什么时候转国 发布:2025-02-12 18:38:05 浏览:433
php发送email 发布:2025-02-12 18:38:02 浏览:296
扫描二维码密码多少 发布:2025-02-12 18:23:35 浏览:51
北京时间ftp 发布:2025-02-12 18:23:31 浏览:777