3

I want to encrypt and decrypt a string in C# using an algorithm that lead me to same encrypted string. For example if i encrypt a string 122ujhdheiwe and the result is uoi8asdf8asdf and again if i encrypt the same string 122ujhdheiwe it lead me to uoi8asdf8asdf string. What are the possible encryption algorithm that i can use and how?

Fraz Sundal
  • 10,288
  • 22
  • 81
  • 132

6 Answers6

2

You can use the ProtectedData class if you want a simple solution:

using System;
using System.Security.Cryptography;
using System.Text;

private void example()
{
    string data = "122ujhdheiwe";

    // Encrypt
    UnicodeEncoding unicodeEncoding = new UnicodeEncoding();
    byte[] secret = ProtectedData.Protect(unicodeEncoding.GetBytes(data), null, DataProtectionScope.CurrentUser);
    Console.WriteLine(BitConverter.ToString(secret));

    // If you need it as a printable string, you can convert the binary to Base64
    string base64 = Convert.ToBase64String(secret);
    Console.WriteLine(base64);

    // Back to binary...
    byte[] backagain = Convert.FromBase64String(base64);

    // Decrypt
    byte[] clearbytes = ProtectedData.Unprotect(backagain, null, DataProtectionScope.CurrentUser);
    string roundtripped = unicodeEncoding.GetString(clearbytes);
    Console.WriteLine(roundtripped);
}

cf. ProtectedDataClass

If you want the encrypted data to look pretty much like your original data, as in the example in your question (122ujhdheiwe ==> uoi8asdf8asdf), then what you are looking for is format-preserving encryption -- cf. here, for which I don't have an example.

EDIT: I just noticed that in your question you write that you want to be able to encrypt the same string again and get the same encrypted result, in which case ProtectedData won't work because the key used in the encryption will change over time.

Jim Flood
  • 8,144
  • 3
  • 36
  • 48
  • Kind of an old answer but I have to that this solution is not available in platforms other than Windows. It throws an `UnsupportedPlatformException`. – badjuice Feb 24 '22 at 11:26
1

enter image description here

I code a demo program do need source ? I am use this namespace using System.Security.Cryptography;

And two this

        public string encryptus(string x, string encrypt)//function
    {
        try
        {

            string y = x;
            byte[] etext = UTF8Encoding.UTF8.GetBytes(y);
            string Code = encrypt;
            MD5CryptoServiceProvider mdhash = new MD5CryptoServiceProvider();
            byte[] keyarray = mdhash.ComputeHash(UTF8Encoding.UTF8.GetBytes(Code));
            TripleDESCryptoServiceProvider tds = new TripleDESCryptoServiceProvider();
            tds.Key = keyarray;
            tds.Mode = CipherMode.ECB;
            tds.Padding = PaddingMode.PKCS7;

            ICryptoTransform itransform = tds.CreateEncryptor();
            byte[] result = itransform.TransformFinalBlock(etext, 0, etext.Length);
            string encryptresult = Convert.ToBase64String(result);
            return encryptresult.ToString();
        }
        catch (Exception ex)
        {
            return ex.Message;
        }
    }
        public string dencryptus(string x, string keyai)
    {
        try
        {
            string y = x.Replace("\0", null);
            byte[] etext = Convert.FromBase64String(y);
            string key = keyai;
            MD5CryptoServiceProvider mdhash = new MD5CryptoServiceProvider();
            byte[] keyarray = mdhash.ComputeHash(UTF8Encoding.UTF8.GetBytes(key));
            TripleDESCryptoServiceProvider tds = new TripleDESCryptoServiceProvider();
            tds.Key = keyarray;
            tds.Mode = CipherMode.ECB;
            tds.Padding = PaddingMode.PKCS7;

            ICryptoTransform itransform = tds.CreateDecryptor();
            byte[] result = itransform.TransformFinalBlock(etext, 0, etext.Length);
            string dencryptresult = UTF8Encoding.UTF8.GetString(result);
            return dencryptresult.ToString();
        }
        catch (Exception ex)
        {
            return ex.Message;
        }
    }

And use them like this :

Encrypted.Text = encryptus(Message.Text, EncryptCode.Text.ToString());
Decrypted.Text = dencryptus(Message.Text, EncryptCode.Text.ToString());
Tiny Hacker
  • 131
  • 1
  • 6
1

rot13 (Caesar) maybe? It shifts all characters by the offset 13. Thus, applying it twice, you will get the plain text again.

fjdumont
  • 1,517
  • 1
  • 9
  • 22
1

I have a simple solution here:

http://remy.supertext.ch/2011/01/simple-c-encryption-and-decryption/

Bascially it works like this:

DESCryptoServiceProvider des = new DESCryptoServiceProvider();
byte[] Key = { 12, 13, 14, 15, 16, 17, 18, 19 };
byte[] IV =  { 12, 13, 14, 15, 16, 17, 18, 19 };

ICryptoTransform encryptor = des.CreateEncryptor(Key, IV);

byte[] IDToBytes = ASCIIEncoding.ASCII.GetBytes(source);
byte[] encryptedID = encryptor.TransformFinalBlock(IDToBytes, 0, IDToBytes.Length);
return Convert.ToBase64String(encryptedID);

And then the other way round.

Remy
  • 12,555
  • 14
  • 64
  • 104
0

This answer is contains my ready to use Crypto Class Triple Des

.NET: what are my options for decrypting a password in my project .setting file

Just create new class library, copy/paste this code, and use it :)

Community
  • 1
  • 1
Serkan Hekimoglu
  • 4,234
  • 5
  • 40
  • 64
0

Necromancing...

I just wanted to put out a simple copy-paster for anyone that's searching for an easy encryption:

public static class AesConverter
{     
    public static string Encrypt(string clearText)
    {
        var inputBytes = Encoding.Unicode.GetBytes(clearText);
        var outputBytes = AesConvert(inputBytes, aes => aes.CreateEncryptor());
        return Convert.ToBase64String(outputBytes);
    }

    public static string Decrypt(string cipherText)
    {
        var inputBytes = Convert.FromBase64String(cipherText.Replace(" ", "+"));
        var outputBytes = AesConvert(inputBytes, aes => aes.CreateDecryptor());
        return Encoding.Unicode.GetString(outputBytes);
    }

    private static byte[] AesConvert(byte[] inputBytes, Func<Aes, ICryptoTransform> convert)
    {
        using var aes = Aes.Create();
        var key = "populateThisFromAppSettings";
        var derivedBytes = new Rfc2898DeriveBytes(key, new byte[] { 0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76 });
        aes.Key = derivedBytes.GetBytes(32);
        aes.IV = derivedBytes.GetBytes(16);
        using var ms = new MemoryStream();
        using var cs = new CryptoStream(ms, convert(aes), CryptoStreamMode.Write);
        cs.Write(inputBytes, 0, inputBytes.Length);
        cs.Close();
        return ms.ToArray();
    }
}
Ryan Naccarato
  • 674
  • 8
  • 12