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

解决方案 »

  1.   

    c#类写错了
    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();
    } }
    }
      

  2.   

    UP一下,只懂C#不會java。。幫頂了..
      

  3.   

    改了一下
    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......
      

  4.   

    兄弟, 看了你的代码,感觉写的比较乱, 关键问题出在这里了,就是你在java程序
    中只设置了key,没有设置向量, 而你在C#中iv和key都设置了,所以结果会不一样有问题可以找我, 我也完成国垒石的代码
      

  5.   

    除了以上问题外,不知你的Padding模式是否一样,C#默认是CBC
      

  6.   

    DES是标准的对称加密算法,所以两者的加密应该是相同的,算法采用的密钥长度可以是8bit或者16bit。至于加密的结果不一样,这是因为VI(初始向量)不同。DES的起始VI是随机的,所以加密结果不同。但是解密过程是相反的,解密到最后一组字节流的时候就得到了VI,这个VI在解密完成后会被舍弃。所以两种实现的加密的结果不同是没有关系的,同样可以解密。
      

  7.   

    初始化向量vi是可以设置的,两边可以设置相同的vi,然后密约也可以设置相同的,我给你一个程序吧,这是我在项目中实际做的一段代码,也是涉及到java和C#的交叉加密解密。关键问题是设置相同初始化向量和密钥。java下:
    // 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);
      

  8.   

    好啊,我与正在搞这个,头大啊,连MD5在.net里与通用的加出来都不同!!
    收藏.....
      

  9.   

    我也是啊,烦啊,我的3DES不知道怎与人家java的对接啊!!实在不行,只有架个tamcat 的java server自己传成明文,再用.net调.....呵呵
    晕啊