public static string encrypt(string PlainText, byte[] key, byte[] iv, long AAD, out byte[] outTag) { string sR = string.Empty; try { byte[] plainBytes = Encoding.ASCII.GetBytes(PlainText); GcmBlockCipher cipher = new GcmBlockCipher(new AesFastEngine()); AeadParameters parameters = new AeadParameters(new KeyParameter(key), 128, iv, null); var tempAddBytesArr = BitConverter.GetBytes(AAD); cipher.Init(true, parameters); foreach (var item in tempAddBytesArr) { cipher.ProcessAadByte(item); } byte[] encryptedBytes = new byte[cipher.GetOutputSize(plainBytes.Length)]; Int32 retLen = cipher.ProcessBytes (plainBytes, 0, plainBytes.Length, encryptedBytes, 0); outTag = cipher.GetMac(); cipher.DoFinal(encryptedBytes, retLen); sR = Convert.ToBase64String(encryptedBytes, Base64FormattingOptions.None); } catch (Exception ex) { outTag = new byte[1] { 0x0 }; Console.WriteLine(ex.Message); Console.WriteLine(ex.StackTrace); } return(sR); }
private void AES_GCM_Encrypt(byte[] k) { GcmBlockCipher cipher = new GcmBlockCipher(new AesEngine(), new BasicGcmMultiplier()); KeyParameter contentKey; // The requirements from JWA // IV is 96 bits // Authentication tag is 128 bits // key sizes are 128, 192 and 256 bits _iv = new byte[96 / 8]; s_PRNG.NextBytes(_iv); contentKey = new KeyParameter(k); // Build the object to be hashed byte[] a = CreateAad(); AeadParameters parameters = new AeadParameters(contentKey, 128, _iv, a); cipher.Init(true, parameters); byte[] c = new byte[cipher.GetOutputSize(payload.Length)]; int len = cipher.ProcessBytes(payload, 0, payload.Length, c, 0); cipher.DoFinal(c, len); _RgbEncrypted = c; _Tag = cipher.GetMac(); Array.Resize(ref _RgbEncrypted, _RgbEncrypted.Length - _Tag.Length); }
/// <summary> /// Encrypts the message. /// </summary> /// <param name="message">The message.</param> /// <param name="key">The key.</param> /// <returns></returns> /// <exception cref="System.ArgumentException"> /// key /// or /// Message Required! - message /// </exception> /// PushBullet requires the encryption to be in the format of [version + tag + IV + encrypted message] public static string EncryptMessage(string message, string key) { byte[] messageBytes = Encoding.UTF8.GetBytes(message); byte[] keyBytes = Convert.FromBase64String(key); byte[] versionBytes = Encoding.UTF8.GetBytes("1"); if (keyBytes == null || keyBytes.Length != KeyBitSize / 8) { throw new ArgumentException(string.Format("Key needs to be {0} bit!", KeyBitSize), "key"); } if (message == null || message.Length == 0) { throw new ArgumentException("Message required!", "message"); } //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 AesEngine()); var parameters = new AeadParameters(new KeyParameter(keyBytes), TagBitSize, nonce); cipher.Init(true, parameters); //Generate Cipher Text With Auth Tag var outputSize = cipher.GetOutputSize(messageBytes.Length); var cipherText = new byte[outputSize]; var len = cipher.ProcessBytes(messageBytes, 0, messageBytes.Length, cipherText, 0); cipher.DoFinal(cipherText, len); //Get the tag and remove the tag from the cipherText var tag = cipher.GetMac(); byte[] encrypted = new byte[cipherText.Length - tag.Length]; Array.Copy(cipherText, 0, encrypted, 0, encrypted.Length); //Assemble Message using (var combinedStream = new MemoryStream()) { using (var binaryWriter = new BinaryWriter(combinedStream)) { //Prepend the version binaryWriter.Write(versionBytes); //Prepend Tag binaryWriter.Write(tag); //Prepend Nonce binaryWriter.Write(nonce); //Write Encrypted Message binaryWriter.Write(encrypted); } return(Convert.ToBase64String(combinedStream.ToArray())); } }
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 string SimpleDecrypt(string 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 (string.IsNullOrWhiteSpace(encryptedMessage)) { throw new ArgumentException("Encrypted Message Required!", "encryptedMessage"); } var messageArray = Convert.FromBase64String(encryptedMessage); using (var cipherStream = new MemoryStream(messageArray)) 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(messageArray.Length - nonSecretPayloadLength - nonce.Length); var plainText = new byte[cipher.GetOutputSize(cipherText.Length)]; var len = cipher.ProcessBytes(cipherText, 0, cipherText.Length, plainText, 0); cipher.DoFinal(plainText, len); //Grab Authentication var cipherTag = new byte[MacBitSize / 8]; Array.Copy(cipherText, cipherText.Length - cipherTag.Length, cipherTag, 0, cipherTag.Length); //Check Autentication var calcTag = cipher.GetMac(); var auth = true; for (var i = 0; i < cipherTag.Length; i++) { auth = auth && cipherTag[i] == calcTag[i]; } //Return Null if it doesn't authenticate return(!auth ? null : Encoding.UTF8.GetString(plainText)); } }
public byte[][] Encrypt(byte[] plainText, byte[] cek, byte[] iv, byte[] aad) { var cipher = new GcmBlockCipher(new AesEngine()); var parameters = new AeadParameters(new KeyParameter(cek), KeySize, iv, aad); cipher.Init(true, parameters); var cipherText = new byte[cipher.GetOutputSize(plainText.Length)]; var len = cipher.ProcessBytes(plainText, 0, plainText.Length, cipherText, 0); cipher.DoFinal(cipherText, len); return(new[] { cipherText.SkipLast(16).ToArray(), cipher.GetMac() }); }
public static string GetEncryptedPassword(this IInstaApi api, string password, long?providedTime = null) { var pubKey = api.GetLoggedUser().PublicKey; var pubKeyId = api.GetLoggedUser().PublicKeyId; byte[] randKey = new byte[32]; byte[] iv = new byte[12]; secureRandom.NextBytes(randKey, 0, randKey.Length); secureRandom.NextBytes(iv, 0, iv.Length); long time = providedTime ?? DateTime.UtcNow.ToUnixTime(); byte[] associatedData = Encoding.UTF8.GetBytes(time.ToString()); var pubKEY = Encoding.UTF8.GetString(Convert.FromBase64String(pubKey)); byte[] encryptedKey; using (var rdr = PemKeyUtils.GetRSAProviderFromPemString(pubKEY.Trim())) encryptedKey = rdr.Encrypt(randKey, false); byte[] plaintext = Encoding.UTF8.GetBytes(password); var cipher = new GcmBlockCipher(new AesEngine()); var parameters = new AeadParameters(new KeyParameter(randKey), 128, iv, associatedData); cipher.Init(true, parameters); var ciphertext = new byte[cipher.GetOutputSize(plaintext.Length)]; var len = cipher.ProcessBytes(plaintext, 0, plaintext.Length, ciphertext, 0); cipher.DoFinal(ciphertext, len); var con = new byte[plaintext.Length]; for (int i = 0; i < plaintext.Length; i++) { con[i] = ciphertext[i]; } ciphertext = con; var tag = cipher.GetMac(); byte[] buffersSize = BitConverter.GetBytes(Convert.ToInt16(encryptedKey.Length)); byte[] encKeyIdBytes = BitConverter.GetBytes(Convert.ToUInt16(pubKeyId)); if (BitConverter.IsLittleEndian) { Array.Reverse(encKeyIdBytes); } encKeyIdBytes[0] = 1; var payload = Convert.ToBase64String(encKeyIdBytes.Concat(iv).Concat(buffersSize).Concat(encryptedKey).Concat(tag).Concat(ciphertext).ToArray()); return($"#PWD_INSTAGRAM:4:{time}:{payload}"); }
//--------------------------------------------------------Set-, Get- Methods:---------------------------------------------------------\\ #region --Set-, Get- Methods-- #endregion //--------------------------------------------------------Misc Methods:---------------------------------------------------------------\\ #region --Misc Methods (Public)-- public byte[] encrypt(byte[] data) { // Create the cipher instance and initialize: GcmBlockCipher cipher = new GcmBlockCipher(new AesEngine()); KeyParameter keyParam = new KeyParameter(key); AeadParameters aeadParams = new AeadParameters(keyParam, AUTH_TAG_SIZE_BITS, iv); cipher.Init(true, aeadParams); // Encrypt: byte[] ciphertext = new byte[cipher.GetOutputSize(data.Length)]; int length = cipher.ProcessBytes(data, 0, data.Length, ciphertext, 0); cipher.DoFinal(ciphertext, length); authTag = cipher.GetMac(); /*byte[] encryptedData = new byte[iv.Length + ciphertext.Length]; * Buffer.BlockCopy(iv, 0, encryptedData, 0, iv.Length); * Buffer.BlockCopy(ciphertext, 0, encryptedData, iv.Length, ciphertext.Length);*/ return(ciphertext); }
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(65536); byte[] P = new byte[pLength]; srng.NextBytes(P); int aLength = srng.Next(256); byte[] A = new byte[aLength]; srng.NextBytes(A); int saLength = srng.Next(256); byte[] SA = new byte[saLength]; srng.NextBytes(SA); int ivLength = 1 + srng.Next(256); byte[] IV = new byte[ivLength]; srng.NextBytes(IV); AeadParameters parameters = new AeadParameters(new KeyParameter(K), 16 * 8, IV, A); GcmBlockCipher cipher = InitCipher(m, true, parameters); byte[] C = new byte[cipher.GetOutputSize(P.Length)]; int predicted = cipher.GetUpdateOutputSize(P.Length); int split = srng.Next(SA.Length + 1); cipher.ProcessAadBytes(SA, 0, split); int len = cipher.ProcessBytes(P, 0, P.Length, C, 0); cipher.ProcessAadBytes(SA, split, SA.Length - split); if (predicted != len) { Fail("encryption reported incorrect update length in randomised test"); } len += cipher.DoFinal(C, len); if (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)]; predicted = cipher.GetUpdateOutputSize(C.Length); split = srng.Next(SA.Length + 1); cipher.ProcessAadBytes(SA, 0, split); len = cipher.ProcessBytes(C, 0, C.Length, decP, 0); cipher.ProcessAadBytes(SA, split, SA.Length - split); if (predicted != len) { Fail("decryption reported incorrect update length in randomised test"); } 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"); } // // key reuse test // cipher.Init(false, AeadTestUtilities.ReuseKey(parameters)); decP = new byte[cipher.GetOutputSize(C.Length)]; split = NextInt(srng, SA.Length + 1); cipher.ProcessAadBytes(SA, 0, split); len = cipher.ProcessBytes(C, 0, C.Length, decP, 0); cipher.ProcessAadBytes(SA, split, SA.Length - split); len += cipher.DoFinal(decP, len); if (!AreEqual(P, decP)) { Fail("incorrect decrypt in randomised test"); } decT = cipher.GetMac(); if (!AreEqual(encT, decT)) { Fail("decryption produced different mac from encryption"); } }
internal override void Evaluate(EngineProvider provider) { GcmBlockCipher encCipher = new GcmBlockCipher(provider.CreateEngine(EngineUsage.GENERAL)); GcmBlockCipher decCipher = new GcmBlockCipher(provider.CreateEngine(EngineUsage.GENERAL)); byte[] K = Hex.Decode("feffe9928665731c6d6a8f9467308308"); byte[] P = Hex.Decode("d9313225f88406e5a55909c5aff5269a" + "86a7a9531534f7da2e4c303d8a318a72" + "1c3c0c95956809532fcf0e2449a6b525" + "b16aedf5aa0de657ba637b39"); byte[] A = Hex.Decode("feedfacedeadbeeffeedfacedeadbeef" + "abaddad2"); byte[] IV = Hex.Decode("cafebabefacedbaddecaf888"); byte[] C = Hex.Decode("42831ec2217774244b7221b784d0d49c" + "e3aa212f2c02a4e035c17e2329aca12e" + "21d514b25466931c7d8f6a5aac84aa05" + "1ba30b396a0aac973d58e091"); byte[] T = Hex.Decode("5bc94fbc3221a5db94fae95ae7121a47"); ICipherParameters parameters = new AeadParameters(new KeyParameter(K), T.Length * 8, IV, A); encCipher.Init(true, parameters); decCipher.Init(false, parameters); 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) { Fail("encryption reported incorrect length"); } byte[] mac = encCipher.GetMac(); byte[] data = new byte[P.Length]; Array.Copy(enc, 0, data, 0, data.Length); byte[] tail = new byte[enc.Length - P.Length]; Array.Copy(enc, P.Length, tail, 0, tail.Length); if (!Arrays.AreEqual(FipsKats.Values[FipsKats.Vec.AesGcmEnc], data)) { Fail("incorrect encrypt"); } if (!Arrays.AreEqual(FipsKats.Values[FipsKats.Vec.AesGcmEncTag], mac)) { Fail("getMac() returned wrong MAC"); } if (!Arrays.AreEqual(FipsKats.Values[FipsKats.Vec.AesGcmEncTag], tail)) { Fail("stream contained wrong MAC"); } byte[] dec = new byte[decCipher.GetOutputSize(enc.Length)]; len = decCipher.ProcessBytes(enc, 0, enc.Length, dec, 0); decCipher.DoFinal(dec, len); mac = decCipher.GetMac(); data = new byte[C.Length]; Array.Copy(dec, 0, data, 0, data.Length); if (!Arrays.AreEqual(FipsKats.Values[FipsKats.Vec.AesGcmDec], data)) { Fail("incorrect decrypt"); } if (!Arrays.AreEqual(FipsKats.Values[FipsKats.Vec.AesGcmDecTag], mac)) { Fail("incorrect MAC on decrypt"); } }
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"); } }
public byte[] EncryptWithKey(byte[] messageToEncrypt, byte[] keyBytes, string keyId, byte[] nonSecretPayload = null) { var key = new byte[32]; _random.NextBytes(key); //User Error Checks CheckKey(key); //Non-secret Payload Optional nonSecretPayload = nonSecretPayload ?? new byte[] { }; //Using random nonce large enough not to repeat var nonce = new byte[12]; // new byte[_nonceSize / 8]; /// equals IV // _random.NextBytes(nonce, 0, nonce.Length); var cipher = new GcmBlockCipher(new AesEngine()); var parameters = new AeadParameters(new KeyParameter(key), _macSize, nonce, nonSecretPayload); cipher.Init(true, parameters); //Generate Cipher Text With Auth Tag var cipherText = new byte[cipher.GetOutputSize(messageToEncrypt.Length)]; var len = cipher.ProcessBytes(messageToEncrypt, 0, messageToEncrypt.Length, cipherText, 0); cipher.DoFinal(cipherText, len); var encryptedKey = Sodium.SealedPublicKeyBox.Create(key, keyBytes); var bytesOfLen = ToBytes((short)encryptedKey.Length); // ToBytes = BitConverter.GetBytes(short); var info = new byte[] { 1, byte.Parse(keyId) }; //Output auth tag var authTag = cipher.GetMac(); // Console.WriteLine($"Cipher text (hex): {ByteArrayToString(cipherText)}"); // Console.WriteLine($"Cipher tag (hex): {ByteArrayToString(authTag)}"); var temp = cipherText; cipherText = new byte[messageToEncrypt.Length]; for (int i = 0; i < cipherText.Length; i++) { cipherText[i] = temp[i]; } // Console.WriteLine($"Cipher text after cut (hex): {ByteArrayToString(cipherText)}"); //Assemble Message byte[] result; using (var combinedStream = new MemoryStream()) { using (var binaryWriter = new BinaryWriter(combinedStream)) { // info.Concat(bytesOfLen). // Concat(encryptedKey). // Concat(tag). // Concat(cipherText); // Concat means that concat two array binaryWriter.Write(info); binaryWriter.Write(bytesOfLen); binaryWriter.Write(encryptedKey); binaryWriter.Write(authTag); binaryWriter.Write(cipherText); //Assemble Message //Prepend Authenticated Payload // binaryWriter.Write(nonSecretPayload); // //Prepend Nonce // binaryWriter.Write(nonce); // //Write Cipher Text // binaryWriter.Write(cipherText); } result = combinedStream.ToArray(); } // string Info = "======== Bytes Info [sosi]=======\n"; // Info+= $"Payload: {nonSecretPayload.Length} ({ByteArrayToString(nonSecretPayload)})\n"; // Info += $"Key: {ByteArrayToString(keyBytes)}\n"; // Info += $"KeyId: {keyId}\n"; // // Info += $"info: {info.Length} ({ByteArrayToString(info)})\n"; // Info += $"bytesOfLen: {bytesOfLen.Length} ({ByteArrayToString(bytesOfLen)}) [{(short)key.Length}]\n"; // Info += $"encryptedKey: {encryptedKey.Length} ({ByteArrayToString(encryptedKey)})\n"; // Info += $"auth_tag: {authTag.Length} ({ByteArrayToString(authTag)})\n"; // Info += $"cipherText: {cipherText.Length} ({ByteArrayToString(cipherText)})\n\n"; // Info += $"Total: {result.Length} ({ByteArrayToString(result)})\n"; // Info += "===========================\n"; // // Console.WriteLine(Info); return(result); }