public static byte[] Encrypt(byte[] input) { if (_key == null || _key.Length == 0) throw new Exception("Key can not be empty."); if (input == null || input.Length == 0) throw new ArgumentException("Input can not be empty."); byte[] data = input, encdata = new byte[0]; try { using (var ms = new MemoryStream()) { using (var rd = new AesManaged { Key = _key }) { rd.GenerateIV(); using (var cs = new CryptoStream(ms, rd.CreateEncryptor(), CryptoStreamMode.Write)) { ms.Write(rd.IV, 0, rd.IV.Length); // write first 16 bytes IV, followed by encrypted message cs.Write(data, 0, data.Length); } } encdata = ms.ToArray(); } } catch { } return encdata; }
/// <summary> /// <see cref="IAesManagedWrapper.Encrypt"/> /// </summary> public byte[] Encrypt(byte[] bytesToBeEncrypted, byte[] aesKey, out byte[] aesIv) { byte[] encryptedBytes; using (var ms = new MemoryStream()) { using (var aes = new AesManaged()) { SetStandardConfiguration(aes); aes.Key = aesKey; aes.GenerateIV(); aesIv = aes.IV; using (var cs = new CryptoStream(ms, aes.CreateEncryptor(), CryptoStreamMode.Write)) { cs.Write(bytesToBeEncrypted, 0, bytesToBeEncrypted.Length); cs.Close(); } encryptedBytes = ms.ToArray(); } } return encryptedBytes; }
/// <summary> /// Creates a symmetric key. See this link for more information behind the numbers /// http://blogs.msdn.com/b/shawnfa/archive/2006/10/09/the-differences-between-rijndael-and-aes.aspx /// </summary> /// <returns></returns> private SymmetricKey CreateNewAESSymmetricKeyset() { if (cert == null) { throw new InvalidOperationException("Unable to create new AES keyset; Certificate not loaded."); } byte[] symmKey, iv; using (AesManaged aes = new AesManaged()) { aes.GenerateIV(); aes.GenerateKey(); symmKey = aes.Key; iv = aes.IV; aes.Clear(); } // Encrypt the Symmetric Key for storage byte[] encryptedKey = EncryptRSA(symmKey, cert); SymmetricKey symmKeySet = new SymmetricKey() { iv = iv, Key = encryptedKey, CertificateThumbprint = cert.Thumbprint }; return symmKeySet; }
public EncryptedMessage Encrypt(byte[] input) { var em = new EncryptedMessage(); using (var aes = new AesManaged()) { aes.KeySize = 256; aes.GenerateIV(); aes.GenerateKey(); em.IV = aes.IV; em.Key = aes.Key; em.EncryptionType = MessageEncryptionType.Aes; using (var encryptor = aes.CreateEncryptor()) { using (var msOutput = new MemoryStream()) { using (var cryptoStream = new CryptoStream(msOutput, encryptor, CryptoStreamMode.Write)) { using (var msInput = new MemoryStream(input)) { msInput.CopyTo(cryptoStream); } } em.CipherBytes = msOutput.ToArray(); } } return em; } }
/// <summary> /// Generates a new random Initialization vector. /// This can be used for the encryption of keys in the HOTP/TOTP classes /// </summary> /// <returns>returns a new Initialization vector</returns> public static byte[] GenerateNewAesIv() { using (AesManaged aesAlg = new AesManaged()) { aesAlg.GenerateIV(); return aesAlg.IV; } }
public static byte[] GenerateIV() { var aes = new System.Security.Cryptography.AesManaged(); aes.KeySize = 256; aes.GenerateIV(); return(aes.IV); }
public AESEncryption() { Algorithm = new AesManaged(); Algorithm.KeySize = 256; Algorithm.Mode = CipherMode.CBC; Algorithm.GenerateIV(); Algorithm.GenerateKey(); Algorithm.Padding = PaddingMode.PKCS7; }
private void GenerateEncryptionParameters(X509Certificate2 certificate) { var aesManaged = new AesManaged(); aesManaged.GenerateIV(); aesManaged.GenerateKey(); string ivToStoreInConfig = Convert.ToBase64String(aesManaged.IV); string encryptionKeyAsString = Convert.ToBase64String(aesManaged.Key); string keyToStoreInConfig = RsaEncrypt(certificate, encryptionKeyAsString); ConfigurationManager.AppSettings["EncryptionIV"] = ivToStoreInConfig; ConfigurationManager.AppSettings["EncryptionKey"] = keyToStoreInConfig; }
public SymmetricKey CreateNewAesSymmetricKeyset() { var aes = new AesManaged(); aes.GenerateIV(); aes.GenerateKey(); var symmKeySet = new SymmetricKey() { Iv = RsaEncryptBytes(aes.IV), Key = RsaEncryptBytes(aes.Key) }; return symmKeySet; }
static TokenCrypt() { try { CryptKey = JsonHelper.ParseJson<AesKey>(File.ReadAllText(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, KeyFile)).Trim()); } catch(FileNotFoundException) { using(var aes = new AesManaged()) { aes.GenerateKey(); aes.GenerateIV(); CryptKey = new AesKey { Key = aes.Key, IV = aes.IV }; File.WriteAllText(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, KeyFile), CryptKey.ToJsonString()); } } }
public static byte[] EncryptString(string text, string secret, string salt) { byte[] buffer; using (Aes aes = new AesManaged()) { aes.Key = new Rfc2898DeriveBytes(secret, Encoding.UTF8.GetBytes(salt)).GetBytes(0x10); aes.GenerateIV(); using (MemoryStream stream = new MemoryStream()) { stream.Write(BitConverter.GetBytes(aes.IV.Length), 0, 4); stream.Write(aes.IV, 0, aes.IV.Length); using (CryptoStream stream2 = new CryptoStream(stream, aes.CreateEncryptor(), CryptoStreamMode.Write)) { stream2.Write(Encoding.UTF8.GetBytes(text), 0, text.Length); stream2.FlushFinalBlock(); buffer = stream.ToArray(); } } } return buffer; }
public AESCipher() { this.utf8Encoding = new System.Text.UTF8Encoding(); this.aes = new AesManaged(); this.aes.Mode = CipherMode.CBC; this.aes.Padding = PaddingMode.PKCS7; this.aes.KeySize = 128; this.aes.BlockSize = 128; aes.GenerateKey(); aes.GenerateIV(); if (File.Exists(@"C:\Users\Chris\Documents\Cambridge\Part II Project\Code\Encryption Example\EncryptionExample\AESkey.xml") == true) File.Delete(@"C:\Users\Chris\Documents\Cambridge\Part II Project\Code\Encryption Example\EncryptionExample\AESkey.xml"); //provide AES encryption key params FileStream fs = new FileStream(@"C:\Users\Chris\Documents\Cambridge\Part II Project\Code\Encryption Example\EncryptionExample\AESkey.xml", FileMode.CreateNew, FileAccess.ReadWrite); StreamWriter sw = new StreamWriter(fs); string aesKeyXML = byte2Hex(aes.Key); sw.Write("<AESkey>"+ aesKeyXML + "</AESkey>"); sw.Close(); fs.Close(); }
/** * Encrypts a specified string using AES encryption and returns * the encrypted string and key used. */ public static string[] Encrypt(string str) { byte[] bytes = Encoding.UTF8.GetBytes(str); var manager = new AesManaged { KeySize = 256, Padding = PaddingMode.PKCS7 }; manager.GenerateKey(); manager.GenerateIV(); ICryptoTransform c = manager.CreateEncryptor(); bytes = c.TransformFinalBlock(bytes, 0, bytes.Length); string hash = BitConverter.ToString(manager.IV).Replace("-", ""); hash += BitConverter.ToString(bytes).Replace("-", ""); string key = BitConverter.ToString(manager.Key).Replace("-", ""); return new[] {hash, key}; }
public static byte[] EncryptStringToByte(string sourceText,ref byte[] key,ref byte[] IV) { if (sourceText == null || sourceText == "") { return null; } byte[] result; AesManaged aesAlg = new AesManaged(); if (key == null || key.Length <= 0 || IV == null || IV.Length <= 0) { aesAlg.GenerateKey(); aesAlg.GenerateIV(); key = aesAlg.Key; IV = aesAlg.IV; } else { aesAlg.Key = key; aesAlg.IV = IV; } ICryptoTransform encryptor = aesAlg.CreateEncryptor(); MemoryStream msEncrypt = new MemoryStream(); CryptoStream csEncrypt = new CryptoStream(msEncrypt,encryptor, CryptoStreamMode.Write); StreamWriter swEncrypt = new StreamWriter(csEncrypt); swEncrypt.Write(sourceText); swEncrypt.Close(); csEncrypt.Close(); result = msEncrypt.ToArray(); return result; }
public void RsaHelperBytesShouldSucceed() { var directory = TestContext.DeploymentDirectory; var helper = new RsaHelper(Path.Combine(directory, "TestCertificate.pfx"), CertificatePassword); var aes = new AesManaged(); aes.GenerateIV(); aes.GenerateKey(); var originalKey = aes.Key; var originalIv = aes.IV; var encryptedKeyBytes = helper.RsaEncryptBytes(aes.Key); var encryptedIvBytes = helper.RsaEncryptBytes(aes.IV); encryptedIvBytes.Should().NotBeNull("IV failed to encrypt"); encryptedKeyBytes.Should().NotBeNull("Key failed to encrypt"); var decryptedKeyBytes = helper.RsaDecryptToBytes(encryptedKeyBytes); var decryptedIvBytes = helper.RsaDecryptToBytes(encryptedIvBytes); originalKey.ShouldBeEquivalentTo(decryptedKeyBytes); originalIv.ShouldBeEquivalentTo(decryptedIvBytes); }
public SecurityHelper() { rijAlg = new AesManaged(); rijAlg.GenerateIV(); IV = rijAlg.IV; KEY = Convert.FromBase64String(EncodeTo64(key)); rijAlg.Key = KEY; //try //{ // string original = "Here is some data to encrypt!"; // // Create a new instance of the AesManaged // // class. This generates a new key and initialization // // vector (IV). // using (AesManaged myAes = new AesManaged()) // { // myAes.Key = Convert.FromBase64String(EncodeTo64(key)); // // Encrypt the string to an array of bytes. // byte[] encrypted = EncryptStringToBytes_Aes(original, myAes.Key, myAes.IV); // // Decrypt the bytes to a string. // string roundtrip = DecryptStringFromBytes_Aes(encrypted, myAes.Key, myAes.IV); // //Display the original data and the decrypted data. // Debug.WriteLine("Original: {0}", original); // Debug.WriteLine("Round Trip: {0}", roundtrip); // } //} //catch (Exception e) //{ // Debug.WriteLine("Error: {0}", e.Message); //} }
public EncryptResponse Encrypt(string password, Guid id) { // Key = Hashed (setting Guid + Salt) using (var sha256 = SHA256.Create()) { var enc = new UTF8Encoding(); var keyBytes = sha256.ComputeHash(enc.GetBytes(id + EncryptionSalt)); // Encrypt password using (var aes = new AesManaged()) { aes.GenerateIV(); aes.Key = keyBytes; var encryptor = aes.CreateEncryptor(); using (var msEncrypt = new MemoryStream()) { using ( var csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write)) { using (var swEncrypt = new StreamWriter(csEncrypt)) { swEncrypt.Write(password); } var encryptedPassword = Convert.ToBase64String(msEncrypt.ToArray()); if (encryptedPassword.IsNullOrWhiteSpace()) { throw new NullReferenceException("Password encryption failed!"); } return new EncryptResponse(encryptedPassword, Convert.ToBase64String(aes.IV)); } } } } }
public static string EncryptAssymetric(Tuple<byte[], byte[]> parameters, string data) { var bytes = Encoding.UTF8.GetBytes(data); var results = new List<byte>(); using (var aesKeyGen = new AesManaged { KeySize = 256, }) { aesKeyGen.GenerateKey(); aesKeyGen.GenerateIV(); results.AddRange(AddEncryptedKeyAndIv(parameters, aesKeyGen)); using (var encryptor = aesKeyGen.CreateEncryptor()) { var encryptedBytes = encryptor.TransformEntireBlock(bytes); results.AddRange(encryptedBytes); } } return BytesToString(results.ToArray()); }
/// <summary> /// Generates a random initialization vector (IV) to use for the symmetric algorithm. /// </summary> /// <returns>The initialization vector (IV) to use for the symmetric algorithm.</returns> public static byte[] GenerateIV() { byte[] iv; using (var aes = new AesManaged()) { aes.GenerateIV(); iv = aes.IV; } return iv; }
public static Byte[] GenFreshAESIV() { AesManaged aes = new AesManaged(); aes.GenerateIV(); return aes.IV; }
/// <summary> /// Simple Encryption(AES) then Authentication (HMAC) for a UTF8 Message. /// </summary> /// <param name="secretMessage">The secret message.</param> /// <param name="cryptKey">The crypt key.</param> /// <param name="authKey">The auth key.</param> /// <param name="nonSecretPayload">(Optional) Non-Secret Payload.</param> /// <returns> /// Encrypted Message /// </returns> /// <remarks> /// Adds overhead of (Optional-Payload + BlockSize(16) + Message-Padded-To-Blocksize + HMac-Tag(32)) * 1.33 Base64 /// </remarks> public static byte[] SimpleEncrypt(byte[] secretMessage, byte[] cryptKey, byte[] authKey, byte[] nonSecretPayload = null) { //User Error Checks if (cryptKey == null || cryptKey.Length != KeyBitSize / 8) throw new ArgumentException(String.Format("Key needs to be {0} bit!", KeyBitSize), "cryptKey"); if (authKey == null || authKey.Length != KeyBitSize / 8) throw new ArgumentException(String.Format("Key needs to be {0} bit!", KeyBitSize), "authKey"); if (secretMessage == null || secretMessage.Length < 1) throw new ArgumentException("Secret Message Required!", "secretMessage"); //non-secret payload optional nonSecretPayload = nonSecretPayload ?? new byte[] { }; byte[] cipherText; byte[] iv; using (var aes = new AesManaged { KeySize = KeyBitSize, BlockSize = BlockBitSize, Mode = CipherMode.CBC, Padding = PaddingMode.PKCS7 }) { //Use random IV aes.GenerateIV(); iv = aes.IV; using (var encrypter = aes.CreateEncryptor(cryptKey, iv)) using (var cipherStream = new MemoryStream()) { using (var cryptoStream = new CryptoStream(cipherStream, encrypter, CryptoStreamMode.Write)) using (var binaryWriter = new BinaryWriter(cryptoStream)) { //Encrypt Data binaryWriter.Write(secretMessage); } cipherText = cipherStream.ToArray(); } } //Assemble encrypted message and add authentication using (var hmac = new HMACSHA256(authKey)) using (var encryptedStream = new MemoryStream()) { using (var binaryWriter = new BinaryWriter(encryptedStream)) { //Prepend non-secret payload if any binaryWriter.Write(nonSecretPayload); //Prepend IV binaryWriter.Write(iv); //Write Ciphertext binaryWriter.Write(cipherText); binaryWriter.Flush(); //Authenticate all data var tag = hmac.ComputeHash(encryptedStream.ToArray()); //Postpend tag binaryWriter.Write(tag); } return encryptedStream.ToArray(); } }
private string Encrypt(string secretMessage, byte[] cryptKey, byte[] authKey, byte[] nonSecretPayload) { nonSecretPayload = nonSecretPayload ?? new byte[] { }; byte[] cipherText; byte[] iv; using (var aes = new AesManaged { KeySize = KEY_BIT_SIZE, BlockSize = BLOCK_BIT_SIZE, Mode = CipherMode.CBC, Padding = PaddingMode.PKCS7 }) { aes.GenerateIV(); iv = aes.IV; using (var encryptor = aes.CreateEncryptor(cryptKey, iv)) { using (var cipherStream = new MemoryStream()) { using (var cryptoStream = new CryptoStream(cipherStream, encryptor, CryptoStreamMode.Write)) { using (var binaryWriter = new BinaryWriter(cryptoStream)) { binaryWriter.Write(Encoding.UTF8.GetBytes(secretMessage)); } } cipherText = cipherStream.ToArray(); } } } using (var hmac = new HMACSHA256(authKey)) { using (var encryptedStream = new MemoryStream()) { using (var binaryWriter = new BinaryWriter(encryptedStream)) { binaryWriter.Write(nonSecretPayload); binaryWriter.Write(iv); binaryWriter.Write(cipherText); binaryWriter.Flush(); var tag = hmac.ComputeHash(encryptedStream.ToArray()); binaryWriter.Write(tag); } return Convert.ToBase64String(encryptedStream.ToArray()); } } }
internal static void GenerateKey(this Settings s, ref AesManaged AES) { AES.GenerateIV(); AES.GenerateKey(); s.Key = AES.Key; s.IV = AES.IV; s.IsFirst = false; }
/// <summary> /// 出力ストリームとパスワードを指定して、 <see cref="Encrypt.Encryptor"/> クラスの新しいインスタンスを初期化します。 /// </summary> /// <param name="outputStream">暗号化されたデータを出力するストリーム。</param> /// <param name="password">パスワード。</param> /// <remarks> /// <para> /// AESアルゴリズムを使用した暗号化を行うストリームを作成します。 /// 暗号化ストリームを作成した時に使用したソルトとIVを、出力ストリームの先頭に出力します。 /// </para> /// <para> /// パスワードが<see cref="Encrypt.EncryptSettings.KeySize"/> より短いと鍵空間が小さくなるため、 /// 指定されたパスワードをベースに擬似乱数を生成して鍵として使用します。 /// </para> /// </remarks> public Encryptor(Stream outputStream, string password) { if (outputStream == null) { throw new ArgumentNullException("outputStream"); } if (string.IsNullOrEmpty(password)) { throw new ArgumentNullException("password"); } OutputStream = outputStream; using (var aes = new AesManaged()) { var settings = EncryptSettings.Instance; aes.BlockSize = settings.BlockSize; aes.KeySize = settings.KeySize; aes.Mode = settings.Mode; aes.Padding = settings.Padding; // 指定されたパスワードをベースに擬似乱数を生成 var derivedBytes = new Rfc2898DeriveBytes(password, settings.SaltSize / 8); var salt = derivedBytes.Salt; aes.Key = derivedBytes.GetBytes(aes.KeySize / 8); // aes.KeySize は必ず8の倍数 aes.GenerateIV(); ICryptoTransform encryptor = aes.CreateEncryptor(aes.Key, aes.IV); CryptoStream = new CryptoStream(OutputStream, encryptor, CryptoStreamMode.Write); // saltとIVをファイル先頭に暗号化しないで保存する OutputStream.Write(salt, 0, salt.Length); OutputStream.Write(aes.IV, 0, aes.IV.Length); DeflateStream = new DeflateStream(CryptoStream, CompressionMode.Compress); } }
private void HandleEncryptedDeviceRequest(HttpContext context) { var request = context.Request; var response = context.Response; var authorization = request.Headers["Authorization"]; var authTokens = authorization.Split(':'); IContainerOwner owner = null; if (request.Path.StartsWith("/auth/grp/")) { string groupID = GetGroupID(context.Request.Path); owner = new VirtualOwner("grp", groupID); } else throw new NotSupportedException("Account device requests not yet supported"); string ivStr = authTokens[1]; string trustID = authTokens[2]; string contentName = authTokens[3]; DeviceMembership deviceMembership = DeviceMembership.RetrieveFromOwnerContent(owner, trustID); if(deviceMembership == null) throw new InvalidDataException("Device membership not found"); if(deviceMembership.IsValidatedAndActive == false) throw new SecurityException("Device membership not valid and active"); InformationContext.Current.Owner = owner; InformationContext.Current.ExecutingForDevice = deviceMembership; if (request.RequestType == "GET") { string contentPath = request.Path.Substring(AuthGroupPrefixLen + GuidIDLen + 1); if(contentPath.Contains("TheBall.CORE")) throw new SecurityException("Invalid request location"); var blob = StorageSupport.GetOwnerBlobReference(owner, contentPath); AesManaged aes = new AesManaged(); aes.KeySize = SymmetricSupport.AES_KEYSIZE; aes.BlockSize = SymmetricSupport.AES_BLOCKSIZE; aes.GenerateIV(); aes.Key = deviceMembership.ActiveSymmetricAESKey; aes.Padding = SymmetricSupport.PADDING_MODE; aes.Mode = SymmetricSupport.AES_MODE; aes.FeedbackSize = SymmetricSupport.AES_FEEDBACK_SIZE; var ivBase64 = Convert.ToBase64String(aes.IV); response.Headers.Add("IV", ivBase64); var responseStream = response.OutputStream; var encryptor = aes.CreateEncryptor(aes.Key, aes.IV); var cryptoStream = new CryptoStream(responseStream, encryptor, CryptoStreamMode.Write); blob.DownloadToStream(cryptoStream); cryptoStream.Close(); } else if (request.RequestType == "POST") { if (contentName.StartsWith(DeviceSupport.OperationPrefixStr)) { string operationName = contentName.Substring(DeviceSupport.OperationPrefixStr.Length); var reqStream = request.GetBufferedInputStream(); AesManaged decAES = new AesManaged { KeySize = SymmetricSupport.AES_KEYSIZE, BlockSize = SymmetricSupport.AES_BLOCKSIZE, IV = Convert.FromBase64String(ivStr), Key = deviceMembership.ActiveSymmetricAESKey, Padding = SymmetricSupport.PADDING_MODE, Mode = SymmetricSupport.AES_MODE, FeedbackSize = SymmetricSupport.AES_FEEDBACK_SIZE }; var reqDecryptor = decAES.CreateDecryptor(decAES.Key, decAES.IV); AesManaged encAES = new AesManaged { KeySize = SymmetricSupport.AES_KEYSIZE, BlockSize = SymmetricSupport.AES_BLOCKSIZE, Key = deviceMembership.ActiveSymmetricAESKey, Padding = SymmetricSupport.PADDING_MODE, Mode = SymmetricSupport.AES_MODE, FeedbackSize = SymmetricSupport.AES_FEEDBACK_SIZE }; encAES.GenerateIV(); var respivBase64 = Convert.ToBase64String(encAES.IV); response.Headers.Add("IV", respivBase64); var responseStream = response.OutputStream; var respEncryptor = encAES.CreateEncryptor(encAES.Key, encAES.IV); using (CryptoStream reqDecryptStream = new CryptoStream(reqStream, reqDecryptor, CryptoStreamMode.Read), respEncryptedStream = new CryptoStream(responseStream, respEncryptor, CryptoStreamMode.Write)) { OperationSupport.ExecuteOperation(operationName, new Tuple<string, object>("InputStream", reqDecryptStream), new Tuple<string, object>("OutputStream", respEncryptedStream)); } } else { string contentRoot = deviceMembership.RelativeLocation + "_Input"; string blobName = contentRoot + "/" + contentName; var blob = StorageSupport.GetOwnerBlobReference(owner, blobName); if (blob.Name != blobName) throw new InvalidDataException("Invalid content name"); var reqStream = request.GetBufferedInputStream(); AesManaged aes = new AesManaged(); aes.KeySize = SymmetricSupport.AES_KEYSIZE; aes.BlockSize = SymmetricSupport.AES_BLOCKSIZE; aes.IV = Convert.FromBase64String(ivStr); aes.Key = deviceMembership.ActiveSymmetricAESKey; aes.Padding = SymmetricSupport.PADDING_MODE; aes.Mode = SymmetricSupport.AES_MODE; aes.FeedbackSize = SymmetricSupport.AES_FEEDBACK_SIZE; var decryptor = aes.CreateDecryptor(aes.Key, aes.IV); CryptoStream cryptoStream = new CryptoStream(reqStream, decryptor, CryptoStreamMode.Read); blob.UploadFromStream(cryptoStream); } response.StatusCode = 200; response.End(); } else throw new NotSupportedException("Device request type not supported: " + request.RequestType); }
private void EncryptToFile(string data, string filepath) { // Gets the bytes from the string. byte[] binData = Encoding.UTF8.GetBytes(data); // AES encryption of the source file. byte[] aesKey, aesIv; byte[] aesEncData; using (AesManaged aes = new AesManaged()) { // Generates a random AES key and IV. aes.GenerateKey(); aes.GenerateIV(); aesKey = aes.Key; aesIv = aes.IV; // Encrypts the data. ICryptoTransform ct = aes.CreateEncryptor(); using (MemoryStream ms = new MemoryStream()) { using (CryptoStream cs = new CryptoStream(ms, ct, CryptoStreamMode.Write)) { using (BinaryWriter bw = new BinaryWriter(cs)) { bw.Write(binData); } } aesEncData = ms.ToArray(); } } // Loads the RSA public key. RSAParameters rsaPublicKey = LoadRSAPublicKey(); // RSA encryption of the AES key+iv. byte[] rsaEncAesKey, rsaEncAesIv; using (RSACryptoServiceProvider rsa = new RSACryptoServiceProvider()) { // Imports the key. rsa.ImportParameters(rsaPublicKey); // Performs encryption. rsaEncAesKey = rsa.Encrypt(aesKey, false); rsaEncAesIv = rsa.Encrypt(aesIv, false); } // Writes the encrypted data. using (IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForApplication()) { using (IsolatedStorageFileStream fs = isf.OpenFile(filepath, FileMode.Create)) { using (BinaryWriter bw = new BinaryWriter(fs)) { // Key length + data. bw.Write(rsaEncAesKey.Length); bw.Write(rsaEncAesKey); // IV length + data. bw.Write(rsaEncAesIv.Length); bw.Write(rsaEncAesIv); // AES encrypted length + data bw.Write(aesEncData.Length); bw.Write(aesEncData); } } } }
public AesCipher() { _aes = new AesManaged {KeySize = KeySize}; _aes.GenerateIV(); _aes.GenerateKey(); }
static void Main(string[] args) { try { string original = "aaaaaaaaaaaaaaa"; char result; using (AesManaged myAes = new AesManaged()) { myAes.KeySize = 256; myAes.BlockSize = 128; myAes.GenerateIV(); myAes.GenerateKey(); //myAes.Key = GetBytes("chave"); // transformar em bytes //myAes.IV = GetBytes("Sal"); // transformar em bytes byte[] encrypted = EncryptedStringToBytes_Aes(original, myAes.Key, myAes.IV); string criptb64 = System.Convert.ToBase64String(encrypted, 0, encrypted.Length); string cript = GetString(encrypted); string roundtrip = DecryptStringFromBytes_Aes(encrypted, myAes.Key, myAes.IV); Console.WriteLine($"1 Original: {original} tamanho: {original.Length}"); Console.WriteLine($"2 encryped: {cript} tamanho: {cript.Length}"); foreach(byte number in encrypted) { result = Convert.ToChar(number); Console.WriteLine($"number: {number} convert: {result}"); } Console.WriteLine($"3 cript64: {criptb64} tamanho: {criptb64.Length}"); Console.WriteLine($"4 roundtrip: {roundtrip} tamanho: {roundtrip.Length}"); } } catch (Exception e) { Console.WriteLine($"Erro: {e.Message}"); } Console.ReadKey(); }
/// <summary> /// Simple Encryption(AES) then Authentication (HMAC) for a UTF8 Message. /// </summary> /// <param name="secretMessage">The secret message.</param> /// <param name="cryptKey">The crypt key.</param> /// <param name="authKey">The auth key.</param> /// <param name="nonSecretPayload">(Optional) Non-Secret Payload.</param> /// <returns>Encrypted Message</returns> /// <remarks> /// Adds overhead of (Optional-Payload + BlockSize(16) + Message-Padded-To-Blocksize + HMac-Tag(32)) * 1.33 Base64 /// </remarks> private static string SimpleEncrypt(string secretMessage, byte[] cryptKey, byte[] authKey, byte[] nonSecretPayload = null) { Debug.Assert(cryptKey != null); Debug.Assert(cryptKey.Length == KeyBitSize / 8); Debug.Assert(authKey != null); Debug.Assert(authKey.Length == KeyBitSize / 8); Debug.Assert(secretMessage != null); Debug.Assert(secretMessage.Length > 0); //non-secret payload optional nonSecretPayload = nonSecretPayload ?? new byte[] {}; byte[] cipherText; byte[] iv; using (var aes = new AesManaged { KeySize = KeyBitSize, BlockSize = BlockBitSize, Mode = CipherMode.CBC, Padding = PaddingMode.PKCS7 } ) { //Use random IV aes.GenerateIV(); iv = aes.IV; using (var encrypter = aes.CreateEncryptor(cryptKey, iv)) using (var cipherStream = new MemoryStream()) { using (var tCryptoStream = new CryptoStream(cipherStream, encrypter, CryptoStreamMode.Write)) using (var tBinaryWriter = new BinaryWriter(tCryptoStream)) { //Encrypt Data tBinaryWriter.Write(Encoding.UTF8.GetBytes(secretMessage)); } cipherText = cipherStream.ToArray(); } } //Assemble encrypted message and add authentication using (var hmac = new HMACSHA256(authKey)) using (var encryptedStream = new MemoryStream()) { using (var binaryWriter = new BinaryWriter(encryptedStream)) { //Prepend non-secret payload if any binaryWriter.Write(nonSecretPayload); //Prepend IV binaryWriter.Write(iv); //Write Ciphertext binaryWriter.Write(cipherText); binaryWriter.Flush(); //Authenticate all data var tag = hmac.ComputeHash(encryptedStream.ToArray()); //Postpend tag binaryWriter.Write(tag); } return Convert.ToBase64String(encryptedStream.ToArray()); } }
public static string CreateEncryptedJweToken(JsonObject jwtPayload, RSAParameters publicKey) { //From: http://self-issued.info/docs/draft-ietf-jose-json-web-encryption-09.html#RSACBCExample var jweHeader = new JsonObject { { "alg", "RSA-OAEP" }, { "enc", "A128CBC-HS256" }, { "kid", Convert.ToBase64String(publicKey.Modulus).Substring(0,3) }, }; var jweHeaderBase64Url = jweHeader.ToJson().ToUtf8Bytes().ToBase64UrlSafe(); var authKey = new byte[128 / 8]; var cryptKey = new byte[128 / 8]; var cryptAuthKeys256 = AesUtils.CreateKey(); Buffer.BlockCopy(cryptAuthKeys256, 0, authKey, 0, authKey.Length); Buffer.BlockCopy(cryptAuthKeys256, authKey.Length, cryptKey, 0, cryptKey.Length); using (var aes = new AesManaged { KeySize = 128, BlockSize = 128, Mode = CipherMode.CBC, Padding = PaddingMode.PKCS7 }) { aes.GenerateIV(); var iv = aes.IV; aes.Key = cryptKey; var jweEncKey = RsaUtils.Encrypt(cryptAuthKeys256, publicKey, UseRsaKeyLength); var jweEncKeyBase64Url = jweEncKey.ToBase64UrlSafe(); var ivBase64Url = iv.ToBase64UrlSafe(); var aad = jweHeaderBase64Url + "." + jweEncKeyBase64Url; var aadBytes = aad.ToUtf8Bytes(); var payloadBytes = jwtPayload.ToJson().ToUtf8Bytes(); byte[] cipherText, tag; using (var encrypter = aes.CreateEncryptor(cryptKey, iv)) using (var cipherStream = new MemoryStream()) { using (var cryptoStream = new CryptoStream(cipherStream, encrypter, CryptoStreamMode.Write)) using (var writer = new BinaryWriter(cryptoStream)) { writer.Write(payloadBytes); } cipherText = cipherStream.ToArray(); } using (var hmac = new HMACSHA256(authKey)) using (var encryptedStream = new MemoryStream()) { using (var writer = new BinaryWriter(encryptedStream)) { writer.Write(aadBytes); writer.Write(iv); writer.Write(cipherText); writer.Flush(); tag = hmac.ComputeHash(encryptedStream.ToArray()); } } var cipherTextBase64Url = cipherText.ToBase64UrlSafe(); var tagBase64Url = tag.ToBase64UrlSafe(); var jweToken = jweHeaderBase64Url + "." + jweEncKeyBase64Url + "." + ivBase64Url + "." + cipherTextBase64Url + "." + tagBase64Url; return jweToken; } }
/// <summary> /// Creates or updates cipher keys. /// </summary> internal void UpdateKeyIVs() { using (AesManaged symmetricAlgorithm = new AesManaged()) { symmetricAlgorithm.KeySize = 256; symmetricAlgorithm.GenerateKey(); symmetricAlgorithm.GenerateIV(); if ((object)m_keyIVs == null) { // Initialize new key set m_keyIVs = new byte[2][][]; m_keyIVs[EvenKey] = new byte[2][]; m_keyIVs[OddKey] = new byte[2][]; m_keyIVs[EvenKey][KeyIndex] = symmetricAlgorithm.Key; m_keyIVs[EvenKey][IVIndex] = symmetricAlgorithm.IV; symmetricAlgorithm.GenerateKey(); symmetricAlgorithm.GenerateIV(); m_keyIVs[OddKey][KeyIndex] = symmetricAlgorithm.Key; m_keyIVs[OddKey][IVIndex] = symmetricAlgorithm.IV; m_cipherIndex = EvenKey; } else { // Generate a new key set for current cipher index m_keyIVs[m_cipherIndex][KeyIndex] = symmetricAlgorithm.Key; m_keyIVs[m_cipherIndex][IVIndex] = symmetricAlgorithm.IV; // Set run-time to the other key set m_cipherIndex ^= 1; } } m_lastCipherKeyUpdateTime = DateTime.UtcNow.Ticks; }