public byte[] Encription(string message, byte[] bobPubKeyBlob) { byte[] rawData = Encoding.UTF8.GetBytes(message); byte[] encryptedData = null; using (var aliceAlgorithm = new ECDiffieHellmanCng(privKey)) using (CngKey bobPubKey = CngKey.Import(bobPubKeyBlob, CngKeyBlobFormat.EccPublicBlob)) { byte[] symmKey = aliceAlgorithm.DeriveKeyMaterial(bobPubKey); using (var aes = new AesCryptoServiceProvider()) { aes.Key = symmKey; aes.GenerateIV(); using (ICryptoTransform encryptor = aes.CreateEncryptor()) using (MemoryStream ms = new MemoryStream()) { // create CryptoStream and encrypt data to send var cs = new CryptoStream(ms, encryptor, CryptoStreamMode.Write); // write initialization vector not encrypted ms.Write(aes.IV, 0, aes.IV.Length); cs.Write(rawData, 0, rawData.Length); cs.Close(); encryptedData = ms.ToArray(); } aes.Clear(); } } return encryptedData; }
protected void Application_Start() { //HibernatingRhinos.Profiler.Appender.EntityFramework.EntityFrameworkProfiler.Initialize(); log4net.Config.XmlConfigurator.ConfigureAndWatch(new FileInfo(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "log4net.config"))); GlobalConfig.Log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); AreaRegistration.RegisterAllAreas(); WebApiConfig.Register(GlobalConfiguration.Configuration); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); RouteConfig.RegisterRoutes(RouteTable.Routes); BundleConfig.RegisterBundles(BundleTable.Bundles); AuthConfig.RegisterAuth(); var container = new Container(); SimpleInjectorInitializer.InitializeInjector(container); DependencyResolver.SetResolver(new SimpleInjectorDependencyResolver(container)); GlobalConfig.ConnectionString = System.Web.Configuration.WebConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString; GlobalConfig.GadgetTypes = new System.Collections.Concurrent.ConcurrentDictionary<string, Type>(); LoadGadgets(); var aesCsp = new AesCryptoServiceProvider(); aesCsp.GenerateKey(); aesCsp.GenerateIV(); GlobalConfig.Encryptor = new SimpleAES(aesCsp.Key, aesCsp.IV); }
/// <summary> /// Generates a unique encryption vector /// </summary> /// <returns>byte[] vector value</returns> static public byte[] GenerateEncryptionVector() { //Generate a Vector var aesProvider = new AesCryptoServiceProvider(); aesProvider.GenerateIV(); return aesProvider.IV; }
private void OnGenerate(object sender, EventArgs e) { // Create the AES provider. using (AesCryptoServiceProvider aesProvider = new AesCryptoServiceProvider()) { // Generate the IV. aesProvider.GenerateIV(); // Generate the key. aesProvider.GenerateKey(); StringBuilder builder = new StringBuilder(); foreach (byte b in aesProvider.IV) { builder.AppendFormat("0x{0:X2}, ", b); } this.textBoxIv.Text = builder.ToString(); builder.Clear(); foreach(byte b in aesProvider.Key) { builder.AppendFormat("0x{0:X2}, ", b); } this.textBoxKey.Text = builder.ToString(); } }
public void Encrypt(string filename) { FileStream fsInput = new FileStream(filename, FileMode.Open, FileAccess.Read); FileStream fsOutput = new FileStream(filename + ".crypt", FileMode.Create, FileAccess.Write); AesCryptoServiceProvider Aes = new AesCryptoServiceProvider(); Aes.KeySize = 128; Aes.GenerateIV(); Aes.GenerateKey(); byte[] output = _algorithm_asym.Encrypt(Aes.Key, false); fsOutput.Write(output, 0, 256); output = _algorithm_asym.Encrypt(Aes.IV, false); fsOutput.Write(output, 0, 256); ICryptoTransform encrypt = Aes.CreateEncryptor(); CryptoStream cryptostream = new CryptoStream(fsOutput, encrypt, CryptoStreamMode.Write); byte[] bytearrayinput = new byte[fsInput.Length - 1]; fsInput.Read(bytearrayinput, 0, bytearrayinput.Length); cryptostream.Write(bytearrayinput, 0, bytearrayinput.Length); fsInput.Close(); fsOutput.Close(); }
private static byte[] AliceSendData(string msg) { Console.WriteLine(string.Format("Alice Send Msg: {0}", msg)); byte[] rawdata = Encoding.UTF8.GetBytes(msg); byte[] encryptedData = null; using (var aliceAlgorithm = new ECDiffieHellmanCng(aliceKey)) using (CngKey bobPubKey = CngKey.Import(bobPubKeyBlob, CngKeyBlobFormat.EccPublicBlob)) { byte[] symmkey = aliceAlgorithm.DeriveKeyMaterial(bobPubKey); Console.WriteLine(string.Format("Alice Create this symmtric key with {0}", Convert.ToBase64String(symmkey))); var aes = new AesCryptoServiceProvider(); aes.Key = symmkey; aes.GenerateIV(); using (ICryptoTransform encryptor = aes.CreateEncryptor()) using (MemoryStream ms = new MemoryStream()) { var cs = new CryptoStream(ms, encryptor, CryptoStreamMode.Write); ms.Write(aes.IV, 0, aes.IV.Length); cs.Write(rawdata, 0, rawdata.Length); cs.Close(); encryptedData = ms.ToArray(); } aes.Clear(); } Console.WriteLine(Convert.ToBase64String(encryptedData)); return encryptedData; }
public static byte[] Encrypt(byte[] input, byte[] key) { if (key == null || key.Length == 0) throw new Exception("Key can not be empty."); using (var md5 = new MD5CryptoServiceProvider()) { key = md5.ComputeHash(key); } byte[] data = input, encdata = new byte[0]; try { using (var ms = new MemoryStream()) { using (var aesProvider = new AesCryptoServiceProvider() { Key = key }) { aesProvider.GenerateIV(); using (var cs = new CryptoStream(ms, aesProvider.CreateEncryptor(), CryptoStreamMode.Write)) { ms.Write(aesProvider.IV, 0, aesProvider.IV.Length); // write first 16 bytes IV, followed by encrypted message cs.Write(data, 0, data.Length); } } encdata = ms.ToArray(); } } catch { } return encdata; }
private async static Task<byte[]> AliceSendsData(string message) { Console.WriteLine("Alice send message {0}", message); byte[] rawData = Encoding.UTF8.GetBytes(message); byte[] encryptedData = null; using(var aliceAlgo = new ECDiffieHellmanCng(aliceKey)) { using(CngKey bobPubKey = CngKey.Import(bobPubKeyBlob, CngKeyBlobFormat.GenericPublicBlob)) { byte[] symmKey = aliceAlgo.DeriveKeyMaterial(bobPubKey); Console.WriteLine("Alice create this symm key with Bobs public key information : {0}", Convert.ToBase64String(symmKey)); using(var aes = new AesCryptoServiceProvider()) { aes.Key = symmKey; aes.GenerateIV(); using(ICryptoTransform encryptor = aes.CreateEncryptor()) { using(MemoryStream ms = new MemoryStream()) { var cs = new CryptoStream(ms, encryptor,CryptoStreamMode.Write); await ms.WriteAsync(aes.IV, 0, aes.IV.Length); cs.Write(rawData, 0, rawData.Length); cs.Close(); encryptedData = ms.ToArray(); } } aes.Clear(); } } } Console.WriteLine("Alice message is encrypted : {0}", Convert.ToBase64String(encryptedData)); return encryptedData; }
protected override string EncryptByBlocks(byte[] key, List<byte> plainText) { var cipherText = new StringBuilder(); if (plainText.Count % BlockSize == 0) { AddDummyBlock(plainText); } using (var aes = new AesCryptoServiceProvider()) { aes.BlockSize = BlockSize * 8; aes.KeySize = KeySize * 8; aes.Padding = PaddingMode.None; aes.Key = key; aes.GenerateIV(); cipherText.Append(BytesToHexString(aes.IV)); using (var encr = aes.CreateEncryptor()) { while (plainText.Count != 0) { var block = DetachBlock(plainText); if (block.Length < BlockSize) { block = CompleteBlock(block); } var encrypted = new byte[BlockSize]; encr.TransformBlock(block, 0, BlockSize, encrypted, 0); cipherText.Append(BytesToHexString(encrypted)); aes.IV = encrypted; } } } return cipherText.ToString(); }
/// <summary> /// AES Encryption /// </summary> public static string Encrypt(string clearText) { if (clearText == null) return null; // AesCryptoServiceProvider AesCryptoServiceProvider aes = new AesCryptoServiceProvider(); aes.BlockSize = 128; aes.KeySize = 128; aes.GenerateIV(); aes.Key = Encoding.UTF8.GetBytes(AesKey); aes.Mode = CipherMode.CBC; aes.Padding = PaddingMode.PKCS7; // Convert string to byte array byte[] src = Encoding.Unicode.GetBytes(clearText); // encryption using (ICryptoTransform encrypt = aes.CreateEncryptor()) { byte[] dest = encrypt.TransformFinalBlock(src, 0, src.Length); // Convert byte array to Base64 strings return Convert.ToBase64String(aes.IV) + Convert.ToBase64String(dest); } }
public static AesCryptoServiceProvider generateAESKey() { AesCryptoServiceProvider aes = new AesCryptoServiceProvider(); aes.KeySize = 256; aes.GenerateKey(); aes.GenerateIV(); return aes; }
// Create an object of type IV from a given object of type Key. // Usage of AesCryptoServiceProvider: // - create it // - set its key size according the the size of the input Key // - use GenerateIV() public static IV createRandomIV(Key key) { using (var aes = new AesCryptoServiceProvider()) { aes.KeySize = key.Format.BitSize.signed(); // this should not be required? // aes.Key = key.Data; aes.GenerateIV(); return new IV(aes.IV); } }
/// <summary> /// Encrypt data with AES algorithm /// </summary> /// <param name="data"></param> /// <param name="key"></param> /// <param name="iv"></param> /// <returns></returns> public static byte[] AesEncrypt(byte[] data, out byte[] key, out byte[] iv) { if (data == null) throw new ArgumentNullException("No data to encrypt."); using (AesCryptoServiceProvider provider = new AesCryptoServiceProvider()) { provider.GenerateKey(); provider.GenerateIV(); key = provider.Key; iv = provider.IV; return provider.CreateEncryptor().TransformFinalBlock(data, 0, data.Length); } }
private static AesCryptoServiceProvider getProvider(byte[] keyPhrase) { AesCryptoServiceProvider result = new AesCryptoServiceProvider(); result.BlockSize = 128; result.KeySize = 128; result.Mode = CipherMode.CBC; result.Padding = PaddingMode.PKCS7; result.GenerateIV(); result.IV = new byte[] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; byte[] key = getKey(keyPhrase, result); result.Key = key; // result.IV = RealKey; return result; }
public static byte[] Encrypt(byte[] input, byte[] password, ushort saltSize, int iterations) { var salt = CreateSalt(saltSize); using (var aes = new AesCryptoServiceProvider()) { aes.BlockSize = 128; aes.KeySize = 256; using (var key = new Rfc2898DeriveBytes(password, salt, iterations)) { aes.Key = key.GetBytes(16); aes.Mode = CipherMode.CBC; aes.Padding = PaddingMode.PKCS7; aes.GenerateIV(); using (var memStream = new MemoryStream()) { //While a byte would suffice, //we'll take the sure-thing and just use a ushort instead, this allows a key-length of 65535 tokens. var bytes = new byte[sizeof(ushort)]; fixed (void* b = bytes) *((ushort*)b) = saltSize; memStream.Write(bytes, 0, bytes.Length); fixed (void* b = bytes) *((ushort*)b) = (ushort)aes.IV.Length; memStream.Write(bytes, 0, bytes.Length); memStream.Write(salt, 0, salt.Length); memStream.Write(aes.IV, 0, aes.IV.Length); using (var encryptor = aes.CreateEncryptor()) using (var cryptoStream = new CryptoStream(memStream, encryptor, CryptoStreamMode.Write)) { cryptoStream.Write(input, 0, input.Length); cryptoStream.FlushFinalBlock(); var encrypted = memStream.ToArray(); return encrypted; } } } } }
public static EncryptionResult AesEncrypt(byte[] data, byte[] key) { EncryptionResult result; using(var crypto = new AesCryptoServiceProvider {Key = key}) { crypto.GenerateIV(); result.IV = crypto.IV; var encryptor = crypto.CreateEncryptor(); using (var stream = new MemoryStream()) using (var cryptoStream = new CryptoStream(stream, encryptor, CryptoStreamMode.Write)) { cryptoStream.Write(data); cryptoStream.FlushFinalBlock(); result.EncryptedData = stream.ToArray(); } } return result; }
public TestSymmetricKeyProvider() { byte[] key; byte[] iv; using (var provider = new AesCryptoServiceProvider()) { provider.GenerateIV(); provider.GenerateKey(); key = provider.Key; iv = provider.IV; provider.Clear(); } _key = new TestSymmetricKey(key, iv); }
static void Main() { AesCryptoServiceProvider aes = new AesCryptoServiceProvider(); aes.GenerateKey(); aes.GenerateIV(); //Tworzenie CryptoTransform ICryptoTransform En = aes.CreateEncryptor(); ICryptoTransform De = aes.CreateDecryptor(); //Tworzenie potrzebnych zmiennych byte[] before = Encoding.UTF8.GetBytes("AES"); byte[] after; byte[] end = new byte[1024]; string result; //szyfrowanie using (MemoryStream mem = new MemoryStream()) { using (CryptoStream crypt = new CryptoStream(mem, En, CryptoStreamMode.Write)) { crypt.Write(before, 0, before.Length); } after = mem.ToArray(); } //deszyfracja using (MemoryStream mem = new MemoryStream(after)) { int i; using (CryptoStream crypt = new CryptoStream(mem, De, CryptoStreamMode.Read)) { i = crypt.Read(end, 0, end.Length); } result = Encoding.UTF8.GetString(end, 0, i); } //wypisanie na ekran informacji. Console.WriteLine("Wiadomość: {0}", Encoding.UTF8.GetString(before)); Console.WriteLine("Zaszyfrowana wiadomość: {0}", Encoding.UTF8.GetString(after)); Console.WriteLine("Odszyfrowana wiadomość: {0}", result); Console.ReadKey(); }
public byte[] EncryptToken(AuthenticationToken authenticationToken) { byte[] tokenBytes = authenticationToken.Serialize(); var symmetricAlgorithm = new AesCryptoServiceProvider { Key = Convert.FromBase64String(authenticationKey) }; symmetricAlgorithm.GenerateIV(); var transform = symmetricAlgorithm.CreateEncryptor(); using (var stream = new MemoryStream()) { var writer = new BinaryWriter(stream); writer.Write(symmetricAlgorithm.IV.Length); writer.Write(symmetricAlgorithm.IV); using (var cryptoStream = new CryptoStream(stream, transform, CryptoStreamMode.Write)) { cryptoStream.Write(tokenBytes, 0, tokenBytes.Length); } return stream.ToArray(); } }
public string Encrypt(string plainText, string password) { if (plainText == null) { throw new ArgumentNullException("plainText"); } if (string.IsNullOrEmpty(password)) { throw new ArgumentNullException("password"); } // create instance of the AES crypto provider var aes = new AesCryptoServiceProvider(); // generate a random IV will be used a salt value for generating key aes.GenerateIV(); // use derive bytes to generate a key from the password and IV var rfc2898DeriveBytes = new Rfc2898DeriveBytes(password, aes.IV, Iterations); // generate a key from the password provided byte[] key = rfc2898DeriveBytes.GetBytes(16); // encrypt the plainText using (var memoryStream = new MemoryStream()) using (var cryptoStream = new CryptoStream(memoryStream, aes.CreateEncryptor(key, aes.IV), CryptoStreamMode.Write)) { // write the salt first not encrypted memoryStream.Write(aes.IV, 0, aes.IV.Length); // convert the plain text string into a byte array byte[] bytes = Encoding.UTF8.GetBytes(plainText); // write the bytes into the crypto stream so that they are encrypted bytes cryptoStream.Write(bytes, 0, bytes.Length); cryptoStream.FlushFinalBlock(); return Convert.ToBase64String(memoryStream.ToArray()); } }
public static byte[] Encrypt(string publicKey, byte[] data) { using (var aes = new AesCryptoServiceProvider()) { aes.GenerateKey(); aes.GenerateIV(); using (var encryptor = aes.CreateEncryptor()) using (var ms = new MemoryStream()) { ms.Write(Rsa.Encrypt(publicKey, aes.IV), 0, 128); ms.Write(Rsa.Encrypt(publicKey, aes.Key), 0, 128); using (var cs = new CryptoStream(ms, encryptor, CryptoStreamMode.Write)) { cs.Write(data, 0, data.Length); } return ms.ToArray(); } } }
public static byte[] Encrypt(string publicKey, byte[] data) { using (var aes = new AesCryptoServiceProvider()) { aes.GenerateKey(); aes.GenerateIV(); using (var encryptor = aes.CreateEncryptor()) using (var ms = new MemoryStream()) { ms.Write(Rsa.Encrypt(publicKey, aes.IV), 0, 128); ms.Write(Rsa.Encrypt(publicKey, aes.Key), 0, 128); using (var cs = new CryptoStream(ms, encryptor, CryptoStreamMode.Write)) { cs.Write(data, 0, data.Length); } return(ms.ToArray()); } } }
public string DecryptFile(byte[] data) { AesCryptoServiceProvider aes = new AesCryptoServiceProvider(); aes.GenerateIV(); byte[] iv = aes.IV; aes.GenerateKey(); byte[] key = aes.Key; ICryptoTransform cryptoTransform = aes.CreateEncryptor(); MemoryStream memoryStream = new MemoryStream(); CryptoStream cryptoStream = new CryptoStream(memoryStream, cryptoTransform, CryptoStreamMode.Write); StreamWriter streamWriter = new StreamWriter(cryptoStream); memoryStream = new MemoryStream(data); cryptoStream = new CryptoStream(memoryStream, aes.CreateDecryptor(), CryptoStreamMode.Read); StreamReader streamReader = new StreamReader(cryptoStream); string decryptText = streamReader.ReadToEnd(); streamWriter.Dispose(); cryptoStream.Dispose(); memoryStream.Dispose(); return decryptText; }
private async Task<byte[]> AliceSendsDataAsync(string message) { WriteLine($"Alice sends message: {message}"); byte[] rawData = Encoding.UTF8.GetBytes(message); byte[] encryptedData = null; using (var aliceAlgorithm = new ECDiffieHellmanCng(_aliceKey)) using (CngKey bobPubKey = CngKey.Import(_bobPubKeyBlob, CngKeyBlobFormat.EccPublicBlob)) { byte[] symmKey = aliceAlgorithm.DeriveKeyMaterial(bobPubKey); WriteLine("Alice creates this symmetric key with " + $"Bobs public key information: { Convert.ToBase64String(symmKey)}"); using (var aes = new AesCryptoServiceProvider()) { aes.Key = symmKey; aes.GenerateIV(); using (ICryptoTransform encryptor = aes.CreateEncryptor()) using (var ms = new MemoryStream()) { // create CryptoStream and encrypt data to send using (var cs = new CryptoStream(ms, encryptor, CryptoStreamMode.Write)) { // write initialization vector not encrypted await ms.WriteAsync(aes.IV, 0, aes.IV.Length); await cs.WriteAsync(rawData, 0, rawData.Length); } encryptedData = ms.ToArray(); } aes.Clear(); } } WriteLine($"Alice: message is encrypted: {Convert.ToBase64String(encryptedData)}"); ; WriteLine(); return encryptedData; }
private void initialize(string password,byte[] salt, byte[] iv) { AesCryptoServiceProvider csp=new AesCryptoServiceProvider(); csp.Mode = CipherMode.CBC; csp.Padding = PaddingMode.PKCS7; var spec = new Rfc2898DeriveBytes(Encoding.UTF8.GetBytes(password), salt, 65536); byte[] key = spec.GetBytes(16); csp.Key = key; if (iv == null) //enc { csp.GenerateIV(); this.IV = csp.IV; ict = csp.CreateEncryptor(); } else { csp.IV = iv; ict = csp.CreateDecryptor(); this.IV = iv; } }
public TestSymmetricKeyProvider(params string[] ids) { _keys = new Dictionary<string, TestSymmetricKey>(); foreach (var id in ids.Concat(new[] {"default"}).Distinct()) { byte[] key; byte[] iv; using (var provider = new AesCryptoServiceProvider()) { provider.GenerateIV(); provider.GenerateKey(); key = provider.Key; iv = provider.IV; provider.Clear(); } _keys.Add(id, new TestSymmetricKey(key, iv)); } }
/// <summary> /// データを暗号化し、ファイルに出力します。 /// </summary> /// <param name="ms">暗号化したいメモリストリーム</param> /// <param name="outfilepath">出力ファイルの名前</param> public static void EncryptionData(MemoryStream ms, string outfilepath) { //AesCryptoServiceProviderオブジェクトの作成 using (AesCryptoServiceProvider aes = new AesCryptoServiceProvider()) { aes.BlockSize = 128; //ブロックサイズ(128bit) aes.KeySize = 128; //キー最大長(128bit) aes.Mode = CipherMode.CBC; //CBCモード aes.Padding = PaddingMode.PKCS7; //パディングモード aes.GenerateIV(); byte[] bytesIV = aes.IV; //初期化ベクトルの設定と取得(ブロックサイズと同サイズ=128bit) aes.Key = AESTransformBytes(PASSWORD); //キーの設定 ICryptoTransform encrypt = aes.CreateEncryptor(); //AES暗号化オブジェクトの作成 //FileStreamの生成 using (System.IO.FileStream outfs = new System.IO.FileStream(outfilepath, System.IO.FileMode.Create, System.IO.FileAccess.Write)) { outfs.Write(bytesIV, 0, 16); //IVを先頭に書き込む(128bit=16bytes) //CryptoStreamの作成 using (CryptoStream cs = new CryptoStream( outfs, encrypt, CryptoStreamMode.Write)) { //暗号化データを書き出していく byte[] buffer = new byte[4096];//[2048];//byte[1024] int length; while ((length = ms.Read(buffer, 0, buffer.Length)) > 0) { cs.Write(buffer, 0, length);// bufferは87くらいまでしか使われてない } } } } }
public byte[] EncryptFile(string text) { AesCryptoServiceProvider aes = new AesCryptoServiceProvider(); aes.GenerateIV(); byte[] iv = aes.IV; aes.GenerateKey(); byte[] key = aes.Key; ICryptoTransform cryptoTransform = aes.CreateEncryptor(); MemoryStream memoryStream = new MemoryStream(); CryptoStream cryptoStream = new CryptoStream(memoryStream, cryptoTransform, CryptoStreamMode.Write); StreamWriter streamWriter = new StreamWriter(cryptoStream); streamWriter.Write(text); byte[] enryptText = memoryStream.ToArray(); streamWriter.Dispose(); cryptoStream.Dispose(); memoryStream.Dispose(); return enryptText; }
/// <summary> /// Encrypts string to an array of bytes using an AesCryptoServiceProvider. /// </summary> /// <param name="plainText">Input value to be necrypted.</param> /// <param name="Key">Key used in the encryption process.</param> /// <returns>An ecnrypted byte array.</returns> public static byte[] EncryptStringToBytes_Aes(string plainText, byte[] Key) { // Check arguments. if (string.IsNullOrWhiteSpace(plainText)) { throw new ArgumentNullException("plainText"); } if (Key == null || Key.Length <= 0) { throw new ArgumentNullException("Key"); } // Byte array used to store the encrypted data. byte[] encrypted; // Create an AesCryptoServiceProvider object with the specified key and // a random IV. using (var aesAlg = new AesCryptoServiceProvider()) { aesAlg.Key = Key; aesAlg.GenerateIV(); // Create a decrytor to perform the stream transform. using (var encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV)) { // Create the streams used for encryption. using (var msEncrypt = new MemoryStream()) { // Write out IV. msEncrypt.Write(aesAlg.IV, 0, 16); using (var csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write)) { using (var swEncrypt = new StreamWriter(csEncrypt)) { //Write all data to the stream. swEncrypt.Write(plainText); } encrypted = msEncrypt.ToArray(); } } } } return encrypted; }
public static byte[] getInitializationVector() { AesCryptoServiceProvider myAes = new AesCryptoServiceProvider(); myAes.GenerateIV(); return myAes.IV; }
public ResponseModel Provision(CompanyModel companyModel, string UserName, string PlatformCode, Command Command, string Email) { //Generate IV AesCryptoServiceProvider cryptoProvider = new AesCryptoServiceProvider(); cryptoProvider.KeySize = 256; cryptoProvider.GenerateIV(); string IV = Convert.ToBase64String(cryptoProvider.IV); //Encrypt Model byte[] data = Encoding.UTF8.GetBytes(Newtonsoft.Json.JsonConvert.SerializeObject(companyModel)); byte[] key = Convert.FromBase64String(provisionerKey); string hash = Convert.ToBase64String(new HMACSHA512(key).ComputeHash(data)); string data2 = Encrypt(key, Convert.FromBase64String(IV), Newtonsoft.Json.JsonConvert.SerializeObject(companyModel)); //Construct the request model RequestModel requestModel = new RequestModel { UserName = UserName, PlatformCode = PlatformCode, Command = Command, IV = IV, Data = data2, Hash = hash }; var req = new WebClient(); req.BaseAddress = "https://provisioning.datamotion.com:8888"; req.Headers.Clear(); req.Headers.Add("Accept", "application/json"); req.Headers.Add(Headers.Email, Email); req.Headers.Add(Headers.Iv, IV); try { var request = req.UploadData("https://provisioning.datamotion.com:8888", Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(requestModel))); ResponseModel response = JsonConvert.DeserializeObject<ResponseModel>(Encoding.UTF8.GetString(request)); response.Data = Decrypt(key, Convert.FromBase64String(response.IV), response.Data); return response; } catch (Exception ex) { throw new Exception(ex.Message); } }