Barchiel122
2021-08-12 21:54
采纳率: 100%
浏览 26

用C#写DES加密算法解密出错

img

  • 好问题 提建议
  • 收藏

1条回答 默认 最新

  • guwei4037 2021-08-12 21:59
    已采纳
    
    namespace ConsoleApplication1
    {
        class Program
        {
            static void Main(string[] args)
            {
                string result = DESStr("guwei4037");
                Console.WriteLine("这是你的加密结果:{0}", result);//1tE8zvi9ouQJNb4FlxlKFQ==
     
                string src = FromDESStr(result);
                Console.WriteLine("这是我的解密结果:{0}", src);//guwei4037
            }
     
            /// <summary>
            /// DES加密
            /// </summary>
            /// <param name="src"></param>
            /// <returns></returns>
            public static string DESStr(string src)
            {
                string des = string.Empty;
                byte[] bysData = Encoding.UTF8.GetBytes(src);
     
                DESCryptoServiceProvider objDESCryptoServiceProvider = new DESCryptoServiceProvider();
                objDESCryptoServiceProvider.Key = Encoding.ASCII.GetBytes("12345678");//密钥
                objDESCryptoServiceProvider.Mode = CipherMode.ECB;
                objDESCryptoServiceProvider.Padding = PaddingMode.None;
     
                byte[] bysFixSizeData = new byte[(int)Math.Ceiling(bysData.Length / 8.0) * 8];
                Array.Copy(bysData, bysFixSizeData, bysData.Length);
     
                byte[] bysEncrypted = objDESCryptoServiceProvider.CreateEncryptor().TransformFinalBlock(bysFixSizeData, 0, bysFixSizeData.Length);//加密
                des = Convert.ToBase64String(bysEncrypted);//加密后的字符串
                if (des.Equals("")) des = "error";
                return des;
            }
     
            /// <summary>
            /// DES解密
            /// </summary>
            /// <param name="str"></param>
            /// <returns></returns>
            public static string FromDESStr(string str)
            {
                string des = string.Empty;
                byte[] inputByteArray = Convert.FromBase64String(str);
     
                DESCryptoServiceProvider objDESCryptoServiceProvider = new DESCryptoServiceProvider();
                objDESCryptoServiceProvider.Key = Encoding.ASCII.GetBytes("12345678");//密钥
                objDESCryptoServiceProvider.Mode = CipherMode.ECB;
                objDESCryptoServiceProvider.Padding = PaddingMode.None;
     
                byte[] bysDEcrypted = objDESCryptoServiceProvider.CreateDecryptor().TransformFinalBlock(inputByteArray, 0, inputByteArray.Length);//解密
                byte[] bysFixSizeData = new byte[(int)Math.Ceiling(bysDEcrypted.Length / 8.0) * 8];
                Array.Copy(bysDEcrypted, bysFixSizeData, bysDEcrypted.Length);
     
                des = Encoding.UTF8.GetString(bysFixSizeData);//解密后的字符串
                if (des.Equals("")) des = "error";
                return des;
            }
        }
    }
    
    已采纳该答案
    评论
    解决 无用
    打赏 举报

相关推荐 更多相似问题