欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

C#对应Java DES的加解密方法

程序员文章站 2024-03-14 11:02:16
...

在网上找了一圈,没找到C#对应Java Des的加解密方法,要么解出来的不对,要么报错,自己看了下Java的源码才恍然大悟,关键地方我已经加上注释,希望能帮到需要的人。

Java 加解密方法

 //加密方法,以String明文输入,密文输出 注意**16位,其实也是8位,只不过加密偏移量8位,私钥8位,请看后面源码
  public static String EncryptDes(String data, String sourcekey)
    throws Exception
  {
      //DES加密和解密过程中,**长度都必须是8的倍数
    if ((sourcekey == null) || (sourcekey.length() != 16))
    {
      throw new Exception("KEY必须为16字节字符串");
    }
    //设置秘钥 **共16位
    //取前八位为私钥
    byte[] key = sourcekey.substring(0, 8).getBytes(charset);
    //取后八位为偏移量
    byte[] iv = sourcekey.substring(8).getBytes(charset);
    //设置秘钥参数
    DESKeySpec dks = new DESKeySpec(key);
    //获得秘钥工厂
    SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
    //获得秘钥对象
    SecretKey secretKey = keyFactory.generateSecret(dks);

    Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
    //设置向量
    IvParameterSpec param = new IvParameterSpec(iv);
    // 用密匙初始化Cipher对象
    cipher.init(1, secretKey, param);
    //加密
    byte[] encryptedData = cipher.doFinal(data.getBytes(charset));

    return new String(Base64.encode(encryptedData), charset);
  }
  //Java 解密方法
  public static String DecryptDes(String data, String sourcekey) throws Exception
  {
    if ((sourcekey == null) || (sourcekey.length() != 16))
    {
      throw new Exception("KEY必须为16字节字符串");
    }
    byte[] key = sourcekey.substring(0, 8).getBytes(charset);
    byte[] iv = sourcekey.substring(8).getBytes(charset);

    DESKeySpec dks = new DESKeySpec(key);

    SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
    SecretKey secretKey = keyFactory.generateSecret(dks);

    Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");

    IvParameterSpec param = new IvParameterSpec(iv);
    cipher.init(2, secretKey, param);

    byte[] decryptedData = cipher.doFinal(Base64.decode(data.getBytes(charset)));

    return new String(decryptedData, charset);
  }

对应的C#加解密方法

    /// <summary>
    /// 加密
    /// </summary>
    /// <param name="sourceString">原文</param>
    /// <param name="sourcekey">16位**,其实也是8位,只不过加密偏移量取后8位,私钥取前8位,请看后面源码</param>
    /// <returns></returns>
    public static string EncryptDes(string sourceString, String sourcekey)
    {
        if (sourcekey == null || sourcekey.Length != 16)
            return null;
        //取前八位作为私钥
        String key = sourcekey.Substring(0, 8);
        //取后八位作为加密偏移量
        String iv = sourcekey.Substring(8);
        byte[] btKey = Encoding.UTF8.GetBytes(key);
        byte[] btIV = Encoding.UTF8.GetBytes(iv);
        DESCryptoServiceProvider des = new DESCryptoServiceProvider();
        using (MemoryStream ms = new MemoryStream())
        {
            try
            {
                byte[] inData = Encoding.UTF8.GetBytes(sourceString);
                using (CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(btKey, btIV), CryptoStreamMode.Write))
                {
                    cs.Write(inData, 0, inData.Length);
                    cs.FlushFinalBlock();
                }
                //Base64
                return Convert.ToBase64String(ms.ToArray());
            }
            catch
            {
                return null;
            }
        }
    }

    /// <summary>
    /// 解密
    /// </summary>
    /// <param name="sourceString">原文</param>
    /// <param name="sourcekey">16位**,其实也是8位,只不过加密偏移量取后8位,私钥取前8位,请看后面源码</param>
    /// <returns></returns>
    public static string DecryptDes(string sourceString, String sourcekey)
    {
        if (sourcekey == null || sourcekey.Length != 16)
            return null;
        //取前八位作为私钥
        String key = sourcekey.Substring(0, 8);
        //取后八位作为加密偏移量
        String iv = sourcekey.Substring(8);
        byte[] btKey = Encoding.UTF8.GetBytes(key);
        byte[] btIV = Encoding.UTF8.GetBytes(iv);
        DESCryptoServiceProvider des = new DESCryptoServiceProvider();
        using (MemoryStream ms = new MemoryStream())
        {
            try
            {
                //Base64
                byte[] inData = Convert.FromBase64String(sourceString);
                using (CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(btKey, btIV), CryptoStreamMode.Write))
                {
                    cs.Write(inData, 0, inData.Length);
                    cs.FlushFinalBlock();
                }
                return Encoding.UTF8.GetString(ms.ToArray());
            }
            catch
            {
                return null;
            }
        }
    }