Java DES与C# DES 加密是一样的算法吗?为什么加密的结果不一致.如何才能正确在java中DES加密,C#/VB中解密.java中用DES加密的结果怎么与C#不一样呀!??
DES.java:
import java.security.SecureRandom;
import javax.crypto.*;
import javax.crypto.spec.DESKeySpec;
public class DES {
private byte[] desKey;
public DES(byte[] desKey) {
this.desKey = desKey;
}
public byte[] doEncrypt(byte[] plainText) throws Exception {
// DES算法要求有一个可信任的随机数源
SecureRandom sr = new SecureRandom();
byte rawKeyData[] = desKey;/* 用某种方法获得密匙数据 */
// 从原始密匙数据创建DESKeySpec对象
DESKeySpec dks = new DESKeySpec(rawKeyData);
// 创建一个密匙工厂,然后用它把DESKeySpec转换成
// 一个SecretKey对象
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
SecretKey key = keyFactory.generateSecret(dks);
// Cipher对象实际完成加密操作
Cipher cipher = Cipher.getInstance("DES");
// 用密匙初始化Cipher对象
cipher.init(Cipher.ENCRYPT_MODE, key, sr);
// 现在,获取数据并加密
byte data[] = plainText;/* 用某种方法获取数据 */
// 正式执行加密操作
byte encryptedData[] = cipher.doFinal(data);
return encryptedData;
} public static void main(String[] args) throws Exception {
String key = "ABCDEFGH";
String value = "013988888888";
DES desEncrypt = new DES(key.getBytes());
byte[] encryptText = desEncrypt.doEncrypt(value.getBytes());
System.out.println("doEncrypt - " + toHexString(encryptText));
System.out.println("doEncrypt - " + new String(encryptText)); byte[] decryptText = desEncrypt.doDecrypt(encryptText);
System.out.println("doDecrypt - " + new String(decryptText));
System.out.println("doDecrypt - " + toHexString(decryptText));
}
}c#类:
using System;
using System.IO;
using System.Security.Cryptography;namespace test1
{
public class Security
{
const string KEY_64 = "ABCDEFGH";
const string IV_64 = "ABCDEFGH"; //注意了,是8个字符,64位 public Security()
{
//
// TODO: 在此处添加构造函数逻辑
//
} public static string Encode(string data)
{
byte[] byKey = System.Text.ASCIIEncoding.ASCII.GetBytes(KEY_64);
byte[] byIV = System.Text.ASCIIEncoding.ASCII.GetBytes(IV_64); DESCryptoServiceProvider cryptoProvider = new DESCryptoServiceProvider();
int i = cryptoProvider.KeySize;
MemoryStream ms = new MemoryStream();
CryptoStream cst = new CryptoStream(ms,cryptoProvider.CreateEncryptor(byKey,byIV),CryptoStreamMode.Write);
StreamWriter sw = new StreamWriter(cst);
sw.Write(data);
sw.Flush();
cst.FlushFinalBlock();
sw.Flush();
/*byte[] temp=ms.GetBuffer();
string stemp="";
for(int j=0;j<temp.Length;j++)
stemp+=temp[j];*/
Console.WriteLine(Convert.ToBase64String(ms.GetBuffer(),0,(int)ms.Length));
for(int m=0;m<(int)ms.Length;m++)
{
Console.WriteLine(ms.GetBuffer()[m]);
}
Console.WriteLine("");
return "";
}
}
}
DES.java:
import java.security.SecureRandom;
import javax.crypto.*;
import javax.crypto.spec.DESKeySpec;
public class DES {
private byte[] desKey;
public DES(byte[] desKey) {
this.desKey = desKey;
}
public byte[] doEncrypt(byte[] plainText) throws Exception {
// DES算法要求有一个可信任的随机数源
SecureRandom sr = new SecureRandom();
byte rawKeyData[] = desKey;/* 用某种方法获得密匙数据 */
// 从原始密匙数据创建DESKeySpec对象
DESKeySpec dks = new DESKeySpec(rawKeyData);
// 创建一个密匙工厂,然后用它把DESKeySpec转换成
// 一个SecretKey对象
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
SecretKey key = keyFactory.generateSecret(dks);
// Cipher对象实际完成加密操作
Cipher cipher = Cipher.getInstance("DES");
// 用密匙初始化Cipher对象
cipher.init(Cipher.ENCRYPT_MODE, key, sr);
// 现在,获取数据并加密
byte data[] = plainText;/* 用某种方法获取数据 */
// 正式执行加密操作
byte encryptedData[] = cipher.doFinal(data);
return encryptedData;
} public static void main(String[] args) throws Exception {
String key = "ABCDEFGH";
String value = "013988888888";
DES desEncrypt = new DES(key.getBytes());
byte[] encryptText = desEncrypt.doEncrypt(value.getBytes());
System.out.println("doEncrypt - " + toHexString(encryptText));
System.out.println("doEncrypt - " + new String(encryptText)); byte[] decryptText = desEncrypt.doDecrypt(encryptText);
System.out.println("doDecrypt - " + new String(decryptText));
System.out.println("doDecrypt - " + toHexString(decryptText));
}
}c#类:
using System;
using System.IO;
using System.Security.Cryptography;namespace test1
{
public class Security
{
const string KEY_64 = "ABCDEFGH";
const string IV_64 = "ABCDEFGH"; //注意了,是8个字符,64位 public Security()
{
//
// TODO: 在此处添加构造函数逻辑
//
} public static string Encode(string data)
{
byte[] byKey = System.Text.ASCIIEncoding.ASCII.GetBytes(KEY_64);
byte[] byIV = System.Text.ASCIIEncoding.ASCII.GetBytes(IV_64); DESCryptoServiceProvider cryptoProvider = new DESCryptoServiceProvider();
int i = cryptoProvider.KeySize;
MemoryStream ms = new MemoryStream();
CryptoStream cst = new CryptoStream(ms,cryptoProvider.CreateEncryptor(byKey,byIV),CryptoStreamMode.Write);
StreamWriter sw = new StreamWriter(cst);
sw.Write(data);
sw.Flush();
cst.FlushFinalBlock();
sw.Flush();
/*byte[] temp=ms.GetBuffer();
string stemp="";
for(int j=0;j<temp.Length;j++)
stemp+=temp[j];*/
Console.WriteLine(Convert.ToBase64String(ms.GetBuffer(),0,(int)ms.Length));
for(int m=0;m<(int)ms.Length;m++)
{
Console.WriteLine(ms.GetBuffer()[m]);
}
Console.WriteLine("");
return "";
}
}
}
namespace test1
{
/// <summary>
/// Security 的摘要说明。
/// </summary>
public class Security
{
const string KEY_64 = "ABCDEFGH";
const string IV_64 = "ABCDEFGH"; //注意了,是8个字符,64位 public Security()
{
//
// TODO: 在此处添加构造函数逻辑
//
} public static byte[] Encode(string data)
{
byte[] byKey = System.Text.ASCIIEncoding.ASCII.GetBytes(KEY_64);
byte[] byIV = System.Text.ASCIIEncoding.ASCII.GetBytes(IV_64); DESCryptoServiceProvider cryptoProvider = new DESCryptoServiceProvider();
int i = cryptoProvider.KeySize;
MemoryStream ms = new MemoryStream();
CryptoStream cst = new CryptoStream(ms,cryptoProvider.CreateEncryptor(byKey,byIV),CryptoStreamMode.Write);
StreamWriter sw = new StreamWriter(cst);
sw.Write(data);
sw.Flush();
cst.FlushFinalBlock();
sw.Flush();
return ms.GetBuffer();
} }
}
C#:其中KEY_64\IV_64均为"ABCDEFGH"
public static string Encode(string data)
{
byte[] byKey = System.Text.ASCIIEncoding.ASCII.GetBytes(KEY_64);
byte[] byIV = System.Text.ASCIIEncoding.ASCII.GetBytes(IV_64); DESCryptoServiceProvider cryptoProvider = new DESCryptoServiceProvider();
int i = cryptoProvider.KeySize;
MemoryStream ms = new MemoryStream();
CryptoStream cst = new CryptoStream(ms,cryptoProvider.CreateEncryptor(byKey,byIV),CryptoStreamMode.Write);
StreamWriter sw = new StreamWriter(cst);
sw.Write(data);
sw.Flush();
cst.FlushFinalBlock();
sw.Flush();
return Convert.ToBase64String(ms.GetBuffer(),0,(int)ms.Length);
}
Encode("13988888888")后得到结果是"BHFtXIFNMTKfE+QcKrxL9w=="java改为:
import javax.crypto.*;
import java.io.*;
import javax.crypto.spec.*;
import java.security.spec.*;public class DES {
Cipher ecipher;
Cipher dcipher;
// 8-byte Salt
byte[] salt = {
(byte)0x41, (byte)0x42, (byte)0x43, (byte)0x44,
(byte)0x45, (byte)0x46, (byte)0x47, (byte)0x48
};
// Iteration count
int iterationCount = 19;
DES(String passPhrase) {
try {
// Create the key
KeySpec keySpec = new PBEKeySpec(passPhrase.toCharArray(), salt, iterationCount);
SecretKey key = SecretKeyFactory.getInstance(
"PBEWithMD5AndDES").generateSecret(keySpec);
ecipher = Cipher.getInstance(key.getAlgorithm());
dcipher = Cipher.getInstance(key.getAlgorithm());
// Prepare the parameter to the ciphers
AlgorithmParameterSpec paramSpec = new PBEParameterSpec(salt, iterationCount);
// Create the ciphers
ecipher.init(Cipher.ENCRYPT_MODE, key, paramSpec);
dcipher.init(Cipher.DECRYPT_MODE, key, paramSpec);
} catch (java.security.InvalidAlgorithmParameterException e) {
} catch (java.security.spec.InvalidKeySpecException e) {
} catch (javax.crypto.NoSuchPaddingException e) {
} catch (java.security.NoSuchAlgorithmException e) {
} catch (java.security.InvalidKeyException e) {
}
}
public String encrypt(String str) {
try {
// Encode the string into bytes using utf-8
byte[] utf8 = str.getBytes("UTF8");
// Encrypt
byte[] enc = ecipher.doFinal(utf8);
// Encode bytes to base64 to get a string
return new sun.misc.BASE64Encoder().encode(enc);
} catch (javax.crypto.BadPaddingException e) {
} catch (IllegalBlockSizeException e) {
} catch (UnsupportedEncodingException e) {
} catch (java.io.IOException e) {
}
return null;
}
public String decrypt(String str) {
try {
// Decode base64 to get bytes
byte[] dec = new sun.misc.BASE64Decoder().decodeBuffer(str);
// Decrypt
byte[] utf8 = dcipher.doFinal(dec);
// Decode using utf-8
return new String(utf8, "UTF8");
} catch (javax.crypto.BadPaddingException e) {
} catch (IllegalBlockSizeException e) {
} catch (UnsupportedEncodingException e) {
} catch (java.io.IOException e) {
}
return null;
}
// Here is an example that uses the class
public static void main(String s[])
{
try {
// Create encrypter/decrypter class
DES encrypter = new DES("ABCDEFGH");
// Encrypt
String encrypted = encrypter.encrypt("13988888888");
System.out.println(encrypted);
// Decrypt
String decrypted = encrypter.decrypt(encrypted);
System.out.println(decrypted);
} catch (Exception e) {e.printStackTrace();}}
}
加密结果是"0fqEGapnVxUtJ/SCaRqIqA=="
还是不一样呀!!不解ing......痛苦ing......
中只设置了key,没有设置向量, 而你在C#中iv和key都设置了,所以结果会不一样有问题可以找我, 我也完成国垒石的代码
// The initialization vector should be 8 bytes
private final byte[] EncryptionIV = "abcdefgh".getBytes();
private final static String DES = "DES/CBC/PKCS5Padding";
// Create SecretKey object
byte[] EncryptionByte = EncryptionString.getBytes();
DESKeySpec dks = new DESKeySpec(EncryptionByte);
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
SecretKey securekey = keyFactory.generateSecret(dks);// Initialize Cipher object
cipher.init(Cipher.DECRYPT_MODE, securekey, spec);
收藏.....
晕啊