C#与JAVA的DES加密结果一致的参数设置

文章出自 http://blog.csdn.net/soar_ersa/article/details/7550359
DES加密解密结果一般要注意的地方:密钥、偏移量、块密码模式、填充模式
java DES加密的时候:
如果使用这种方式,Cipher cipher = Cipher.getInstance("DES"); 此时块密码模式是ECB模式,C#DES类默认模式是CBC模式,所以如果java使用上面的方式进行初始化的时候,使用C#解密的时候要记得设置Mode属性为ECB,另外,如果没有设置偏移量,C#解密的时候Key和IV设置成一样的就可以进行正常解密了。
所以对于上面java的第2种DES加密方法,使用C#解密的时候只需要在解密之前加上"provider.Mode = CipherMode.ECB;"就可以了。

最近需要使用C#的DES解密工具类解密字符串,但是要解密的字符串是使用java进行DES加密的,去网上查了关于C#和java关于DES加密解密的资料,发现可以相互加密解密的时候,

java进行DES加密一般都会写成如下:
public static byte[] encrypt(String message, String key) throws Exception {   
  Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");   //这里指定了CBC模式. 如果是Cipher.getInstance("DES")则是EBC模式

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

//SecureRandom sr = new SecureRandom();

//cipher.init(Cipher.ENCRYPT_MODE, secretKey, sr);   //这种没有偏移量的init ,偏移量就是key
  return cipher.doFinal(message.getBytes("UTF-8"));   
}


C#对应的加密方法

public static string DesEncrypt(string pToEncrypt, string sKey)
        {
            string DecryptText = string.Empty;
            using (DESCryptoServiceProvider des = new DESCryptoServiceProvider())
            {
                des.Mode = CipherMode.ECB;//这里指定加密模式为ECB
                byte[] inputByteArray = Encoding.UTF8.GetBytes(pToEncrypt);
                des.Key = ASCIIEncoding.ASCII.GetBytes(sKey);
                des.IV = ASCIIEncoding.ASCII.GetBytes(sKey);
                System.IO.MemoryStream ms = new System.IO.MemoryStream();
                using (CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(), CryptoStreamMode.Write))
                {
                    cs.Write(inputByteArray, 0, inputByteArray.Length);
                    cs.FlushFinalBlock();
                    cs.Close();
                }
                string str = Convert.ToBase64String(ms.ToArray());
                ms.Close();
                return str;
            }
        }

  • 3
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值