private static byte[] EncryptAesGcmWithBouncyCastle(byte[] plaintext, byte[] key, byte[] nonce, out byte[] tag) { const int tagLenth = 16; // in bytes var plaintextBytes = plaintext; var bcCiphertext = new byte[plaintextBytes.Length + tagLenth]; var cipher = new GcmBlockCipher(new AesEngine()); var parameters = new AeadParameters(new KeyParameter(key), tagLenth * 8, nonce); cipher.Init(true, parameters); var offset = cipher.ProcessBytes(plaintextBytes, 0, plaintextBytes.Length, bcCiphertext, 0); cipher.DoFinal(bcCiphertext, offset); // Bouncy Castle includes the authentication tag in the ciphertext var ciphertext = new byte[plaintextBytes.Length]; tag = new byte[tagLenth]; Buffer.BlockCopy(bcCiphertext, 0, ciphertext, 0, plaintextBytes.Length); Buffer.BlockCopy(bcCiphertext, plaintextBytes.Length, tag, 0, tagLenth); return(ciphertext); }
public virtual void Init( bool forEncryption, ICipherParameters parameters) { this.forEncryption = forEncryption; if (parameters is AeadParameters) { AeadParameters param = (AeadParameters)parameters; nonce = param.GetNonce(); associatedText = param.GetAssociatedText(); macSize = param.MacSize / 8; keyParam = param.Key; } else if (parameters is ParametersWithIV) { ParametersWithIV param = (ParametersWithIV)parameters; nonce = param.GetIV(); associatedText = null; macSize = macBlock.Length / 2; keyParam = param.Parameters; } else { throw new ArgumentException("invalid parameters passed to CCM"); } }
public MemoryStream Decrypt(MemoryStream data) { if (data.Length > int.MaxValue) { throw new ArgumentException("Data to decrypt should be smaller than 2GB"); } using (var cipherReader = new BinaryReader(data)) { data.Position = 0; var nonce = cipherReader.ReadBytes(SALT_LENGTH); var cipher = new GcmBlockCipher(new AesEngine()); var parameters = new AeadParameters(new KeyParameter(this.key), TAG_LENGTH * 8, nonce, null); cipher.Init(false, parameters); int dataLength = (int)data.Length - SALT_LENGTH; var ciphertext = cipherReader.ReadBytes(dataLength); var plaintext = new byte[cipher.GetOutputSize(ciphertext.Length)]; var len = cipher.ProcessBytes(ciphertext, 0, ciphertext.Length, plaintext, 0); cipher.DoFinal(plaintext, len); return(new MemoryStream(plaintext)); } }
public static string EncryptSymmetric <T>(this T data, string symmetricKey, string initialisationVector) { var keyParameter = new KeyParameter(Convert.FromBase64String(symmetricKey)); const int macSize = 128; var nonce = new byte[128 / 8]; nonce = Encoding.UTF8.GetBytes(initialisationVector).Take(nonce.Length).ToArray(); var associatedText = new byte[] { }; var cipher = new GcmBlockCipher(new AesFastEngine()); var parameters = new AeadParameters(keyParameter, macSize, nonce, associatedText); cipher.Init(true, parameters); using (MemoryStream ms = new MemoryStream()) { Serializer.Serialize <T>(ms, data); ms.Position = 0; byte[] msg; using (BinaryReader br = new BinaryReader(ms)) msg = br.ReadBytes((int)ms.Length); var encdata = new byte[cipher.GetOutputSize(msg.Length)]; var len = cipher.ProcessBytes(msg, 0, msg.Length, encdata, 0); cipher.DoFinal(encdata, len); return(Convert.ToBase64String(encdata)); } }
public static byte[] Aes256Decrypt(ReadOnlyMemory <byte> encryptedData, ReadOnlyMemory <byte> key, EncryptionOptions options = null) { if (key.Length != Constants.Aes256.KeySize || encryptedData.Length == 0) { return(null); } using var cipherStream = new MemoryStream(encryptedData.ToArray()); using var cipherReader = new BinaryReader(cipherStream); var nonce = cipherReader.ReadBytes(options?.NonceSize ?? Constants.Aes256.NonceSize); var cipher = new GcmBlockCipher(new AesEngine()); var parameters = new AeadParameters(new KeyParameter(key.ToArray()), options?.MacBitSize ?? Constants.Aes256.MacBitSize, nonce); cipher.Init(false, parameters); var cipherText = cipherReader.ReadBytes(encryptedData.Length - nonce.Length); var plainText = new byte[cipher.GetOutputSize(cipherText.Length)]; try { cipher.DoFinal(plainText, cipher.ProcessBytes(cipherText, 0, cipherText.Length, plainText, 0)); } catch (InvalidCipherTextException) { return(null); } return(plainText); }
/// <summary> /// Encrypt the specified data using the specified salt. ///Encrypt uses provided salt, uses master key ///& salt to generate per-data key & nonce with the help of HKDF ///Salt is concatenated to the ciphertext /// </summary> /// <returns>The encrypted data bytes.</returns> /// <param name="data">Data to be encrypted.</param> public byte[] EncryptWithSalt(byte[] data, byte[] salt) { Validation.NotNull(data); Validation.NotNullOrEmptyByteArray(salt); var hkdf = new HkdfBytesGenerator(new Sha512Digest()); hkdf.Init(new HkdfParameters(this.key, salt, this.domain)); var keyNonce = new byte[SymKeyLen + SymNonceLen]; hkdf.GenerateBytes(keyNonce, 0, keyNonce.Length); var cipher = new GcmBlockCipher(new AesEngine()); var keyNonceSlice1 = ((Span <byte>)keyNonce).Slice(0, SymKeyLen); var keyNonceSlice2 = ((Span <byte>)keyNonce).Slice(SymKeyLen); var parameters = new AeadParameters( new KeyParameter(keyNonceSlice1.ToArray()), SymTagLen * 8, keyNonceSlice2.ToArray()); cipher.Init(true, parameters); var cipherText = new byte[cipher.GetOutputSize(data.Length)]; var len = cipher.ProcessBytes(data, 0, data.Length, cipherText, 0); cipher.DoFinal(cipherText, len); return(Bytes.Combine(salt, cipherText)); }
private byte[] AESGCM_KeyWrap(byte[] key, EncryptMessage msg) { 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 // Keywrap says that there is no AAD contentKey = new KeyParameter(key); byte[] a = new byte[0]; byte[] iv = Message.base64urldecode(FindAttr("iv", msg).AsString()); byte[] tag = Message.base64urldecode(FindAttr("tag", msg).AsString()); AeadParameters parameters = new AeadParameters(contentKey, 128, iv, a); cipher.Init(false, parameters); byte[] c = new byte[cipher.GetOutputSize(_rgbEncrypted.Length + tag.Length)]; int len = cipher.ProcessBytes(_rgbEncrypted, 0, _rgbEncrypted.Length, c, 0); len += cipher.ProcessBytes(tag, 0, tag.Length, c, len); cipher.DoFinal(c, len); return(c); }
public static byte[] AES256Encrypt(this byte[] plainData, byte[] key, byte[] nonce, byte[] associatedData = null) { if (nonce.Length != 12) { throw new ArgumentOutOfRangeException(nameof(nonce)); } var tag = new byte[16]; var cipherBytes = new byte[plainData.Length]; if (!IsOSX) { using var cipher = new AesGcm(key); cipher.Encrypt(nonce, plainData, cipherBytes, tag, associatedData); } else { var cipher = new GcmBlockCipher(new AesEngine()); var parameters = new AeadParameters( new KeyParameter(key), 128, //128 = 16 * 8 => (tag size * 8) nonce, associatedData); cipher.Init(true, parameters); cipherBytes = new byte[cipher.GetOutputSize(plainData.Length)]; var length = cipher.ProcessBytes(plainData, 0, plainData.Length, cipherBytes, 0); cipher.DoFinal(cipherBytes, length); } return(Concat(nonce, cipherBytes, tag)); }
private static void ConfigureAes128GcmCipher(GcmBlockCipher aes128GcmCipher, bool forEncryption, byte[] pseudorandomKey, byte[] contentEncryptionKey, ulong recordSequenceNumber) { aes128GcmCipher.Reset(); AeadParameters aes128GcmParameters = new AeadParameters(new KeyParameter(contentEncryptionKey), 128, GetNonce(pseudorandomKey, recordSequenceNumber)); aes128GcmCipher.Init(forEncryption, aes128GcmParameters); }
/// <summary> /// 敏感信息加密需要从https://api.mch.weixin.qq.com/risk/getcertficates此接口下载加密证书进行下一步加密, /// 该接口下载到的是密文,使用此AESGCM.Decrypt()方法解密得到证书明文 /// </summary> /// <param name="ciphertext">接口下载得到的JSON里的ciphertext字段</param> /// <param name="key">微信支付商户后台设置的V3密钥</param> /// <param name="ivs">接口下载得到的JSON里的nonce字段</param> /// <param name="associatedText">默认为certificate,不需更改</param> /// <returns> 返回公钥明文,-----BEGIN CERTIFICATE----- </returns> public static string Decrypt(string ciphertext, string key, string ivs, string associatedText = "certificate") { var buff = Convert.FromBase64String(ciphertext); var secret = Encoding.UTF8.GetBytes(key); var nonce = Encoding.UTF8.GetBytes(ivs); var associatedData = Encoding.UTF8.GetBytes(associatedText); // 算法 AEAD_AES_256_GCM,C# 环境使用 BouncyCastle.Crypto.dll 类库实现 var cipher = new GcmBlockCipher(new AesFastEngine()); var aead = new AeadParameters(new KeyParameter(secret), 128, nonce, associatedData); cipher.Init(false, aead); var data = new byte[cipher.GetOutputSize(buff.Length)]; var num = cipher.ProcessBytes(buff, 0, buff.Length, data, 0); try { cipher.DoFinal(data, num); } catch (Exception) { } return(Encoding.UTF8.GetString(data)); }
// Token: 0x06000013 RID: 19 RVA: 0x00003260 File Offset: 0x00001460 private static string smethod_15(byte[] byte_0, byte[] byte_1, int int_1) { string @string; using (MemoryStream memoryStream = new MemoryStream(byte_0)) { using (BinaryReader binaryReader = new BinaryReader(memoryStream)) { binaryReader.ReadBytes(int_1); byte[] array = binaryReader.ReadBytes(12); GcmBlockCipher gcmBlockCipher = new GcmBlockCipher(new AesEngine()); AeadParameters aeadParameters = new AeadParameters(new KeyParameter(byte_1), 128, array); gcmBlockCipher.Init(false, aeadParameters); byte[] array2 = binaryReader.ReadBytes(byte_0.Length); byte[] array3 = new byte[gcmBlockCipher.GetOutputSize(array2.Length)]; try { int num = gcmBlockCipher.ProcessBytes(array2, 0, array2.Length, array3, 0); gcmBlockCipher.DoFinal(array3, num); } catch { return(null); } @string = Encoding.Default.GetString(array3); } } return(@string); }
private void checkVectors( int count, string additionalDataType, byte[] k, int macSize, byte[] n, byte[] a, byte[] sa, byte[] p, byte[] t, byte[] c) { EaxBlockCipher encEax = new EaxBlockCipher(new AesEngine()); EaxBlockCipher decEax = new EaxBlockCipher(new AesEngine()); AeadParameters parameters = new AeadParameters(new KeyParameter(k), macSize, n, a); encEax.Init(true, parameters); decEax.Init(false, parameters); runCheckVectors(count, encEax, decEax, additionalDataType, sa, p, t, c); runCheckVectors(count, encEax, decEax, additionalDataType, sa, p, t, c); // key reuse test parameters = new AeadParameters(null, macSize, n, a); encEax.Init(true, parameters); decEax.Init(false, parameters); runCheckVectors(count, encEax, decEax, additionalDataType, sa, p, t, c); runCheckVectors(count, encEax, decEax, additionalDataType, sa, p, t, c); }
private void AES_GCM_Decrypt(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 contentKey = new KeyParameter(k); byte[] a = CreateAad(); AeadParameters parameters = new AeadParameters(contentKey, 128, _iv, a); cipher.Init(false, parameters); byte[] c = new byte[cipher.GetOutputSize(_RgbEncrypted.Length + _Tag.Length)]; int len = cipher.ProcessBytes(_RgbEncrypted, 0, _RgbEncrypted.Length, c, 0); len += cipher.ProcessBytes(_Tag, 0, _Tag.Length, c, len); cipher.DoFinal(c, len); payload = c; }
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); }
//encrypt with byte array private byte[] EncryptWithKey(byte[] text, byte[] key, byte[] nonSecretPayload = null) { if (key == null || key.Length != KEY_BIT_SIZE / 8) { throw new ArgumentException(String.Format("Key needs to be {0} bit!", KEY_BIT_SIZE), "key"); } nonSecretPayload = nonSecretPayload ?? new byte[] { }; var nonce = new byte[NONCE_BIT_SIZE / 8]; _random.NextBytes(nonce, 0, nonce.Length); var cipher = new GcmBlockCipher(new AesEngine()); var parameters = new AeadParameters(new KeyParameter(key), MAC_BIT_SIZE, nonce, nonSecretPayload); cipher.Init(true, parameters); var cipherData = new byte[cipher.GetOutputSize(text.Length)]; var len = cipher.ProcessBytes(text, 0, text.Length, cipherData, 0); cipher.DoFinal(cipherData, len); using (var combinedStream = new MemoryStream()) { using (var binaryWriter = new BinaryWriter(combinedStream)) { binaryWriter.Write(nonSecretPayload); binaryWriter.Write(nonce); binaryWriter.Write(cipherData); } return(combinedStream.ToArray()); } }
private void RunTestCase(string testName, string[] testVector, int macLengthBits) { byte[] key = Hex.Decode(K); byte[] nonce = Hex.Decode(N); int pos = 0; byte[] A = Hex.Decode(testVector[pos++]); byte[] P = Hex.Decode(testVector[pos++]); byte[] C = Hex.Decode(testVector[pos++]); int macLengthBytes = macLengthBits / 8; // TODO Variations processing AAD and cipher bytes incrementally KeyParameter keyParameter = new KeyParameter(key); AeadParameters aeadParameters = new AeadParameters(keyParameter, macLengthBits, nonce, A); OcbBlockCipher encCipher = InitCipher(true, aeadParameters); OcbBlockCipher decCipher = InitCipher(false, aeadParameters); CheckTestCase(encCipher, decCipher, testName, macLengthBytes, P, C); CheckTestCase(encCipher, decCipher, testName + " (reused)", macLengthBytes, P, C); // TODO Key reuse }
public string decrypt_data(byte[] data) { var encryptedData = data; var encKey = File.ReadAllText(Environment.GetEnvironmentVariable("APPDATA").GoUpNLevels() + @"/Local/Google/Chrome/User Data/Local State"); encKey = JObject.Parse(encKey)["os_crypt"]["encrypted_key"].ToString(); var decodedKey = ProtectedData.Unprotect(Convert.FromBase64String(encKey).Skip(5).ToArray(), null, DataProtectionScope.LocalMachine); const int MAC_BIT_SIZE = 128; const int NONCE_BIT_SIZE = 96; using (var cipherStream = new MemoryStream(encryptedData)) using (var cipherReader = new BinaryReader(cipherStream)) { var nonSecretPayload = cipherReader.ReadBytes(3); var nonce = cipherReader.ReadBytes(NONCE_BIT_SIZE / 8); var cipher = new GcmBlockCipher(new AesEngine()); var parameters = new AeadParameters(new KeyParameter(decodedKey), MAC_BIT_SIZE, nonce); cipher.Init(false, parameters); var cipherText = cipherReader.ReadBytes(encryptedData.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(Encoding.Default.GetString(plainText)); } }
private OcbBlockCipher InitCipher(bool forEncryption, AeadParameters parameters) { OcbBlockCipher c = new OcbBlockCipher(new AesFastEngine(), new AesFastEngine()); c.Init(forEncryption, parameters); return(c); }
public override byte[] Encrypt(byte[] input, CryptoKey key) { byte[] nonce = GenerateNonce(); IAeadBlockCipher cipher = GetNewAeadBlockCipherInstance(); AeadParameters cipherParameters = GetParameters(key, nonce); try { cipher.Init(true, cipherParameters); int outputLen = cipher.GetOutputSize(input.Length); byte[] output = new byte[outputLen + nonce.Length]; int position = cipher.ProcessBytes(input, 0, input.Length, output, 0); try { cipher.DoFinal(output, position); } catch (Exception e) { throw new AppEncryptionException("unexpected error during encrypt cipher finalization", e); } AppendNonce(output, nonce); return(output); } finally { ManagedBufferUtils.WipeByteArray(cipherParameters.Key.GetKey()); } }
private void RunTestCase( IGcmMultiplier encM, IGcmMultiplier decM, string testName, byte[] K, byte[] IV, byte[] A, byte[] SA, byte[] P, byte[] C, byte[] T) { AeadParameters parameters = new AeadParameters(new KeyParameter(K), T.Length * 8, IV, A); GcmBlockCipher encCipher = InitCipher(encM, true, parameters); GcmBlockCipher decCipher = InitCipher(decM, false, parameters); CheckTestCase(encCipher, decCipher, testName, SA, P, C, T); encCipher = InitCipher(encM, true, parameters); CheckTestCase(encCipher, decCipher, testName + " (reused)", SA, P, C, T); // Key reuse AeadParameters keyReuseParams = AeadTestUtilities.ReuseKey(parameters); try { encCipher.Init(true, keyReuseParams); Fail("no exception"); } catch (ArgumentException e) { IsTrue("wrong message", "cannot reuse nonce for GCM encryption".Equals(e.Message)); } }
public byte[] Encrypt(byte[] message, byte[] nonSecret = null) { var nonce = new byte[NonceBitSize / 8]; _secureRandom.NextBytes(nonce, 0, nonce.Length); nonSecret = nonSecret ?? new byte[] { }; var cipher = new GcmBlockCipher(new AesEngine()); var parameters = new AeadParameters( new KeyParameter(_key), MacBitSize, nonce, nonSecret ); cipher.Init(true, parameters); var cipherText = new byte[cipher.GetOutputSize(message.Length)]; int len = cipher.ProcessBytes(message, 0, message.Length, cipherText, 0); cipher.DoFinal(cipherText, len); using var combinedStream = new MemoryStream(); using (var binaryWriter = new BinaryWriter(combinedStream)) { binaryWriter.Write(nonSecret); binaryWriter.Write(nonce); binaryWriter.Write(cipherText); } return(combinedStream.ToArray()); }
public static string Decrypt(string EncryptedText) { string sR = string.Empty; try { byte[] key = HexToByte("2143B39425BBD08B6E8E61C5D1E1BC9F428FC569FBC6F78C0BC48FCCDB0F89AE"); byte[] iv = HexToByte("E1E592E89225847C19D948684F3B070D"); byte[] encryptedBytes = Convert.FromBase64String(EncryptedText); GcmBlockCipher cipher = new GcmBlockCipher(new AesFastEngine()); AeadParameters parameters = new AeadParameters(new KeyParameter(key), 128, iv, null); //ParametersWithIV parameters = new ParametersWithIV(new KeyParameter(key), iv); cipher.Init(false, parameters); byte[] plainBytes = new byte[cipher.GetOutputSize(encryptedBytes.Length)]; Int32 retLen = cipher.ProcessBytes (encryptedBytes, 0, encryptedBytes.Length, plainBytes, 0); cipher.DoFinal(plainBytes, retLen); sR = Encoding.UTF8.GetString(plainBytes).TrimEnd("\r\n\0".ToCharArray()); } catch (Exception ex) { Console.WriteLine(ex.Message); } return(sR); }
private byte[] EncryptOrDecrypt(bool forEncryption, byte[] data, byte[] key, byte[] nonce) { if (ExpectedKeySize != key.Length) { throw new CryptoException("Invalid key size"); } if (ExpectedNonceSize != nonce.Length) { throw new CryptoException("Invalid nonce size"); } // We do the X-part of XChaCha20 and then use the ChaCha20 from bouncy castle byte[] subkey = new byte[KeySizeBytes]; ChaCha20Base.HChaCha20(subkey, key, nonce); byte[] chaChaNonce = CreateChaChaNonce(nonce); ICipherParameters aeadParams = new AeadParameters( new KeyParameter(subkey), MacSizeBytes * 8, chaChaNonce, null); IAeadCipher chaCha20Poly1305 = new ChaCha20Poly1305(); chaCha20Poly1305.Init(forEncryption, aeadParams); byte[] result = new byte[chaCha20Poly1305.GetOutputSize(data.Length)]; int len = chaCha20Poly1305.ProcessBytes(data, 0, data.Length, result, 0); chaCha20Poly1305.DoFinal(result, len); return(result); }
public static string Encrypt(string PlainText) { string sR = string.Empty; try { byte[] key = HexToByte("2143B39425BBD08B6E8E61C5D1E1BC9F428FC569FBC6F78C0BC48FCCDB0F89AE"); byte[] iv = HexToByte("E1E592E89225847C19D948684F3B070D"); byte[] plainBytes = Encoding.UTF8.GetBytes(PlainText); GcmBlockCipher cipher = new GcmBlockCipher(new AesFastEngine()); AeadParameters parameters = new AeadParameters(new KeyParameter(key), 128, iv, null); cipher.Init(true, parameters); byte[] encryptedBytes = new byte[cipher.GetOutputSize(plainBytes.Length)]; Int32 retLen = cipher.ProcessBytes (plainBytes, 0, plainBytes.Length, encryptedBytes, 0); cipher.DoFinal(encryptedBytes, retLen); sR = Convert.ToBase64String(encryptedBytes, Base64FormattingOptions.None); } catch (Exception ex) { Console.WriteLine(ex.Message); } return(sR); }
public virtual void Init(bool forEncryption, ICipherParameters parameters) { this.forEncryption = forEncryption; ICipherParameters cipherParameters; if (parameters is AeadParameters) { AeadParameters aeadParameters = (AeadParameters)parameters; this.nonce = aeadParameters.GetNonce(); this.initialAssociatedText = aeadParameters.GetAssociatedText(); this.macSize = aeadParameters.MacSize / 8; cipherParameters = aeadParameters.Key; } else { if (!(parameters is ParametersWithIV)) { throw new ArgumentException("invalid parameters passed to CCM"); } ParametersWithIV parametersWithIV = (ParametersWithIV)parameters; this.nonce = parametersWithIV.GetIV(); this.initialAssociatedText = null; this.macSize = this.macBlock.Length / 2; cipherParameters = parametersWithIV.Parameters; } if (cipherParameters != null) { this.keyParam = cipherParameters; } if (this.nonce == null || this.nonce.Length < 7 || this.nonce.Length > 13) { throw new ArgumentException("nonce must have length from 7 to 13 octets"); } this.Reset(); }
public string Encode(byte[] payload) { var nonceBytes = new byte[NonceBytes]; _rng.GetBytes(nonceBytes); var headerBytes = new byte[HeaderBytes]; Buffer.BlockCopy(_magicBytes, 0, headerBytes, 0, MagicBytes); Buffer.BlockCopy(nonceBytes, 0, headerBytes, MagicBytes, NonceBytes); var aead = new AeadParameters(_key, MacBytes * 8, nonceBytes, headerBytes); _gcmEngine.Init(true, aead); var cipherTextBytes = new byte[_gcmEngine.GetOutputSize(payload.Length)]; var pos = _gcmEngine.ProcessBytes(payload, 0, payload.Length, cipherTextBytes, 0); _gcmEngine.DoFinal(cipherTextBytes, pos); var result = new byte[HeaderBytes + cipherTextBytes.Length]; Buffer.BlockCopy(headerBytes, 0, result, 0, HeaderBytes); Buffer.BlockCopy(cipherTextBytes, 0, result, HeaderBytes, cipherTextBytes.Length); return(ToCompatBase64Url(result)); }
public MemoryStream Encrypt(MemoryStream data) { byte[] nonce = generateRandomBytes(SALT_LENGTH); GcmBlockCipher cipher = new GcmBlockCipher(new AesEngine()); AeadParameters parameters = new AeadParameters(new KeyParameter(this.key), TAG_LENGTH * 8, nonce, null); cipher.Init(true, parameters); var plaintext = data.ToArray(); byte[] ciphertext = new byte[cipher.GetOutputSize(plaintext.Length)]; int len = cipher.ProcessBytes(plaintext, 0, plaintext.Length, ciphertext, 0); cipher.DoFinal(ciphertext, len); // Assemble message var combinedStream = new MemoryStream(); var binaryWriter = new BinaryWriter(combinedStream); // Prepend Nonce binaryWriter.Write(nonce); // Write Cipher Text binaryWriter.Write(ciphertext); return(combinedStream); }
//decrypt with byte array private byte[] DecryptWithKey(byte[] message, byte[] key, int nonSecretPayloadLength = 0) { if (key == null || key.Length != KEY_BIT_SIZE / 8) { throw new ArgumentException(String.Format("Key needs to be {0} bit!", KEY_BIT_SIZE), "key"); } if (message == null || message.Length == 0) { throw new ArgumentException("Message required!", "message"); } using (var cipherStream = new MemoryStream(message)) using (var cipherReader = new BinaryReader(cipherStream)) { var nonSecretPayload = cipherReader.ReadBytes(nonSecretPayloadLength); var nonce = cipherReader.ReadBytes(NONCE_BIT_SIZE / 8); var cipher = new GcmBlockCipher(new AesEngine()); var parameters = new AeadParameters(new KeyParameter(key), MAC_BIT_SIZE, nonce, nonSecretPayload); cipher.Init(false, parameters); var cipherData = cipherReader.ReadBytes(message.Length - nonSecretPayloadLength - nonce.Length); var plainText = new byte[cipher.GetOutputSize(cipherData.Length)]; try { var len = cipher.ProcessBytes(cipherData, 0, cipherData.Length, plainText, 0); cipher.DoFinal(plainText, len); } catch (InvalidCipherTextException) { return(null); } return(plainText); } }
private byte[] DecryptWithKey(byte[] encryptedMessage, byte[] key, int nonSecretPayloadLength = 0) { //User Error Checks CheckKey(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(_nonceSize / 8); var cipher = new GcmBlockCipher(new AesEngine()); var parameters = new AeadParameters(new KeyParameter(key), _macSize, 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)]; var len = cipher.ProcessBytes(cipherText, 0, cipherText.Length, plainText, 0); cipher.DoFinal(plainText, len); return(plainText); } }
public virtual byte[] EncodePlaintext(long seqNo, byte type, byte[] plaintext, int offset, int len) { byte[] array = new byte[encryptImplicitNonce.Length + nonce_explicit_length]; Array.Copy(encryptImplicitNonce, 0, array, 0, encryptImplicitNonce.Length); TlsUtilities.WriteUint64(seqNo, array, encryptImplicitNonce.Length); int outputSize = encryptCipher.GetOutputSize(len); byte[] array2 = new byte[nonce_explicit_length + outputSize]; Array.Copy(array, encryptImplicitNonce.Length, array2, 0, nonce_explicit_length); int num = nonce_explicit_length; byte[] additionalData = GetAdditionalData(seqNo, type, len); AeadParameters parameters = new AeadParameters(null, 8 * macSize, array, additionalData); try { encryptCipher.Init(forEncryption: true, parameters); num += encryptCipher.ProcessBytes(plaintext, offset, len, array2, num); num += encryptCipher.DoFinal(array2, num); } catch (Exception alertCause) { throw new TlsFatalAlert(80, alertCause); } if (num != array2.Length) { throw new TlsFatalAlert(80); } return(array2); }