Reputation: 3
Mis-match happens on des encryption, only happens when the raw text has trailing 1,2,3,4.
I've wrote a fiddler here to demo the issue: https://dotnetfiddle.net/7u0Hzr
Attached the fiddler code inline here if you don't want to get redirected:
using System;
using System.IO;
using System.Text;
using System.Security.Cryptography;
public class Program
{
public static void Main()
{
var key = "abcd1234";
var salt = "4321";
var encrypted = "";
var decrypted = "";
var alphabets = "ABCDEFGHIJKLMNOPQRSTUVWXYZ".ToCharArray();
for (var i = 0; i < 100; i++)
{
var text = $"{Math.Floor((double)i / 10)}{i % 10}";
encrypted = DesEncrypt(text, key, salt);
decrypted = DesDecrypt(encrypted, key, salt);
Console.WriteLine($"Text: {text} | Encrypted: {encrypted} | Decrypted: {decrypted}");
}
}
private static string DesEncrypt(string plaintText, string strKey, string salt)
{
byte[] key = { }; //Encryption Key
byte[] IV = { 10, 20, 30, 40, 50, 60, 70, 80 };
byte[] inputByteArray;
try
{
key = Encoding.UTF8.GetBytes(strKey);
// DESCryptoServiceProvider is a cryptography class defind in c#.
DESCryptoServiceProvider ObjDES = new DESCryptoServiceProvider();
inputByteArray = Encoding.UTF8.GetBytes(plaintText + salt);
MemoryStream Objmst = new MemoryStream();
CryptoStream Objcs = new CryptoStream(Objmst, ObjDES.CreateEncryptor(key, IV), CryptoStreamMode.Write);
Objcs.Write(inputByteArray, 0, inputByteArray.Length);
Objcs.FlushFinalBlock();
return Convert.ToBase64String(Objmst.ToArray());//encrypted string
}
catch (System.Exception ex)
{
throw ex;
}
}
private static string DesDecrypt(string cipherText, string strKey, string salt)
{
byte[] key = { };// Key
byte[] IV = { 10, 20, 30, 40, 50, 60, 70, 80 };
byte[] inputByteArray = new byte[cipherText.Length];
try
{
key = Encoding.UTF8.GetBytes(strKey);
DESCryptoServiceProvider ObjDES = new DESCryptoServiceProvider();
inputByteArray = Convert.FromBase64String(cipherText);
MemoryStream Objmst = new MemoryStream();
CryptoStream Objcs = new CryptoStream(Objmst, ObjDES.CreateDecryptor(key, IV), CryptoStreamMode.Write);
Objcs.Write(inputByteArray, 0, inputByteArray.Length);
Objcs.FlushFinalBlock();
Encoding encoding = Encoding.UTF8;
return encoding.GetString(Objmst.ToArray()).TrimEnd(salt.ToCharArray());
}
catch (System.Exception ex)
{
if (ex is FormatException) Console.WriteLine("The token is in the wrong format");
if (ex is System.Security.Cryptography.CryptographicException) Console.WriteLine("Invalid token");
throw ex;
}
}
}
Upvotes: 0
Views: 106
Reputation: 10257
Mis-match happens on des encryption, only happens when the raw text has trailing 1,2,3,4.
mhhh... i doubt that it happens in ENcryption...
a closer look at your DEcryption shows:
return encoding.GetString(Objmst.ToArray()).TrimEnd(salt.ToCharArray());
in other words:
-you get your array from the MemoryStream
-make a string out of it
-and finally remove all instances of you salt chars from the end
(which happen to be your missing chars)
Upvotes: 2