Created
April 3, 2015 00:39
-
-
Save ctigeek/bd62c6f13640b4bd16c7 to your computer and use it in GitHub Desktop.
Encrypt String
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Linq; | |
using System.Security.Cryptography; | |
using System.Text; | |
namespace SandboxThing | |
{ | |
class EncryptedString | |
{ | |
private const int AesBlockSize = 128; | |
private const int AesKeySize = 256; | |
private const CipherMode CiperMode = CipherMode.CBC; | |
private string Base64AesKey; | |
public EncryptedString(string base64Encoded256bitAesKey) | |
{ | |
Base64AesKey = base64Encoded256bitAesKey ?? "tksYWspvM78u0hs/PfUyMJ3G/3P5ditaQYw2i3iqMUI="; | |
} | |
private AesManaged GetAesManaged(byte[] IV = null) | |
{ | |
var aesManaged = new AesManaged(); | |
aesManaged.Mode = CiperMode; | |
aesManaged.Padding = PaddingMode.Zeros; | |
aesManaged.BlockSize = AesBlockSize; | |
aesManaged.KeySize = AesKeySize; | |
if (IV != null) | |
{ | |
aesManaged.IV = IV; | |
} | |
aesManaged.Key = Convert.FromBase64String(Base64AesKey); | |
return aesManaged; | |
} | |
public string GetString(string encryptedString) | |
{ | |
var bytes = Convert.FromBase64String(encryptedString); | |
var IV = bytes.Take(16).ToArray(); | |
using (var aesManaged = GetAesManaged(IV)) | |
{ | |
var decryptor = aesManaged.CreateDecryptor(); | |
var unencryptedData = decryptor.TransformFinalBlock(bytes, 16, bytes.Length - 16); | |
var unencryptedString = Encoding.UTF8.GetString(unencryptedData); | |
return unencryptedString.Trim('\0'); | |
} | |
} | |
public string SetString(string unencryptedString) | |
{ | |
var bytes = Encoding.UTF8.GetBytes(unencryptedString); | |
using (var aesManaged = GetAesManaged()) | |
{ | |
var encryptor = aesManaged.CreateEncryptor(); | |
var encryptedData = encryptor.TransformFinalBlock(bytes, 0, bytes.Length); | |
var fullData = new byte[16 + encryptedData.Length]; | |
aesManaged.IV.CopyTo(fullData, 0); | |
encryptedData.CopyTo(fullData, 16); | |
var encryptedString = Convert.ToBase64String(fullData); | |
return encryptedString; | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment