0

I created the following encryption on my MSSMS 12:

CREATE MASTER KEY ENCRYPTION BY PASSWORD = 'Password123';

CREATE CERTIFICATE Certificate1
WITH SUBJECT = 'Protect Data';

CREATE SYMMETRIC KEY SymmetricKey1 
WITH ALGORITHM = AES_128 
ENCRYPTION BY CERTIFICATE Certificate1;

UPDATE Customer_data
SET Credit_card_number_encrypt = EncryptByKey (Key_GUID('SymmetricKey1'),Credit_card_number)

How do I decrypt the value coming from my database which is a public byte[] Credit_card_number_encrypt to a string?

Here is my attempted code:

private string DecryptString(byte[] inputString)
{
    MemoryStream memStream = null;
    try
    {
        byte[] key = { };
        byte[] IV = { 12, 21, 43, 17, 57, 35, 67, 27 };
        string encryptKey = "Password123"; // MUST be 8 characters
        key = Encoding.UTF8.GetBytes(encryptKey);
        byte[] byteInput = new byte[inputString.Length];
        byteInput = Convert.FromBase64String(inputString);
        DESCryptoServiceProvider provider = new DESCryptoServiceProvider();
        memStream = new MemoryStream();
        ICryptoTransform transform = provider.CreateDecryptor(key, IV);
        CryptoStream cryptoStream = new CryptoStream(memStream, transform, CryptoStreamMode.Write);
        cryptoStream.Write(byteInput, 0, byteInput.Length);
        cryptoStream.FlushFinalBlock();
        Encoding encoding1 = Encoding.UTF8;
        return encoding1.GetString(memStream.ToArray());
    }
    catch (Exception ex)
    {
        Console.Write(ex.Message);
        return "";
    }
}

The problem is the Convert.FromBase64String(inputString) can't convert the data type byte[] to string. How do I do this?

Camilo Terevinto
  • 31,141
  • 6
  • 88
  • 120
Odie
  • 375
  • 4
  • 16
  • 1
    Why is inputString a byte array and not, as the name suggests, a string? Is it a byte array representing a base64 string, or is it just raw unencoded data? – ProgrammingLlama Jun 25 '18 at 13:06
  • Yes it is a base64 string. The data in the database is already encrypted – Odie Jun 25 '18 at 13:24
  • 1
    Possible duplicate of [C# Convert a Base64 -> byte\[\]](https://stackoverflow.com/questions/6733845/c-sharp-convert-a-base64-byte) – ProgrammingLlama Jun 25 '18 at 13:30
  • The answer by Yahia on the duplicate should solve your problem. For what it's worth, you shouldn't be base64 encoding a `byte[]` array, and then storing _that_ as binary data in your database. You should store the original `byte[]` array _before_ it was encoded as binary in your database. Otherwise, what's the point of base64 encoding it - you're gaining nothing by it except making your data take up more disk space. The whole reason for base64 is to encode any binary data in a simple alphanumeric (and +, /, =) format so that it can be transmitted as a string. – ProgrammingLlama Jun 25 '18 at 13:32

0 Answers0