public static IDStorage decryptKeyStoreStorage(byte[] c_baKey, byte[] c_baIV, string c_sBase64JsonStorage) { const int MacBitSize = 128; byte [] baPayload = new byte[0]; var decryptCipher = new GcmBlockCipher(new AesFastEngine()); var parameters = new AeadParameters(new KeyParameter(c_baKey), MacBitSize, c_baIV, baPayload); decryptCipher.Init (false, parameters); byte[] baEncryptedStorage = Convert.FromBase64String (c_sBase64JsonStorage); var decryptedText = new byte[decryptCipher.GetOutputSize(baEncryptedStorage.Length)]; try { var len = decryptCipher.ProcessBytes(baEncryptedStorage, 0, baEncryptedStorage.Length, decryptedText, 0); decryptCipher.DoFinal(decryptedText, len); } catch (InvalidCipherTextException) { //Return null if it doesn't authenticate return null; } string sJsonStorage = Encoding.GetEncoding (1252).GetString (decryptedText); IDStorage _KeyStoreStorage = JsonConvert.DeserializeObject <IDStorage> (sJsonStorage); return _KeyStoreStorage; }
public byte[] Encrypt(byte[] plain, byte[] key, byte[] iv, byte[] aad = null, byte[] associated = null) { if (key.Length * 8 != this.KeySize) { throw new InvalidOperationException($"the given key has invalid size {key.Length * 8}, expect {this.KeySize}"); } var cipher = new Modes.GcmBlockCipher(new Engines.AesEngine()); cipher.Init(true, new Parameters.AeadParameters(new Parameters.KeyParameter(key), this.MacSize, iv, associated)); if (aad != null) { cipher.ProcessAadBytes(aad, 0, aad.Length); } var ret = new byte[cipher.GetOutputSize(plain.Length)]; var len = cipher.ProcessBytes(plain, 0, plain.Length, ret, 0); cipher.DoFinal(ret, len); return(ret); }
private void randomTest( SecureRandom srng, IGcmMultiplier m) { int kLength = 16 + 8 * srng.Next(3); byte[] K = new byte[kLength]; srng.NextBytes(K); int pLength = srng.Next(1024); byte[] P = new byte[pLength]; srng.NextBytes(P); int aLength = srng.Next(1024); byte[] A = new byte[aLength]; srng.NextBytes(A); int ivLength = 1 + srng.Next(1024); byte[] IV = new byte[ivLength]; srng.NextBytes(IV); GcmBlockCipher cipher = new GcmBlockCipher(new AesFastEngine(), m); AeadParameters parameters = new AeadParameters(new KeyParameter(K), 16 * 8, IV, A); cipher.Init(true, parameters); byte[] C = new byte[cipher.GetOutputSize(P.Length)]; int len = cipher.ProcessBytes(P, 0, P.Length, C, 0); len += cipher.DoFinal(C, len); if (C.Length != len) { // Console.WriteLine("" + C.Length + "/" + len); Fail("encryption reported incorrect length in randomised test"); } byte[] encT = cipher.GetMac(); byte[] tail = new byte[C.Length - P.Length]; Array.Copy(C, P.Length, tail, 0, tail.Length); if (!AreEqual(encT, tail)) { Fail("stream contained wrong mac in randomised test"); } cipher.Init(false, parameters); byte[] decP = new byte[cipher.GetOutputSize(C.Length)]; len = cipher.ProcessBytes(C, 0, C.Length, decP, 0); len += cipher.DoFinal(decP, len); if (!AreEqual(P, decP)) { Fail("incorrect decrypt in randomised test"); } byte[] decT = cipher.GetMac(); if (!AreEqual(encT, decT)) { Fail("decryption produced different mac from encryption"); } }
private void checkTestCase( GcmBlockCipher encCipher, GcmBlockCipher decCipher, string testName, byte[] P, byte[] C, byte[] T) { byte[] enc = new byte[encCipher.GetOutputSize(P.Length)]; int len = encCipher.ProcessBytes(P, 0, P.Length, enc, 0); len += encCipher.DoFinal(enc, len); if (enc.Length != len) { // Console.WriteLine("" + enc.Length + "/" + len); Fail("encryption reported incorrect length: " + testName); } byte[] mac = encCipher.GetMac(); byte[] data = new byte[P.Length]; Array.Copy(enc, data, data.Length); byte[] tail = new byte[enc.Length - P.Length]; Array.Copy(enc, P.Length, tail, 0, tail.Length); if (!AreEqual(C, data)) { Fail("incorrect encrypt in: " + testName); } if (!AreEqual(T, mac)) { Fail("GetMac() returned wrong mac in: " + testName); } if (!AreEqual(T, tail)) { Fail("stream contained wrong mac in: " + testName); } byte[] dec = new byte[decCipher.GetOutputSize(enc.Length)]; len = decCipher.ProcessBytes(enc, 0, enc.Length, dec, 0); len += decCipher.DoFinal(dec, len); mac = decCipher.GetMac(); data = new byte[C.Length]; Array.Copy(dec, data, data.Length); if (!AreEqual(P, data)) { Fail("incorrect decrypt in: " + testName); } }
/// <summary> /// Simple Decryption & Authentication (AES-GCM) of a UTF8 Message /// </summary> /// <param name="encryptedMessage">The encrypted message.</param> /// <param name="key">The key.</param> /// <param name="nonSecretPayloadLength">Length of the optional non-secret payload.</param> /// <returns>Decrypted Message</returns> public static byte[] SimpleDecrypt(byte[] encryptedMessage, byte[] key, int nonSecretPayloadLength = 0) { //User Error Checks if (key == null || key.Length != KeyBitSize / 8) throw new ArgumentException(String.Format("Key needs to be {0} bit!", KeyBitSize), "key"); if (encryptedMessage == null || encryptedMessage.Length == 0) throw new ArgumentException("Encrypted Message Required!", "encryptedMessage"); using (var cipherStream = new MemoryStream(encryptedMessage)) using (var cipherReader = new BinaryReader(cipherStream)) { //Grab Payload var nonSecretPayload = cipherReader.ReadBytes(nonSecretPayloadLength); //Grab Nonce var nonce = cipherReader.ReadBytes(NonceBitSize / 8); var cipher = new GcmBlockCipher(new AesFastEngine()); var parameters = new AeadParameters(new KeyParameter(key), MacBitSize, nonce, nonSecretPayload); cipher.Init(false, parameters); //Decrypt Cipher Text var cipherText = cipherReader.ReadBytes(encryptedMessage.Length - nonSecretPayloadLength - nonce.Length); var plainText = new byte[cipher.GetOutputSize(cipherText.Length)]; try { var len = cipher.ProcessBytes(cipherText, 0, cipherText.Length, plainText, 0); cipher.DoFinal(plainText, len); } catch (InvalidCipherTextException) { //Return null if it doesn't authenticate return null; } return plainText; } }
/// <summary> /// Simple Encryption And Authentication (AES-GCM) of a UTF8 string. /// </summary> /// <param name="secretMessage">The secret message.</param> /// <param name="key">The key.</param> /// <param name="nonSecretPayload">Optional non-secret payload.</param> /// <returns>Encrypted Message</returns> /// <remarks> /// Adds overhead of (Optional-Payload + BlockSize(16) + Message + HMac-Tag(16)) * 1.33 Base64 /// </remarks> public static byte[] SimpleEncrypt(byte[] secretMessage, byte[] key, byte[] nonSecretPayload = null) { //User Error Checks if (key == null || key.Length != KeyBitSize / 8) throw new ArgumentException(String.Format("Key needs to be {0} bit!", KeyBitSize), "key"); if (secretMessage == null || secretMessage.Length == 0) throw new ArgumentException("Secret Message Required!", "secretMessage"); //Non-secret Payload Optional nonSecretPayload = nonSecretPayload ?? new byte[] { }; //Using random nonce large enough not to repeat var nonce = new byte[NonceBitSize / 8]; Random.NextBytes(nonce, 0, nonce.Length); var cipher = new GcmBlockCipher(new AesFastEngine()); var parameters = new AeadParameters(new KeyParameter(key), MacBitSize, nonce, nonSecretPayload); cipher.Init(true, parameters); //Generate Cipher Text With Auth Tag var cipherText = new byte[cipher.GetOutputSize(secretMessage.Length)]; var len = cipher.ProcessBytes(secretMessage, 0, secretMessage.Length, cipherText, 0); cipher.DoFinal(cipherText, len); //Assemble Message using (var combinedStream = new MemoryStream()) { using (var binaryWriter = new BinaryWriter(combinedStream)) { //Prepend Authenticated Payload binaryWriter.Write(nonSecretPayload); //Prepend Nonce binaryWriter.Write(nonce); //Write Cipher Text binaryWriter.Write(cipherText); } return combinedStream.ToArray(); } }
// AES private String decrypt(byte[] data, byte[] key, byte[] iv) { var cipher = new GcmBlockCipher(new AesFastEngine()); var parameters = new ParametersWithIV(new KeyParameter(key, 0, 32), iv); cipher.Init(false, parameters); var pText = new byte[cipher.GetOutputSize(data.Length)]; var len2 = cipher.ProcessBytes(data, 0, data.Length, pText, 0); cipher.DoFinal(pText, len2); return System.Text.Encoding.Default.GetString(pText); }
public static string encryptIdStorage(byte[] c_baKey, byte[] c_baIV, IDStorage c_KeyStoreStorage) { const int MacBitSize = 128; byte [] baPayload = new byte[0]; var encryptCipher = new GcmBlockCipher(new AesFastEngine()); var parameters = new AeadParameters(new KeyParameter(c_baKey), MacBitSize, c_baIV, baPayload); encryptCipher.Init (true, parameters); string sJsonStorage = JsonConvert.SerializeObject (c_KeyStoreStorage);//ConvertToJSON and byte[] baJsonStorage = Encoding.GetEncoding(1252).GetBytes(sJsonStorage);// get Bytes from ASCII-String var cipherText = new byte[encryptCipher.GetOutputSize(baJsonStorage.Length)]; var len = encryptCipher.ProcessBytes(baJsonStorage, 0, baJsonStorage.Length, cipherText, 0); encryptCipher.DoFinal(cipherText, len); string sCipherString = Convert.ToBase64String (cipherText); return sCipherString; }