Java与.NET的DES加密

从网上找了不少的DES加密源代码,有关 C# 和 Java。

由于.NET默认 CBC模式的DES加密,这样JAVA也得是CBC模式的加密。

java #

import   javax.crypto.*;
import   javax.crypto.spec.DESKeySpec;
public   class   DES   {
 private   byte[]   desKey;
 private   final   byte[]   EncryptionIV   =   "ABCDEFGH".getBytes();
 private   final   static   String   DES   =   "DES/CBC/PKCS5Padding";

 public   DES(byte[]   desKey)
 {
  this.desKey   =   desKey;
 }
 public   byte[]   doEncrypt(byte[]   plainText)   throws   Exception
 {
  javax.crypto.spec.IvParameterSpec spec=new javax.crypto.spec.IvParameterSpec( EncryptionIV );
  byte   rawKeyData[]   =   desKey;
  DESKeySpec   dks   =   new   DESKeySpec(rawKeyData);
  SecretKeyFactory   keyFactory   =   SecretKeyFactory.getInstance("DES");
  SecretKey   key   =   keyFactory.generateSecret(dks);
  Cipher   cipher   =   Cipher.getInstance(DES);
  cipher.init(Cipher.ENCRYPT_MODE,   key,   spec );
  byte   data[]   =   plainText;
  byte   encryptedData[]   =   cipher.doFinal(data);
  return   encryptedData;
 }
 }

接下来用 C# .Net

public sealed class DESEncrypt
{

    private static string key = "11111111";
    private static string IV =  "11111111";

    public static string Key
    {
        get
        {
            return key;
        }
        set
        {
            key = value;
        }
    }

    public static byte[] DesEncrypt(string encryptString)
    {
        byte[] keyBytes = Encoding.UTF8.GetBytes(key.Substring(0, 8));
        byte[] keyIV =  Encoding.UTF8.GetBytes(IV.Substring(0, 8));

        byte[] inputByteArray = Encoding.UTF8.GetBytes(encryptString);
        DESCryptoServiceProvider provider = new DESCryptoServiceProvider();
        MemoryStream mStream = new MemoryStream();
        CryptoStream cStream = new CryptoStream(mStream, provider.CreateEncryptor(keyBytes, keyIV), CryptoStreamMode.Write);
        cStream.Write(inputByteArray, 0, inputByteArray.Length);
        cStream.FlushFinalBlock();
        return mStream.ToArray();
    }
}

经测试, 两段代码所完成的加密结果是一样的。

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值