• Java加密和C#解密=>DES方法


    Java加密代码:

    import javax.crypto.*;
    import javax.crypto.*;
    import java.io.UnsupportedEncodingException;
    import java.security.spec.*;
    import javax.crypto.spec.*;
    
    public class DES {
    
        public DES()
        {
        }
    
         public String encrypt(String str) {
    
            byte[] enc = null;
            try {
              enc = desEncrypt(str, "abcdefgh");
            }
            catch (Exception ex) {
            }
           
             return new sun.misc.BASE64Encoder().encode(enc);
         }
         
         public static byte[] desEncrypt(String message, String key) throws Exception {
                 Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
     
                 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);
     
                 return cipher.doFinal(message.getBytes("UTF-8"));
             }
    }


    C#加密代码:

        /// <param name="pToDecrypt">要解密的以Base64</param>
            /// <param name="sKey">密钥,且必须为8位。</param>
            /// <returns>已解密的字符串。</returns>
            public string Decrypt(string pToDecrypt, string sKey)
            {
                byte[] inputByteArray = Convert.FromBase64String(pToDecrypt);
                using (DESCryptoServiceProvider des = new DESCryptoServiceProvider())
                {
                    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.CreateDecryptor(), CryptoStreamMode.Write))
                    {
                        cs.Write(inputByteArray, 0, inputByteArray.Length);
                        cs.FlushFinalBlock();
                        cs.Close();
                    }
                    string str = Encoding.UTF8.GetString(ms.ToArray());
                    ms.Close();
                    return str;
                }
            } 


    特别注意关键key=》字符串长度必须为8位数字

  • 相关阅读:
    算法 排序
    Windows系统安装Git
    oracle 查询语句
    .NET CORE AddRazorRuntimeCompilation
    清除html頁面文本框緩存
    ORACLE 生成UUID
    Unable to resolve service for type`***` while attempting to activatre `***`
    xml文件导入Oracle数据库
    jquery 日历控件
    判断并获取一对多表格数据
  • 原文地址:https://www.cnblogs.com/flyfish2012/p/3732627.html
Copyright © 2020-2023  润新知