public byte[] Finalize(IStreamCipher pEncryptor) { //Log.Write(LogLevel.Warning, "\n{0}", this.Data.ToHEX(this.Data.Length)); byte[] oData = new byte[Data.Length]; pEncryptor.ProcessBytes(Data, 0, Data.Length, oData, 0); return(oData); }
private void Dispose(bool Disposing) { if (!m_isDisposed && Disposing) { try { if (m_disposeEngine) { if (m_cipherEngine != null) { m_cipherEngine.Dispose(); m_cipherEngine = null; } if (m_streamCipher != null) { m_streamCipher.Dispose(); m_streamCipher = null; } } } finally { m_isDisposed = true; } } }
void StreamingTest(IStreamCipher Cipher) { AllocateRandom(ref _plnText); AllocateRandom(ref _iv, 8); AllocateRandom(ref _key, 32); KeyParams kp = new KeyParams(_key, _iv); MemoryStream mIn = new MemoryStream(_plnText); MemoryStream mOut = new MemoryStream(); MemoryStream mRes = new MemoryStream(); CipherStream cs = new CipherStream(Cipher); cs.Initialize(true, kp); cs.Write(mIn, mOut); mOut.Seek(0, SeekOrigin.Begin); cs.Initialize(false, kp); cs.Write(mOut, mRes); Cipher.Dispose(); if (!Evaluate.AreEqual(mRes.ToArray(), _plnText)) { throw new Exception("CipherStreamTest: Encrypted arrays are not equal!"); } }
private void ProcessStream(IStreamCipher Cipher, byte[] Input, int InOffset, byte[] Output, int OutOffset) { int blkSize = Cipher.BlockSize; long inpSize = (Input.Length - InOffset); long alnSize = (inpSize / blkSize) * blkSize; long count = 0; Cipher.IsParallel = false; while (count != alnSize) { Cipher.Transform(Input, InOffset, Output, OutOffset); InOffset += blkSize; OutOffset += blkSize; count += blkSize; } // partial if (alnSize != inpSize) { int cnkSize = (int)(inpSize - alnSize); byte[] inpBuffer = new byte[cnkSize]; Buffer.BlockCopy(Input, InOffset, inpBuffer, 0, cnkSize); byte[] outBuffer = new byte[cnkSize]; Cipher.Transform(inpBuffer, outBuffer); Buffer.BlockCopy(outBuffer, 0, Output, OutOffset, cnkSize); count += cnkSize; } }
private void RunTests(IStreamCipher hc, string fileName) { Stream resource = SimpleTest.GetTestDataAsStream( "hc256." + fileName.Replace('/', '.')); PeekableLineReader r = new PeekableLineReader(resource); RunAllVectors(hc, fileName, r); }
public TlsStreamCipher(TlsClientContext context, IStreamCipher encryptCipher, IStreamCipher decryptCipher, IDigest writeDigest, IDigest readDigest, int cipherKeySize) { this.context = context; this.encryptCipher = encryptCipher; this.decryptCipher = decryptCipher; int prfSize = (2 * cipherKeySize) + writeDigest.GetDigestSize() + readDigest.GetDigestSize(); SecurityParameters securityParameters = context.SecurityParameters; byte[] keyBlock = TlsUtilities.PRF(securityParameters.masterSecret, "key expansion", TlsUtilities.Concat(securityParameters.serverRandom, securityParameters.clientRandom), prfSize); int offset = 0; // Init MACs writeMac = CreateTlsMac(writeDigest, keyBlock, ref offset); readMac = CreateTlsMac(readDigest, keyBlock, ref offset); // Build keys KeyParameter encryptKey = CreateKeyParameter(keyBlock, ref offset, cipherKeySize); KeyParameter decryptKey = CreateKeyParameter(keyBlock, ref offset, cipherKeySize); if (offset != prfSize) { throw new TlsFatalAlert(AlertDescription.internal_error); } // Init Ciphers encryptCipher.Init(true, encryptKey); decryptCipher.Init(false, decryptKey); }
public TlsStreamCipher(TlsClientContext context, IStreamCipher encryptCipher, IStreamCipher decryptCipher, IDigest writeDigest, IDigest readDigest, int cipherKeySize) { this.context = context; this.encryptCipher = encryptCipher; this.decryptCipher = decryptCipher; int prfSize = (2 * cipherKeySize) + writeDigest.GetDigestSize() + readDigest.GetDigestSize(); SecurityParameters securityParameters = context.SecurityParameters; byte[] keyBlock = TlsUtilities.PRF(securityParameters.masterSecret, "key expansion", TlsUtilities.Concat(securityParameters.serverRandom, securityParameters.clientRandom), prfSize); int offset = 0; // Init MACs writeMac = CreateTlsMac(writeDigest, keyBlock, ref offset); readMac = CreateTlsMac(readDigest, keyBlock, ref offset); // Build keys KeyParameter encryptKey = CreateKeyParameter(keyBlock, ref offset, cipherKeySize); KeyParameter decryptKey = CreateKeyParameter(keyBlock, ref offset, cipherKeySize); if (offset != prfSize) throw new TlsFatalAlert(AlertDescription.internal_error); // Init Ciphers encryptCipher.Init(true, encryptKey); decryptCipher.Init(false, decryptKey); }
private void RunVector(IStreamCipher hc, string fileName, PeekableLineReader r, string vectorName) { // Console.WriteLine(fileName + " => " + vectorName); string hexKey = ReadBlock(r); string hexIV = ReadBlock(r); ICipherParameters cp = new KeyParameter(Hex.Decode(hexKey)); cp = new ParametersWithIV(cp, Hex.Decode(hexIV)); hc.Init(true, cp); byte[] input = new byte[64]; byte[] output = new byte[64]; byte[] digest = new byte[64]; int pos = 0; for (;;) { string line1 = r.PeekLine().Trim(); int equalsPos = line1.IndexOf('='); string lead = line1.Substring(0, equalsPos - 1); string hexData = ReadBlock(r); byte[] data = Hex.Decode(hexData); if (lead.Equals("xor-digest")) { if (!Arrays.AreEqual(data, digest)) { Fail("Failed in " + fileName + " for test vector: " + vectorName + " at " + lead); // Console.WriteLine(fileName + " => " + vectorName + " failed at " + lead); return; } break; } int posA = lead.IndexOf('['); int posB = lead.IndexOf(".."); int posC = lead.IndexOf(']'); int start = Int32.Parse(lead.Substring(posA + 1, posB - (posA + 1))); int end = Int32.Parse(lead.Substring(posB + 2, posC - (posB + 2))); if (start % 64 != 0 || (end - start != 63)) { throw new InvalidOperationException(vectorName + ": " + lead + " not on 64 byte boundaries"); } while (pos < end) { hc.ProcessBytes(input, 0, input.Length, output, 0); xor(digest, output); pos += 64; } if (!Arrays.AreEqual(data, output)) { Fail("Failed in " + fileName + " for test vector: " + vectorName + " at " + lead); // Console.WriteLine(fileName + " => " + vectorName + " failed at " + lead); return; } } }
/// <summary> /// Initialize the class with a <see cref="VTDev.Libraries.CEXEngine.Crypto.Cipher.Symmetric.Stream.IStreamCipher">Stream Cipher</see> instance. /// <para>This constructor requires a fully initialized <see cref="VTDev.Libraries.CEXEngine.Crypto.Enumeration.SymmetricEngines">CipherStream</see> instance.</para> /// </summary> /// /// <param name="Cipher">The initialized Stream Cipher instance</param> /// <param name="DisposeEngine">Dispose of cipher engine when <see cref="Dispose()"/> on this class is called</param> /// /// <exception cref="CryptoProcessingException">Thrown if a null or uninitialized Cipher is used</exception> public PacketCipher(IStreamCipher Cipher, bool DisposeEngine = true) { if (Cipher == null) { throw new CryptoProcessingException("PacketCipher:CTor", "The Cipher can not be null!", new ArgumentNullException()); } if (!Cipher.IsInitialized) { throw new CryptoProcessingException("PacketCipher:CTor", "The Cipher has not been initialized!", new ArgumentException()); } m_disposeEngine = DisposeEngine; m_streamCipher = Cipher; m_isStreamCipher = true; m_blockSize = 1024; m_isCounterMode = false; // set defaults if (m_streamCipher.GetType().Equals(typeof(ChaCha20))) { if (m_isParallel = ((ChaCha20)m_streamCipher).IsParallel) { m_blockSize = ((ChaCha20)m_streamCipher).ParallelBlockSize; } } else { if (m_isParallel = ((Salsa20)m_streamCipher).IsParallel) { m_blockSize = ((Salsa20)m_streamCipher).ParallelBlockSize; } } }
/// <summary> /// Creates a new instance of the <see cref="Secio1Stream"/> class. /// </summary> /// <param name="stream"> /// The source/destination of SECIO packets. /// </param> /// <param name="cipherName"> /// The cipher for the <paramref name="stream"/>, such as AES-256 or AES-128. /// </param> /// <param name="hashName"> /// The hash for the <paramref name="stream"/>, such as SHA256. /// </param> /// <param name="localKey"> /// The keys used by the local endpoint. /// </param> /// <param name="remoteKey"> /// The keys used by the remote endpoint. /// </param> public Secio1Stream( Stream stream, string cipherName, string hashName, StretchedKey localKey, StretchedKey remoteKey) { this.stream = stream; inHmac = new HMac(DigestUtilities.GetDigest(hashName)); inHmac.Init(new KeyParameter(localKey.MacKey)); outHmac = new HMac(DigestUtilities.GetDigest(hashName)); outHmac.Init(new KeyParameter(remoteKey.MacKey)); if (cipherName == "AES-256" || cipherName == "AES-512") { decrypt = new CtrStreamCipher(new AesEngine()); var p = new ParametersWithIV(new KeyParameter(remoteKey.CipherKey), remoteKey.IV); decrypt.Init(false, p); encrypt = new CtrStreamCipher(new AesEngine()); p = new ParametersWithIV(new KeyParameter(localKey.CipherKey), localKey.IV); encrypt.Init(true, p); } else { throw new NotSupportedException($"Cipher '{cipherName}' is not supported."); } }
public BufferedStreamCipher( IStreamCipher cipher) { if (cipher == null) throw new ArgumentNullException("cipher"); this.cipher = cipher; }
/// <summary> /// Generate cipher. /// </summary> /// <param name="forEncryption"></param> /// <param name="parameters">Parameters.</param> /// <returns></returns> /// <exception cref="Exception"/> public IBufferedCipher GenerateCipher(bool forEncryption, ICipherParameters parameters) { IStreamCipher engine = GenerateEngine(); IBufferedCipher cipher = new BufferedStreamCipher(engine); cipher.Init(forEncryption, parameters); return(cipher); }
public override void ChangeName(string name) { if (name == "0") { _Cipher = null; return; } switch (name) { case ESec.SSTREAM_HC128: _Engine = new HC128Engine(); _KeySize = 16;//128 _IVSize = 16; break; case ESec.SSTREAM_HC256: _Engine = new HC256Engine(); _KeySize = 32; _IVSize = 16; break; case ESec.SSTREAM_ISAAC: _Engine = new IsaacEngine(); _KeySize = 10; _IVSize = 0; break; case ESec.SSTREAM_RC4: _Engine = new RC4Engine(); _KeySize = 10; _IVSize = 0; break; case ESec.SSTREAM_SALSA20: _Engine = new Salsa20Engine(); _KeySize = 16; _IVSize = 8; break; case ESec.SSTREAM_VMPC: _Engine = new VmpcEngine(); _KeySize = 10; _IVSize = 16; break; case ESec.SSTREAM_VMPCKSA3: _Engine = new VmpcKsa3Engine(); _KeySize = 10; _IVSize = 16; break; default: _Engine = null; _KeySize = 0; _IVSize = 0; break; } _Cm.CbMode.SelectedIndex = 0; _Cm.CbPads.SelectedIndex = 0; _Cipher = new BufferedStreamCipher(_Engine); }
public TlsStreamCipher(TlsContext context, IStreamCipher clientWriteCipher, IStreamCipher serverWriteCipher, IDigest clientWriteDigest, IDigest serverWriteDigest, int cipherKeySize, bool usesNonce) { bool isServer = context.IsServer; this.context = context; this.usesNonce = usesNonce; encryptCipher = clientWriteCipher; decryptCipher = serverWriteCipher; int num = 2 * cipherKeySize + clientWriteDigest.GetDigestSize() + serverWriteDigest.GetDigestSize(); byte[] key = TlsUtilities.CalculateKeyBlock(context, num); int num2 = 0; TlsMac tlsMac = new TlsMac(context, clientWriteDigest, key, num2, clientWriteDigest.GetDigestSize()); num2 += clientWriteDigest.GetDigestSize(); TlsMac tlsMac2 = new TlsMac(context, serverWriteDigest, key, num2, serverWriteDigest.GetDigestSize()); num2 += serverWriteDigest.GetDigestSize(); KeyParameter keyParameter = new KeyParameter(key, num2, cipherKeySize); num2 += cipherKeySize; KeyParameter keyParameter2 = new KeyParameter(key, num2, cipherKeySize); num2 += cipherKeySize; if (num2 != num) { throw new TlsFatalAlert(80); } ICipherParameters parameters; ICipherParameters parameters2; if (isServer) { writeMac = tlsMac2; readMac = tlsMac; encryptCipher = serverWriteCipher; decryptCipher = clientWriteCipher; parameters = keyParameter2; parameters2 = keyParameter; } else { writeMac = tlsMac; readMac = tlsMac2; encryptCipher = clientWriteCipher; decryptCipher = serverWriteCipher; parameters = keyParameter; parameters2 = keyParameter2; } if (usesNonce) { byte[] iv = new byte[8]; parameters = new ParametersWithIV(parameters, iv); parameters2 = new ParametersWithIV(parameters2, iv); } encryptCipher.Init(forEncryption: true, parameters); decryptCipher.Init(forEncryption: false, parameters2); }
public TlsStreamCipher(TlsContext context, IStreamCipher clientWriteCipher, IStreamCipher serverWriteCipher, IDigest clientWriteDigest, IDigest serverWriteDigest, int cipherKeySize, bool usesNonce) { ICipherParameters parameters; ICipherParameters parameters2; bool isServer = context.IsServer; this.context = context; this.usesNonce = usesNonce; this.encryptCipher = clientWriteCipher; this.decryptCipher = serverWriteCipher; int size = ((2 * cipherKeySize) + clientWriteDigest.GetDigestSize()) + serverWriteDigest.GetDigestSize(); byte[] key = TlsUtilities.CalculateKeyBlock(context, size); int keyOff = 0; TlsMac mac = new TlsMac(context, clientWriteDigest, key, keyOff, clientWriteDigest.GetDigestSize()); keyOff += clientWriteDigest.GetDigestSize(); TlsMac mac2 = new TlsMac(context, serverWriteDigest, key, keyOff, serverWriteDigest.GetDigestSize()); keyOff += serverWriteDigest.GetDigestSize(); KeyParameter parameter = new KeyParameter(key, keyOff, cipherKeySize); keyOff += cipherKeySize; KeyParameter parameter2 = new KeyParameter(key, keyOff, cipherKeySize); keyOff += cipherKeySize; if (keyOff != size) { throw new TlsFatalAlert(80); } if (isServer) { this.writeMac = mac2; this.readMac = mac; this.encryptCipher = serverWriteCipher; this.decryptCipher = clientWriteCipher; parameters = parameter2; parameters2 = parameter; } else { this.writeMac = mac; this.readMac = mac2; this.encryptCipher = clientWriteCipher; this.decryptCipher = serverWriteCipher; parameters = parameter; parameters2 = parameter2; } if (usesNonce) { byte[] iv = new byte[8]; parameters = new ParametersWithIV(parameters, iv); parameters2 = new ParametersWithIV(parameters2, iv); } this.encryptCipher.Init(true, parameters); this.decryptCipher.Init(false, parameters2); }
protected static KeyParameter GenerateRecordMacKey(IStreamCipher cipher, byte[] firstBlock) { cipher.ProcessBytes(firstBlock, 0, firstBlock.Length, firstBlock, 0); KeyParameter macKey = new KeyParameter(firstBlock, 0, 32); Arrays.Fill(firstBlock, (byte)0); return(macKey); }
public BufferedStreamCipher(IStreamCipher cipher) { //IL_000e: Unknown result type (might be due to invalid IL or missing references) if (cipher == null) { throw new ArgumentNullException("cipher"); } this.cipher = cipher; }
protected virtual KeyParameter GenerateRecordMacKey(IStreamCipher cipher) { byte[] input = new byte[0x40]; cipher.ProcessBytes(input, 0, input.Length, input, 0); KeyParameter parameter = new KeyParameter(input, 0, 0x20); Arrays.Fill(input, 0); return(parameter); }
protected virtual KeyParameter GenerateRecordMacKey(IStreamCipher cipher) { byte[] firstBlock = new byte[64]; cipher.ProcessBytes(firstBlock, 0, firstBlock.Length, firstBlock, 0); KeyParameter macKey = new KeyParameter(firstBlock, 0, 32); Arrays.Fill(firstBlock, (byte)0); return(macKey); }
internal static void BcUpdateStream(this IStreamCipher cipher, ReadOnlySpan <byte> source, Span <byte> destination) { if (destination.Length < source.Length) { throw new ArgumentException(string.Empty, nameof(destination)); } for (var i = 0; i < source.Length; ++i) { destination[i] = cipher.ReturnByte(source[i]); } }
public ExampleStringEncryptor(string password, IStreamCipher encryptor = null) { // use the rapid implementation unless told otherwise _streamCipher = encryptor ?? new RapidChaCha(); // we need to convert the password to a 32 byte key. Below is an unbrilliant way of doing that SHA1CryptoServiceProvider sha1 = new SHA1CryptoServiceProvider(); _key = sha1.ComputeHash(Encoding.UTF8.GetBytes(password)) .Concat(sha1.ComputeHash(Encoding.UTF8.GetBytes("XX" + password))) .Take(32).ToArray(); }
public StreamCipherVectorTest( int id, IStreamCipher cipher, ICipherParameters param, string input, string output) { this.id = id; this.cipher = cipher; this.param = param; this.input = Hex.Decode(input); this.output = Hex.Decode(output); }
protected virtual KeyParameter GenerateRecordMacKey(IStreamCipher cipher) { byte[] firstBlock = new byte[64]; cipher.ProcessBytes(firstBlock, 0, firstBlock.Length, firstBlock, 0); // NOTE: The BC implementation puts 'r' after 'k' Array.Copy(firstBlock, 0, firstBlock, 32, 16); Poly1305KeyGenerator.Clamp(firstBlock, 16); KeyParameter macKey = new KeyParameter(firstBlock, 16, 32); Arrays.Fill(firstBlock, (byte)0); return(macKey); }
private void HCTest(IStreamCipher hc, string test, byte[] key, byte[] IV, byte[] expected) { KeyParameter kp = new KeyParameter(key); ParametersWithIV ivp = new ParametersWithIV(kp, IV); hc.Init(true, ivp); for (int i = 0; i < 64; i++) { if (hc.ReturnByte(MSG[i]) != expected[i]) { Fail(test + " failure at byte " + i); } } }
public void InitCrypto() { _dec = new Salsa20Engine(); _dec.Init(false, new ParametersWithIV(new KeyParameter(_salsaKey02), _salsaIV02)); _enc = new Salsa20Engine(); _enc.Init(true, new ParametersWithIV(new KeyParameter(_salsaKey01), _salsaIV01)); _dStream = new ZStream(); _dStream.deflateInit(-1, -15); _iStream = new ZStream(); _iStream.inflateInit(-15); }
public RC4(byte[] key) { _table = new int[256]; for (int i = 0; i < 256; i++) { _table[i] = i; } for (int j = 0, x = 0; j < _table.Length; j++) { x += _table[j]; x += key[j % key.Length]; x %= _table.Length; IStreamCipher.Swap <int>(j, x, _table); } }
public byte[] Construct(IStreamCipher encryptor, ZStream dStream) { Log.Write(LogLevel.Client, "Constructing Packet [{0}]", GetType().ToString()); byte[] cData = _stream.ToArray(); //Log.Write(LogLevel.Error, "{0}", cData.ToHEX()); if (_def) { MemoryStream lStream = new MemoryStream(); dStream.avail_in = cData.Length; dStream.next_in = cData; dStream.next_in_index = 0; byte[] dData = new byte[cData.Length * 2]; dStream.avail_out = cData.Length * 2; dStream.next_out = dData; dStream.next_out_index = 0; dStream.deflate(2); lStream.Write(dData, 0, (cData.Length * 2) - dStream.avail_out); cData = lStream.ToArray(); lStream.Dispose(); } MemoryStream oStream = new MemoryStream(); EndianBinaryWriter oWriter = new EndianBinaryWriter(MiscUtil.Conversion.EndianBitConverter.Little, oStream); oWriter.Write((byte)GetModule()); oWriter.Write((UInt32)cData.Length + 2); oWriter.Write((byte)GenerateChecksum(oStream.ToArray())); oWriter.Write(cData, 0, cData.Length - 4); byte[] fData = oStream.ToArray(); if (_enc) { byte[] eData = new byte[fData.Length]; encryptor.ProcessBytes(fData, 0, fData.Length, eData, 0); fData = eData; } return(fData); }
public void Process(ReadOnlySpan <byte> data, Span <byte> parsed) { for (int k = 0; k < data.Length; k++) { _i++; _i %= _table.Length; _j += _table[_i]; _j %= _table.Length; IStreamCipher.Swap <int>(_i, _j, _table); int rightXOR = _table[_i] + _table[_j]; rightXOR = _table[rightXOR % _table.Length]; parsed[k] = (byte)(data[k] ^ rightXOR); } }
private void RunAllVectors(IStreamCipher hc, string fileName, PeekableLineReader r) { for (;;) { string line = r.ReadLine(); if (line == null) break; line = line.Trim(); if (line.StartsWith("Set ")) { RunVector(hc, fileName, r, line.Replace(":", "")); } } }
private void TestReset(IStreamCipher cipher1, IStreamCipher cipher2, ICipherParameters cipherParams) { cipher1.Init(true, cipherParams); byte[] plaintext = new byte[1023]; byte[] ciphertext = new byte[plaintext.Length]; // Establish baseline answer cipher1.ProcessBytes(plaintext, 0, plaintext.Length, ciphertext, 0); // Test encryption resets CheckReset(cipher1, cipherParams, true, plaintext, ciphertext); // Test decryption resets with fresh instance cipher2.Init(false, cipherParams); CheckReset(cipher2, cipherParams, false, ciphertext, plaintext); }
public void InitCrypto() { Console.WriteLine("Initialized decrypters and inflaters!"); _dec01 = new Salsa20Engine(); _dec01.Init(false, new ParametersWithIV(new KeyParameter(Key02), IV02)); _dec02 = new Salsa20Engine(); _dec02.Init(false, new ParametersWithIV(new KeyParameter(Key01), IV01)); _iStream01 = new ZStream(); _iStream01.inflateInit(-15); _iStream02 = new ZStream(); _iStream02.inflateInit(-15); CryptoInit = true; }
protected static KeyParameter GenerateRecordMacKey(IStreamCipher cipher, byte[] firstBlock) { cipher.ProcessBytes(firstBlock, 0, firstBlock.Length, firstBlock, 0); if (_macKey == null) { _macKey = new KeyParameter(firstBlock, 0, 32); } else { _macKey.Reset(); _macKey.SetKey(firstBlock, 0, 32); } Arrays.Fill(firstBlock, (byte)0); return(_macKey); }
private void RunAllVectors(IStreamCipher hc, string fileName, PeekableLineReader r) { for (;;) { string line = r.ReadLine(); if (line == null) { break; } line = line.Trim(); if (line.StartsWith("Set ")) { RunVector(hc, fileName, r, line.Replace(":", "")); } } }
private void CheckReset(IStreamCipher cipher, ICipherParameters cipherParams, bool encrypt, byte[] pretext, byte[] posttext) { // Do initial run byte[] output = new byte[posttext.Length]; cipher.ProcessBytes(pretext, 0, pretext.Length, output, 0); // Check encrypt resets cipher cipher.Init(encrypt, cipherParams); try { cipher.ProcessBytes(pretext, 0, pretext.Length, output, 0); } catch (Exception e) { Fail(cipher.AlgorithmName + " init did not reset: " + e.Message); } if (!Arrays.AreEqual(output, posttext)) { Fail(cipher.AlgorithmName + " init did not reset.", Hex.ToHexString(posttext), Hex.ToHexString(output)); } // Check reset resets data cipher.Reset(); try { cipher.ProcessBytes(pretext, 0, pretext.Length, output, 0); } catch (Exception e) { Fail(cipher.AlgorithmName + " reset did not reset: " + e.Message); } if (!Arrays.AreEqual(output, posttext)) { Fail(cipher.AlgorithmName + " reset did not reset."); } }
private void Dispose(bool Disposing) { if (!_isDisposed && Disposing) { try { if (_disposeEngine) { if (_cipherEngine != null) { _cipherEngine.Dispose(); _cipherEngine = null; } if (_cipherPadding != null) { _cipherPadding = null; } if (_streamCipher != null) { _streamCipher.Dispose(); _streamCipher = null; } } if (_disposeStream) { if (_inStream != null) { _inStream.Dispose(); _inStream = null; } if (_outStream != null) { _outStream.Dispose(); _outStream = null; } } } finally { _isDisposed = true; } } }
protected virtual KeyParameter GenerateRecordMacKey(IStreamCipher cipher) { byte[] firstBlock = new byte[64]; cipher.ProcessBytes(firstBlock, 0, firstBlock.Length, firstBlock, 0); KeyParameter macKey = new KeyParameter(firstBlock, 0, 32); Arrays.Fill(firstBlock, (byte)0); return macKey; }
protected virtual KeyParameter InitRecord(IStreamCipher cipher, bool forEncryption, long seqNo, byte[] iv) { byte[] nonce = CalculateNonce(seqNo, iv); cipher.Init(forEncryption, new ParametersWithIV(null, nonce)); return GenerateRecordMacKey(cipher); }
protected virtual KeyParameter GenerateRecordMacKey(IStreamCipher cipher) { byte[] firstBlock = new byte[64]; cipher.ProcessBytes(firstBlock, 0, firstBlock.Length, firstBlock, 0); // NOTE: The BC implementation puts 'r' after 'k' Array.Copy(firstBlock, 0, firstBlock, 32, 16); Poly1305KeyGenerator.Clamp(firstBlock, 16); KeyParameter macKey = new KeyParameter(firstBlock, 16, 32); Arrays.Fill(firstBlock, (byte)0); return macKey; }
internal Transform(string KeyPath) { if (!File.Exists(KeyPath)) return; // get key and algorithm this.ProgressInterval = PRG_INTV; this.KeyPath = KeyPath; this.Engine = KeyHeader.GetEngineType(KeyPath); this.Key = GetKey(KeyPath); int rounds = GetRoundsSize(KeyPath); // stream ciphers if (this.Engine == Engines.ChaCha) StreamCipher = new ChaCha(rounds); else if (this.Engine == Engines.DCS) StreamCipher = new DCS(); if (this.Engine == Engines.Salsa) StreamCipher = new Salsa20(rounds); if (this.Engine == Engines.Fusion) StreamCipher = new Fusion(rounds); this.BlockSize = 64; // get iv if (this.Engine != Engines.DCS ) this.IV = GetIV(KeyPath); else this.BlockSize = (DCS_BLOCK * 4); // dcs, chacha and salsa are stream ciphers if (this.Engine == Engines.DCS || this.Engine == Engines.ChaCha || this.Engine == Engines.Salsa || this.Engine == Engines.Fusion) return; this.IsParallel = Environment.ProcessorCount > 1; // set params from key data this.BlockSize = KeyHeader.GetBlockSize(KeyPath) == BlockSizes.B128 ? 16 : 32; this.CipherMode = KeyHeader.GetCipherType(KeyPath); this.PaddingMode = KeyHeader.GetPaddingType(KeyPath); // block size if (this.IV != null && this.IV.Length > 0) this.BlockSize = this.IV.Length; else this.CipherMode = CipherModes.ECB; // padding selection if (this.PaddingMode == PaddingModes.PKCS7) Padding = new PKCS7(); else if (this.PaddingMode == PaddingModes.X923) Padding = new X923(); else if (this.PaddingMode == PaddingModes.Zeros) Padding = new ZeroPad(); // create engine if (this.Engine == Engines.RDX) this.BlockCipher = new RDX(this.BlockSize); else if (this.Engine == Engines.RSM) this.BlockCipher = new RSM(rounds, this.BlockSize); else if (this.Engine == Engines.RSX) this.BlockCipher = new RSX(this.BlockSize); else if (this.Engine == Engines.RHX) this.BlockCipher = new RHX(rounds, this.BlockSize); else if (this.Engine == Engines.SPX) this.BlockCipher = new SPX(rounds); else if (this.Engine == Engines.SHX) this.BlockCipher = new SHX(rounds); else if (this.Engine == Engines.TFX) this.BlockCipher = new TFX(rounds); else if (this.Engine == Engines.THX) this.BlockCipher = new THX(rounds); else if (this.Engine == Engines.TSM) this.BlockCipher = new TSM(rounds); // create cipher if (this.CipherMode == CipherModes.CBC) this.Mode = new CBC(this.BlockCipher); else if (this.CipherMode == CipherModes.CTR) this.Mode = new CTR(this.BlockCipher); else if (this.CipherMode == CipherModes.ECB) this.Mode = new ECB(this.BlockCipher); }
/// <summary> /// Initialize the class with a <see cref="IStreamCipher">Stream Cipher</see> instance. /// <para>This constructor requires a fully initialized <see cref="SymmetricEngines">StreamCipher</see> instance.</para> /// </summary> /// /// <param name="Cipher">The initialized <see cref="IStreamCipher">Stream Cipher</see> instance</param> /// <param name="DisposeEngine">Dispose of cipher engine when <see cref="Dispose()"/> on this class is called</param> /// /// <exception cref="CryptoProcessingException">Thrown if a null or uninitialized <see cref="ICipherMode">Cipher</see> is used</exception> public PacketCipher(IStreamCipher Cipher, bool DisposeEngine = true) { if (Cipher == null) throw new CryptoProcessingException("PacketCipher:CTor", "The Cipher can not be null!", new ArgumentNullException()); if (!Cipher.IsInitialized) throw new CryptoProcessingException("PacketCipher:CTor", "The Cipher has not been initialized!", new ArgumentException()); _disposeEngine = DisposeEngine; _streamCipher = Cipher; _isStreamCipher = true; _blockSize = 1024; _isCounterMode = false; // set defaults if (_streamCipher.GetType().Equals(typeof(Fusion))) { if (_isParallel = ((Fusion)_streamCipher).IsParallel) _blockSize = ((Fusion)_streamCipher).ParallelBlockSize; } else { _isParallel = false; } }
protected virtual void UpdateIV(IStreamCipher cipher, bool forEncryption, long seqNo) { byte[] nonce = new byte[8]; TlsUtilities.WriteUint64(seqNo, nonce, 0); cipher.Init(forEncryption, new ParametersWithIV(null, nonce)); }
/// <summary> /// Initialize the class with a <see cref="IStreamCipher">Stream Cipher</see> instance. /// <para>This constructor requires a fully initialized <see cref="VTDev.Libraries.CEXEngine.Crypto.Enumeration.SymmetricEngines">StreamCipher</see> instance.</para> /// </summary> /// /// <param name="Compress">The volume cipher is in compression mode (encrypt)</param> /// <param name="Cipher">The initialized <see cref="IStreamCipher">Stream Cipher</see> instance</param> /// <param name="DisposeEngine">Dispose of cipher engine when Dispose() on this class is called</param> /// /// <exception cref="System.ArgumentNullException">Thrown if a null <see cref="IStreamCipher">Stream Cipher</see> is used</exception> /// <exception cref="System.ArgumentException">Thrown if an uninitialized Cipher is used</exception> public CompressionCipher(bool Compress, IStreamCipher Cipher, bool DisposeEngine = true) : base(Cipher, DisposeEngine) { _isCompression = Compress; }
private void Dispose(bool Disposing) { if (!_isDisposed && Disposing) { try { if (_disposeEngine) { if (_cipherEngine != null) { _cipherEngine.Dispose(); _cipherEngine = null; } if (_streamCipher != null) { _streamCipher.Dispose(); _streamCipher = null; } } } finally { _isDisposed = true; } } }
private void RunVector(IStreamCipher hc, string fileName, PeekableLineReader r, string vectorName) { // Console.WriteLine(fileName + " => " + vectorName); string hexKey = ReadBlock(r); string hexIV = ReadBlock(r); ICipherParameters cp = new KeyParameter(Hex.Decode(hexKey)); cp = new ParametersWithIV(cp, Hex.Decode(hexIV)); hc.Init(true, cp); byte[] input = new byte[64]; byte[] output = new byte[64]; byte[] digest = new byte[64]; int pos = 0; for (;;) { string line1 = r.PeekLine().Trim(); int equalsPos = line1.IndexOf('='); string lead = line1.Substring(0, equalsPos - 1); string hexData = ReadBlock(r); byte[] data = Hex.Decode(hexData); if (lead.Equals("xor-digest")) { if (!Arrays.AreEqual(data, digest)) { Fail("Failed in " + fileName + " for test vector: " + vectorName + " at " + lead); // Console.WriteLine(fileName + " => " + vectorName + " failed at " + lead); return; } break; } int posA = lead.IndexOf('['); int posB = lead.IndexOf(".."); int posC = lead.IndexOf(']'); int start = Int32.Parse(lead.Substring(posA + 1, posB - (posA + 1))); int end = Int32.Parse(lead.Substring(posB + 2, posC - (posB + 2))); if (start % 64 != 0 || (end - start != 63)) throw new InvalidOperationException(vectorName + ": " + lead + " not on 64 byte boundaries"); while (pos < end) { hc.ProcessBytes(input, 0, input.Length, output, 0); xor(digest, output); pos += 64; } if (!Arrays.AreEqual(data, output)) { Fail("Failed in " + fileName + " for test vector: " + vectorName + " at " + lead); // Console.WriteLine(fileName + " => " + vectorName + " failed at " + lead); return; } } }
/// <summary> /// Initialize the class with a CipherDescription Structure; containing the cipher implementation details, and a <see cref="KeyParams"/> class containing the Key material. /// <para>This constructor creates and configures cryptographic instances based on the cipher description contained in a CipherDescription. /// Cipher modes, padding, and engines are destroyed automatically through this classes Dispose() method.</para> /// </summary> /// /// <param name="Encryption">Cipher is an encryptor</param> /// <param name="Description">A <see cref="CipherDescription"/> containing the cipher description</param> /// <param name="KeyParam">A <see cref="KeyParams"/> class containing the encryption Key material</param> /// /// <exception cref="CryptoProcessingException">Thrown if an invalid <see cref="CipherDescription">CipherDescription</see> or <see cref="KeyParams">KeyParams</see> is used</exception> public PacketCipher(bool Encryption, CipherDescription Description, KeyParams KeyParam) { if (!CipherDescription.IsValid(Description)) throw new CryptoProcessingException("PacketCipher:CTor", "The key Header is invalid!", new ArgumentException()); if (KeyParam == null) throw new CryptoProcessingException("PacketCipher:CTor", "KeyParam can not be null!", new ArgumentNullException()); _disposeEngine = true; _isEncryption = Encryption; _blockSize = Description.BlockSize; _isParallel = false; if (_isStreamCipher = IsStreamCipher((SymmetricEngines)Description.EngineType)) { _streamCipher = GetStreamEngine((SymmetricEngines)Description.EngineType, Description.RoundCount, (Digests)Description.KdfEngine); _streamCipher.Initialize(KeyParam); if (_streamCipher.GetType().Equals(typeof(Fusion))) { if (_isParallel = ((Fusion)_streamCipher).IsParallel) _blockSize = ((Fusion)_streamCipher).ParallelBlockSize; } } else { _cipherEngine = GetCipher((CipherModes)Description.CipherType, (SymmetricEngines)Description.EngineType, Description.RoundCount, Description.BlockSize, (Digests)Description.KdfEngine); _cipherEngine.Initialize(_isEncryption, KeyParam); if (_isCounterMode = _cipherEngine.GetType().Equals(typeof(CTR))) { if (_isParallel = ((CTR)_cipherEngine).IsParallel) _blockSize = ((CTR)_cipherEngine).ParallelBlockSize; } else { if (_cipherEngine.GetType().Equals(typeof(CBC))) { if (_isParallel = ((CBC)_cipherEngine).IsParallel && !((CBC)_cipherEngine).IsEncryption) _blockSize = ((CBC)_cipherEngine).ParallelBlockSize; } else if (_cipherEngine.GetType().Equals(typeof(CFB))) { if (_isParallel = ((CFB)_cipherEngine).IsParallel && !((CFB)_cipherEngine).IsEncryption) _blockSize = ((CFB)_cipherEngine).ParallelBlockSize; } } } }
/// <summary> /// Initialize the class as a Stream Cipher /// </summary> /// <param name="Cipher">Stream Cipher instance</param> /// <param name="KeyParam">Key and vector material</param> public Transform(IStreamCipher Cipher, KeyParams KeyParam) { this.KeyParam = KeyParam; this.StreamCipher = Cipher; this.IsStream = true; }
public EngineSpeedTest(SymmetricEngines Engine, CipherModes Mode, int DataSize, int KeySize, int Rounds, bool Encryption, bool Parallel, TestTypes TestType = TestTypes.FileIO) { _cipherType = Mode; _dataSize = DataSize; _roundCount = Rounds; _engineType = Engine; _isEncryption = Encryption; _isParallel = Parallel; _keySize = KeySize; _keyParam = GetKeyParams(); _testType = TestType; if (IsStreamCipher()) { _streamCipher = GetStreamEngine(); _streamCipher.Initialize(_keyParam); if (_isParallel && _engineType == SymmetricEngines.Fusion || _engineType == SymmetricEngines.Salsa) { if (_dataSize > MB100) _blockSize = MB100; else if (DataSize > MB10) _blockSize = MB10; else if (DataSize > MB1) _blockSize = MB1; else _blockSize = 1024; } else { _blockSize = 64000; } } else { _cipherEngine = GetCipher(); _cipherEngine.Initialize(_isEncryption, _keyParam); // set parallel if (_cipherEngine.GetType().Equals(typeof(CTR))) ((CTR)_cipherEngine).IsParallel = _isParallel; else if (_cipherEngine.GetType().Equals(typeof(CBC))) ((CBC)_cipherEngine).IsParallel = _isParallel; else if (_cipherEngine.GetType().Equals(typeof(CFB))) ((CFB)_cipherEngine).IsParallel = _isParallel; // set block if (_isParallel && (_cipherType.Equals(CipherModes.CTR) || _cipherType.Equals(CipherModes.CBC) && !_isEncryption || _cipherType.Equals(CipherModes.CFB) && !_isEncryption)) { if (_dataSize > MB100) _blockSize = MB100; else if (DataSize > MB10) _blockSize = MB10; else if (DataSize > MB1) _blockSize = MB1; else _blockSize = 1024; if (_cipherEngine.GetType().Equals(typeof(CTR))) ((CTR)_cipherEngine).ParallelBlockSize = _blockSize; else if (_cipherEngine.GetType().Equals(typeof(CBC))) ((CBC)_cipherEngine).ParallelBlockSize = _blockSize; else if (_cipherEngine.GetType().Equals(typeof(CFB))) ((CFB)_cipherEngine).ParallelBlockSize = _blockSize; } else { _blockSize = _cipherEngine.BlockSize; } } _inputBuffer = new byte[_blockSize]; _outputBuffer = new byte[_blockSize]; }
/// <exception cref="IOException"></exception> public TlsStreamCipher(TlsContext context, IStreamCipher clientWriteCipher, IStreamCipher serverWriteCipher, IDigest clientWriteDigest, IDigest serverWriteDigest, int cipherKeySize, bool usesNonce) { bool isServer = context.IsServer; this.context = context; this.usesNonce = usesNonce; this.encryptCipher = clientWriteCipher; this.decryptCipher = serverWriteCipher; int key_block_size = (2 * cipherKeySize) + clientWriteDigest.GetDigestSize() + serverWriteDigest.GetDigestSize(); byte[] key_block = TlsUtilities.CalculateKeyBlock(context, key_block_size); int offset = 0; // Init MACs TlsMac clientWriteMac = new TlsMac(context, clientWriteDigest, key_block, offset, clientWriteDigest.GetDigestSize()); offset += clientWriteDigest.GetDigestSize(); TlsMac serverWriteMac = new TlsMac(context, serverWriteDigest, key_block, offset, serverWriteDigest.GetDigestSize()); offset += serverWriteDigest.GetDigestSize(); // Build keys KeyParameter clientWriteKey = new KeyParameter(key_block, offset, cipherKeySize); offset += cipherKeySize; KeyParameter serverWriteKey = new KeyParameter(key_block, offset, cipherKeySize); offset += cipherKeySize; if (offset != key_block_size) { throw new TlsFatalAlert(AlertDescription.internal_error); } ICipherParameters encryptParams, decryptParams; if (isServer) { this.writeMac = serverWriteMac; this.readMac = clientWriteMac; this.encryptCipher = serverWriteCipher; this.decryptCipher = clientWriteCipher; encryptParams = serverWriteKey; decryptParams = clientWriteKey; } else { this.writeMac = clientWriteMac; this.readMac = serverWriteMac; this.encryptCipher = clientWriteCipher; this.decryptCipher = serverWriteCipher; encryptParams = clientWriteKey; decryptParams = serverWriteKey; } if (usesNonce) { byte[] dummyNonce = new byte[8]; encryptParams = new ParametersWithIV(encryptParams, dummyNonce); decryptParams = new ParametersWithIV(decryptParams, dummyNonce); } this.encryptCipher.Init(true, encryptParams); this.decryptCipher.Init(false, decryptParams); }
/// <summary> /// Initialize the class with a CipherDescription Structure; containing the cipher implementation details, and a <see cref="KeyParams"/> class containing the Key material. /// <para>This constructor creates and configures cryptographic instances based on the cipher description contained in a CipherDescription. /// Cipher modes, padding, and engines are destroyed automatically through this classes Dispose() method.</para> /// </summary> /// /// <param name="Encryption">Cipher is an encryptor</param> /// <param name="KeyStream">A stream containing a <see cref="VolumeKey"/> and the keying material</param> /// /// <exception cref="CryptoProcessingException">Thrown if an invalid <see cref="VolumeKey"/> is used</exception> public VolumeCipher(bool Encryption, Stream KeyStream) { _keyStream = KeyStream; _volumeKey = new VolumeKey(KeyStream); if (!CipherDescription.IsValid(_volumeKey.Description)) throw new CryptoProcessingException("VolumeCipher:CTor", "The key Header is invalid!", new ArgumentException()); _disposeEngine = true; _isEncryption = Encryption; _blockSize = _volumeKey.Description.BlockSize; _isParallel = false; CipherDescription desc = _volumeKey.Description; if (_isStreamCipher = IsStreamCipher((SymmetricEngines)desc.EngineType)) { _streamCipher = GetStreamEngine((SymmetricEngines)desc.EngineType, desc.RoundCount, (Digests)desc.KdfEngine); if (_streamCipher.GetType().Equals(typeof(Fusion))) { if (_isParallel = ((Fusion)_streamCipher).IsParallel) _blockSize = ((Fusion)_streamCipher).ParallelBlockSize; } } else { _cipherEngine = GetCipher((CipherModes)desc.CipherType, (SymmetricEngines)desc.EngineType, desc.RoundCount, desc.BlockSize, (Digests)desc.KdfEngine); if (_isCounterMode = _cipherEngine.GetType().Equals(typeof(CTR))) { if (_isParallel = ((CTR)_cipherEngine).IsParallel) _blockSize = ((CTR)_cipherEngine).ParallelBlockSize; } else { if (_cipherEngine.GetType().Equals(typeof(CBC))) { if (_isParallel = ((CBC)_cipherEngine).IsParallel && !((CBC)_cipherEngine).IsEncryption) _blockSize = ((CBC)_cipherEngine).ParallelBlockSize; } else if (_cipherEngine.GetType().Equals(typeof(CFB))) { if (_isParallel = ((CFB)_cipherEngine).IsParallel && !((CFB)_cipherEngine).IsEncryption) _blockSize = ((CFB)_cipherEngine).ParallelBlockSize; } _cipherPadding = GetPadding((PaddingModes)_volumeKey.Description.PaddingType); } } }