private void DescriptionTest(CipherDescription Description) { AllocateRandom(ref _iv, 16); AllocateRandom(ref _key, 32); AllocateRandom(ref _plnText); KeyParams kp = new KeyParams(_key, _iv); MemoryStream mIn = new MemoryStream(_plnText); MemoryStream mOut = new MemoryStream(); MemoryStream mRes = new MemoryStream(); CipherStream cs = new CipherStream(Description); cs.Initialize(true, kp); cs.Write(mIn, mOut); mOut.Seek(0, SeekOrigin.Begin); cs.Initialize(false, kp); cs.Write(mOut, mRes); if (!Evaluate.AreEqual(mRes.ToArray(), _plnText)) { throw new Exception("CipherStreamTest: Encrypted arrays are not equal!"); } }
public override void Write( byte[] bytes, int off, int len) { _out.Write(bytes, off, len); }
public void Close() { if (cOut != null) { if (digestOut != null) { BcpgOutputStream bcpgOutputStream = new BcpgOutputStream(digestOut, PacketTag.ModificationDetectionCode, 20L); bcpgOutputStream.Flush(); digestOut.Flush(); byte[] array = DigestUtilities.DoFinal(digestOut.WriteDigest()); cOut.Write(array, 0, array.Length); } cOut.Flush(); try { pOut.Write(c.DoFinal()); pOut.Finish(); } catch (Exception ex) { throw new IOException(ex.Message, ex); } cOut = null; pOut = null; } }
protected void RunSegmentedVectorTest(int number, SegmentedVectorTestCase testCase) { CipherConfiguration config = GetCipherConfiguration(testCase); var plaintext = new byte[testCase.IV.Length]; TestVectorSegment lastSegment = testCase.Segments.Last(); int requiredCiphertextLength = lastSegment.Offset + lastSegment.Length; var msCiphertext = new MemoryStream(); using (var cs = new CipherStream(msCiphertext, true, config, testCase.Key, false)) { while (cs.BytesOut < requiredCiphertextLength) { cs.Write(plaintext, 0, plaintext.Length); } } // Now we analyse the ciphertext segment-wise foreach (var segment in testCase.Segments) { msCiphertext.Seek(segment.Offset, SeekOrigin.Begin); var segmentCiphertext = new byte[segment.Length]; msCiphertext.Read(segmentCiphertext, 0, segment.Length); byte[] referenceCiphertext = segment.Ciphertext; // Validate the segment Assert.IsTrue(referenceCiphertext.SequenceEqualShortCircuiting(segmentCiphertext), "Segmented vector test #{0} (\"{1}\") failed at segment {2}!", number, testCase.Name, segment.Name); } }
void StreamModesTest(ICipherMode Cipher, IPadding Padding) { if (Cipher.Engine.LegalKeySizes[0] > 32) { AllocateRandom(ref _key, 192); } else { AllocateRandom(ref _key, 32); } AllocateRandom(ref _iv, 16); // we are testing padding modes, make sure input size is random, but -not- block aligned.. AllocateRandom(ref _plnText, 0, Cipher.BlockSize); KeyParams kp = new KeyParams(_key, _iv); MemoryStream mIn = new MemoryStream(_plnText); MemoryStream mOut = new MemoryStream(); MemoryStream mRes = new MemoryStream(); CipherStream cs = new CipherStream(Cipher, Padding); cs.Initialize(true, kp); cs.Write(mIn, mOut); cs.Initialize(false, kp); mOut.Seek(0, SeekOrigin.Begin); cs.Write(mOut, mRes); int pos = (int)mRes.Position; byte[] res = new byte[_plnText.Length]; Buffer.BlockCopy(mRes.ToArray(), 0, res, 0, pos); if (!Evaluate.AreEqual(res, _plnText)) { throw new Exception("CipherStreamTest: Encrypted arrays are not equal!"); } Cipher.Dispose(); }
/// <summary> /// Decrypt a single file in the volume /// </summary> /// /// <param name="InputPath">The path to the encrypted file</param> /// <param name="OututPath">The path to the new decrypted file</param> public void Decrypt(string InputPath, string OututPath) { FileStream inpStream = GetStream(InputPath, true); VolumeHeader vh = GetHeader(inpStream); KeyParams key = VolumeKey.FromId(m_keyStream, vh.FileId); if (key == null) { if (ErrorNotification != null) { ErrorNotification(this, string.Format("The file {0}; has no key assigned", InputPath)); } } else { FileStream outStream = GetStream(OututPath, false); if (inpStream == null || outStream == null) { if (ErrorNotification != null) { ErrorNotification(this, string.Format("The file {0}; could not be written to", OututPath)); } } else { m_volumeKey.State[m_volumeKey.GetIndex(vh.FileId)] = (byte)VolumeKeyStates.Decrypted; m_cipherStream.ProgressPercent += OnCipherProgress; m_cipherStream.Initialize(false, key); m_cipherStream.Write(inpStream, outStream); m_cipherStream.ProgressPercent -= OnCipherProgress; outStream.SetLength(outStream.Length - VolumeHeader.GetHeaderSize); inpStream.Dispose(); outStream.Dispose(); UpdateKey(); } } }
private byte[] encryptOnWrite(byte[] dataBytes) { MemoryStream encryptedDataStream = new MemoryStream(); IBufferedCipher outCipher = createCipher(true); CipherStream outCipherStream = new CipherStream(encryptedDataStream, null, outCipher); outCipherStream.Write(dataBytes, 0, dataBytes.Length); Assert.AreEqual(0L, encryptedDataStream.Position % outCipher.GetBlockSize()); outCipherStream.Close(); byte[] encryptedDataBytes = encryptedDataStream.ToArray(); Assert.AreEqual(dataBytes.Length, encryptedDataBytes.Length); return encryptedDataBytes; }
private byte[] encryptOnWrite(byte[] dataBytes) { MemoryStream encryptedDataStream = new MemoryStream(); IBufferedCipher outCipher = createCipher(true); CipherStream outCipherStream = new CipherStream(encryptedDataStream, null, outCipher); outCipherStream.Write(dataBytes, 0, dataBytes.Length); Assert.AreEqual(0L, encryptedDataStream.Position % outCipher.GetBlockSize()); outCipherStream.Close(); byte[] encryptedDataBytes = encryptedDataStream.ToArray(); Assert.AreEqual(dataBytes.Length, encryptedDataBytes.Length); return(encryptedDataBytes); }
protected void RunDiscreteVectorTest(int number, DiscreteVectorTestCase testCase) { CipherConfiguration config = GetCipherConfiguration(testCase); byte[] plaintext = testCase.Plaintext; byte[] ciphertext; using (var msCiphertext = new MemoryStream()) { using (var cs = new CipherStream(msCiphertext, true, config, testCase.Key, false)) { cs.Write(plaintext, 0, plaintext.Length); } ciphertext = msCiphertext.ToArray(); } Assert.IsTrue(testCase.Ciphertext.SequenceEqualShortCircuiting(ciphertext), "Test #{0} (\"{1}\") failed!", number, testCase.Name); }
/// <summary> /// <p> /// Close off the encrypted object - this is equivalent to calling Close() on the stream /// returned by the Open() method. /// </p> /// <p> /// <b>Note</b>: This does not close the underlying output stream, only the stream on top of /// it created by the Open() method. /// </p> /// </summary> public void Close() { if (cOut != null) { // TODO Should this all be under the try/catch block? if (digestOut != null) { // // hand code a mod detection packet // BcpgOutputStream bOut = new BcpgOutputStream( digestOut, PacketTag.ModificationDetectionCode, 20); bOut.Flush(); digestOut.Flush(); // TODO byte[] dig = DigestUtilities.DoFinal(digestOut.WriteDigest()); cOut.Write(dig, 0, dig.Length); } cOut.Flush(); try { pOut.Write(c.DoFinal()); pOut.Finish(); } catch (Exception e) { throw new IOException(e.Message, e); } cOut = null; pOut = null; } }
private void doTest( string alg, int strength, byte[] input, byte[] output) { KeyParameter key = null; CipherKeyGenerator keyGen; SecureRandom rand; IBufferedCipher inCipher = null; IBufferedCipher outCipher = null; CipherStream cIn; CipherStream cOut; MemoryStream bIn; MemoryStream bOut; rand = new FixedSecureRandom(); try { keyGen = GeneratorUtilities.GetKeyGenerator(alg); keyGen.Init(new KeyGenerationParameters(rand, strength)); key = new DesEdeParameters(keyGen.GenerateKey()); inCipher = CipherUtilities.GetCipher(alg + "/ECB/PKCS7Padding"); outCipher = CipherUtilities.GetCipher(alg + "/ECB/PKCS7Padding"); outCipher.Init(true, new ParametersWithRandom(key, rand)); } catch (Exception e) { Fail(alg + " failed initialisation - " + e.ToString()); } try { inCipher.Init(false, key); } catch (Exception e) { Fail(alg + " failed initialisation - " + e.ToString()); } // // encryption pass // bOut = new MemoryStream(); cOut = new CipherStream(bOut, null, outCipher); try { for (int i = 0; i != input.Length / 2; i++) { cOut.WriteByte(input[i]); } cOut.Write(input, input.Length / 2, input.Length - input.Length / 2); cOut.Close(); } catch (IOException e) { Fail(alg + " failed encryption - " + e.ToString()); } byte[] bytes = bOut.ToArray(); if (!Arrays.AreEqual(bytes, output)) { Fail(alg + " failed encryption - expected " + Hex.ToHexString(output) + " got " + Hex.ToHexString(bytes)); } // // decryption pass // bIn = new MemoryStream(bytes, false); cIn = new CipherStream(bIn, inCipher, null); try { // DataInputStream dIn = new DataInputStream(cIn); BinaryReader dIn = new BinaryReader(cIn); bytes = new byte[input.Length]; for (int i = 0; i != input.Length / 2; i++) { bytes[i] = (byte)dIn.ReadByte(); } // dIn.readFully(bytes, input.Length / 2, bytes.Length - input.Length / 2); int remaining = bytes.Length - input.Length / 2; byte[] rest = dIn.ReadBytes(remaining); if (rest.Length != remaining) { throw new Exception("IO problem with BinaryReader"); } rest.CopyTo(bytes, input.Length / 2); } catch (Exception e) { Fail(alg + " failed encryption - " + e.ToString()); } if (!Arrays.AreEqual(bytes, input)) { Fail(alg + " failed decryption - expected " + Hex.ToHexString(input) + " got " + Hex.ToHexString(bytes)); } // TODO Put back in // // // // keyspec test // // // try // { // SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(alg); // DESedeKeySpec keySpec = (DESedeKeySpec)keyFactory.getKeySpec((SecretKey)key, DESedeKeySpec.class); // // if (!equalArray(key.getEncoded(), keySpec.getKey(), 16)) // { // Fail(alg + " KeySpec does not match key."); // } // } // catch (Exception e) // { // Fail(alg + " failed keyspec - " + e.ToString()); // } }
protected override void ExecuteOperation() { Debug.Assert(ItemCompletionRegister[Index] == false); PayloadItem item = PayloadItems[Index]; Guid itemIdentifier = item.Identifier; bool skip = ItemSkipRegister != null && ItemSkipRegister.Contains(itemIdentifier); MuxItemResourceContainer itemContainer; bool activeResource = _activeItemResources.ContainsKey(itemIdentifier); if (activeResource) { itemContainer = _activeItemResources[itemIdentifier]; } else { if (skip == false) { itemContainer = CreateEtMSchemeResources(item); if (Writing) { EmitHeader(itemContainer.Authenticator); } else { ConsumeHeader(itemContainer.Authenticator); } } else { itemContainer = new MuxItemResourceContainer(null, null, null); } _activeItemResources.Add(itemIdentifier, itemContainer); } int opLength = NextOperationLength(); if (skip == false) { CipherStream itemEncryptor = itemContainer.Encryptor; MacStream itemAuthenticator = itemContainer.Authenticator; if (Writing) { // Writing/multiplexing if (itemEncryptor.BytesIn + opLength < item.ExternalLength) { // Normal operation itemEncryptor.WriteExactly(item.StreamBinding, opLength); } else { // Final operation, or just prior to if (itemContainer.Buffer.IsValueCreated == false) { // Redirect final ciphertext to buffer to account for possible expansion itemAuthenticator.ReassignBinding(itemContainer.Buffer.Value, false, finish: false); } var remaining = (int)(item.ExternalLength - itemEncryptor.BytesIn); if (remaining > 0) { while (remaining > 0) { int toRead = Math.Min(remaining, BufferSize); int iterIn = item.StreamBinding.Read(Buffer, 0, toRead); if (iterIn < toRead) { throw new EndOfStreamException(); } itemEncryptor.Write(Buffer, 0, iterIn); // Writing into recently-lazy-inited buffer remaining -= iterIn; } itemEncryptor.Close(); } var toWrite = (int)Math.Min(opLength, itemContainer.Buffer.Value.Length); Debug.Print(DebugUtility.CreateReportString("FabricPayloadMux", "ExecuteOperation", "Multiplexing item: final stripe length", toWrite)); itemContainer.Buffer.Value.ReadTo(PayloadStream, toWrite); } } else { // Reading/demultiplexing long readRemaining = item.InternalLength - itemEncryptor.BytesIn; bool finalOp = false; if (readRemaining <= opLength) { // Final operation opLength = (int)readRemaining; finalOp = true; Debug.Print(DebugUtility.CreateReportString("FabricPayloadMux", "ExecuteOperation", "Demultiplexing item: final stripe length", opLength)); } itemEncryptor.ReadExactly(item.StreamBinding, opLength, finalOp); } if ((Writing && itemEncryptor.BytesIn >= item.ExternalLength && itemContainer.Buffer.Value.Length == 0) || (Writing == false && itemEncryptor.BytesIn >= item.InternalLength)) { // Now that we're finished we need to do some extra things, then clean up FinishItem(item, itemEncryptor, itemAuthenticator); } } else { // Skipping Debug.Assert(Writing == false, "Should not be skipping when writing!"); if (itemContainer.SkippedLength == 0) { // Start of item PayloadStream.Seek(opLength, SeekOrigin.Current); itemContainer.SkippedLength += opLength; } else if (itemContainer.SkippedLength + opLength >= item.InternalLength) { int remainingToSkip = (int)(item.InternalLength - itemContainer.SkippedLength); itemContainer.SkippedLength += remainingToSkip; PayloadStream.Seek(remainingToSkip + GetTrailerLength(), SeekOrigin.Current); // "Finish" item _activeItemResources.Remove(item.Identifier); // Mark the item as completed in the register ItemCompletionRegister[Index] = true; ItemsCompleted++; Debug.Print(DebugUtility.CreateReportString("FabricPayloadMux", "ExecuteOperation", "[*** SKIPPED ITEM", Index + " ***]")); } else { PayloadStream.Seek(opLength, SeekOrigin.Current); itemContainer.SkippedLength += opLength; } } }
public void DoTest( int strength, byte[] keyBytes, byte[] input, byte[] output) { KeyParameter key = ParameterUtilities.CreateKeyParameter("SM4", keyBytes); IBufferedCipher inCipher = CipherUtilities.GetCipher("SM4/ECB/NoPadding"); IBufferedCipher outCipher = CipherUtilities.GetCipher("SM4/ECB/NoPadding"); try { outCipher.Init(true, key); } catch (Exception e) { Fail("SM4 failed initialisation - " + e, e); } try { inCipher.Init(false, key); } catch (Exception e) { Fail("SM4 failed initialisation - " + e, e); } // // encryption pass // MemoryStream bOut = new MemoryStream(); CipherStream cOut = new CipherStream(bOut, null, outCipher); try { for (int i = 0; i != input.Length / 2; i++) { cOut.WriteByte(input[i]); } cOut.Write(input, input.Length / 2, input.Length - input.Length / 2); cOut.Close(); } catch (IOException e) { Fail("SM4 failed encryption - " + e, e); } byte[] bytes = bOut.ToArray(); if (!AreEqual(bytes, output)) { Fail("SM4 failed encryption - expected " + Hex.ToHexString(output) + " got " + Hex.ToHexString(bytes)); } // // decryption pass // MemoryStream bIn = new MemoryStream(bytes, false); CipherStream cIn = new CipherStream(bIn, inCipher, null); try { // DataInputStream dIn = new DataInputStream(cIn); BinaryReader dIn = new BinaryReader(cIn); bytes = new byte[input.Length]; for (int i = 0; i != input.Length / 2; i++) { // bytes[i] = (byte)dIn.read(); bytes[i] = dIn.ReadByte(); } int remaining = bytes.Length - input.Length / 2; // dIn.readFully(bytes, input.Length / 2, remaining); byte[] extra = dIn.ReadBytes(remaining); if (extra.Length < remaining) { throw new EndOfStreamException(); } extra.CopyTo(bytes, input.Length / 2); } catch (Exception e) { Fail("SM4 failed encryption - " + e, e); } if (!AreEqual(bytes, input)) { Fail("SM4 failed decryption - expected " + Hex.ToHexString(input) + " got " + Hex.ToHexString(bytes)); } }
private void ParametersTest() { AllocateRandom(ref _iv, 16); AllocateRandom(ref _key, 32); AllocateRandom(ref _plnText, 1); KeyParams kp = new KeyParams(_key, _iv); _cmpText = new byte[1]; _decText = new byte[1]; _encText = new byte[1]; RHX engine = new RHX(); // 1 byte w/ byte arrays { CTR cipher = new CTR(engine, false); CipherStream cs = new CipherStream(cipher); cs.Initialize(true, kp); cs.Write(_plnText, 0, ref _encText, 0); cs.Initialize(false, kp); cs.Write(_encText, 0, ref _decText, 0); if (!Evaluate.AreEqual(_decText, _plnText)) { throw new Exception("CipherStreamTest: Encrypted arrays are not equal!"); } cipher.Dispose(); } // 1 byte w/ stream { CTR cipher = new CTR(engine, false); CipherStream cs = new CipherStream(cipher); cs.Initialize(true, kp); AllocateRandom(ref _plnText, 1); MemoryStream mIn = new MemoryStream(_plnText); MemoryStream mOut = new MemoryStream(); cs.Write(mIn, mOut); cs.Initialize(false, kp); MemoryStream mRes = new MemoryStream(); mOut.Seek(0, SeekOrigin.Begin); cs.Write(mOut, mRes); if (!Evaluate.AreEqual(mRes.ToArray(), _plnText)) { throw new Exception("CipherStreamTest: Encrypted arrays are not equal!"); } cipher.Dispose(); } // partial block w/ byte arrays { CTR cipher = new CTR(engine, false); CipherStream cs = new CipherStream(cipher); AllocateRandom(ref _plnText, 15); Array.Resize(ref _decText, 15); Array.Resize(ref _encText, 15); cs.Initialize(true, kp); cs.Write(_plnText, 0, ref _encText, 0); cs.Initialize(false, kp); cs.Write(_encText, 0, ref _decText, 0); if (!Evaluate.AreEqual(_decText, _plnText)) { throw new Exception("CipherStreamTest: Encrypted arrays are not equal!"); } cipher.Dispose(); } // partial block w/ stream { CTR cipher = new CTR(engine, false); CipherStream cs = new CipherStream(cipher); AllocateRandom(ref _plnText, 15); Array.Resize(ref _decText, 15); Array.Resize(ref _encText, 15); cs.Initialize(true, kp); MemoryStream mIn = new MemoryStream(_plnText); MemoryStream mOut = new MemoryStream(); cs.Write(mIn, mOut); cs.Initialize(false, kp); MemoryStream mRes = new MemoryStream(); mOut.Seek(0, SeekOrigin.Begin); cs.Write(mOut, mRes); if (!Evaluate.AreEqual(mRes.ToArray(), _plnText)) { throw new Exception("CipherStreamTest: Encrypted arrays are not equal!"); } cipher.Dispose(); } // random block sizes w/ byte arrays { for (int i = 0; i < 100; i++) { CTR cipher = new CTR(engine, false); int sze = AllocateRandom(ref _plnText); _decText = new byte[sze]; _encText = new byte[sze]; CipherStream cs = new CipherStream(cipher); cs.Initialize(true, kp); cs.Write(_plnText, 0, ref _encText, 0); cs.Initialize(false, kp); cs.Write(_encText, 0, ref _decText, 0); if (!Evaluate.AreEqual(_decText, _plnText)) { throw new Exception("CipherStreamTest: Encrypted arrays are not equal!"); } cipher.Dispose(); } } // random block sizes w/ stream { for (int i = 0; i < 100; i++) { CTR cipher = new CTR(engine, false); int sze = AllocateRandom(ref _plnText); _decText = new byte[sze]; _encText = new byte[sze]; CipherStream cs = new CipherStream(cipher); cs.Initialize(true, kp); MemoryStream mIn = new MemoryStream(_plnText); MemoryStream mOut = new MemoryStream(); cs.Write(mIn, mOut); cs.Initialize(false, kp); MemoryStream mRes = new MemoryStream(); mOut.Seek(0, SeekOrigin.Begin); cs.Write(mOut, mRes); if (!Evaluate.AreEqual(mRes.ToArray(), _plnText)) { throw new Exception("CipherStreamTest: Encrypted arrays are not equal!"); } cipher.Dispose(); } } engine.Dispose(); }
public override void Write(byte[] buffer, int offset, int count) { cstream.Write(buffer, offset, count); }
/// <summary> /// Test the CipherStream class implementation /// <para>Throws an Exception on failure</</para> /// </summary> public static void StreamCipherTest() { const int BLSZ = 1024; KeyParams key; byte[] data; MemoryStream instrm; MemoryStream outstrm = new MemoryStream(); using (KeyGenerator kg = new KeyGenerator()) { // get the key key = kg.GetKeyParams(32, 16); // 2048 bytes data = kg.GetBytes(BLSZ * 2); } // data to encrypt instrm = new MemoryStream(data); // Encrypt a stream // // create the outbound cipher using (ICipherMode cipher = new CTR(new RHX())) { // set block size ((CTR)cipher).ParallelBlockSize = BLSZ; // encrypt the stream using (CipherStream sc = new CipherStream(cipher)) { sc.Initialize(true, key); // encrypt the buffer sc.Write(instrm, outstrm); } } // reset stream position outstrm.Seek(0, SeekOrigin.Begin); MemoryStream tmpstrm = new MemoryStream(); // Decrypt a stream // // create the decryption cipher using (ICipherMode cipher = new CTR(new RHX())) { // set block size ((CTR)cipher).ParallelBlockSize = BLSZ; // decrypt the stream using (CipherStream sc = new CipherStream(cipher)) { sc.Initialize(false, key); // process the encrypted bytes sc.Write(outstrm, tmpstrm); } } // compare decrypted output with data if (!Evaluate.AreEqual(tmpstrm.ToArray(), data)) { throw new Exception(); } }
void StreamTest() { AllocateRandom(ref _iv, 8); AllocateRandom(ref _key, 32); KeyParams kp = new KeyParams(_key, _iv); Salsa20 cipher = new Salsa20(); Salsa20 cipher2 = new Salsa20(); CipherStream cs = new CipherStream(cipher2); cipher.IsParallel = false; // ctr test for (int i = 0; i < 10; i++) { int sze = AllocateRandom(ref _plnText); int prlBlock = sze - (sze % (cipher.BlockSize * _processorCount)); _cmpText = new byte[sze]; _decText = new byte[sze]; _encText = new byte[sze]; cipher.ParallelBlockSize = prlBlock; cs.ParallelBlockSize = prlBlock; MemoryStream mIn = new MemoryStream(_plnText); MemoryStream mOut = new MemoryStream(); MemoryStream mRes = new MemoryStream(); // *** Compare encryption output *** // // local processor cipher.Initialize(kp); ProcessStream(cipher, _plnText, 0, _encText, 0); // streamcipher linear mode cs.IsParallel = false; // memorystream interface cs.Initialize(true, kp); cs.Write(mIn, mOut); if (!Evaluate.AreEqual(mOut.ToArray(), _encText)) { throw new Exception("CipherStreamTest: Encrypted arrays are not equal!"); } // byte array interface cs.Initialize(true, kp); cs.Write(_plnText, 0, ref _cmpText, 0); if (!Evaluate.AreEqual(_cmpText, _encText)) { throw new Exception("CipherStreamTest: Encrypted arrays are not equal!"); } mIn.Seek(0, SeekOrigin.Begin); mOut.Seek(0, SeekOrigin.Begin); // parallel test cs.IsParallel = true; cs.Initialize(true, kp); cs.Write(mIn, mOut); if (!Evaluate.AreEqual(mOut.ToArray(), _encText)) { throw new Exception("CipherStreamTest: Encrypted arrays are not equal!"); } // byte array interface cs.Initialize(true, kp); cs.Write(_plnText, 0, ref _cmpText, 0); if (!Evaluate.AreEqual(_cmpText, _encText)) { throw new Exception("CipherStreamTest: Encrypted arrays are not equal!"); } // ***compare decryption output *** // // local processor cipher.Initialize(kp); ProcessStream(cipher, _encText, 0, _decText, 0); if (!Evaluate.AreEqual(_plnText, _decText)) { throw new Exception("CipherStreamTest: Decrypted arrays are not equal!"); } // decrypt linear mode cs.IsParallel = false; mOut.Seek(0, SeekOrigin.Begin); cs.Initialize(false, kp); cs.Write(mOut, mRes); if (!Evaluate.AreEqual(mRes.ToArray(), _decText)) { throw new Exception("CipherStreamTest: Decrypted arrays are not equal!"); } // byte array interface cs.Initialize(false, kp); cs.Write(_encText, 0, ref _cmpText, 0); if (!Evaluate.AreEqual(_cmpText, _decText)) { throw new Exception("CipherStreamTest: Decrypted arrays are not equal!"); } // decrypt parallel mode cs.IsParallel = true; mOut.Seek(0, SeekOrigin.Begin); mRes.Seek(0, SeekOrigin.Begin); cs.Initialize(false, kp); cs.Write(mOut, mRes); if (!Evaluate.AreEqual(mRes.ToArray(), _decText)) { throw new Exception("CipherStreamTest: Decrypted arrays are not equal!"); } // byte array interface cs.Initialize(false, kp); cs.Write(_encText, 0, ref _cmpText, 0); if (!Evaluate.AreEqual(_cmpText, _decText)) { throw new Exception("CipherStreamTest: Decrypted arrays are not equal!"); } } cipher.Dispose(); cipher2.Dispose(); }
public ITestResult doTest( string algorithm, byte[] input, byte[] output) { KeyParameter key; IBufferedCipher inCipher, outCipher; CipherStream cIn, cOut; MemoryStream bIn, bOut; // IvParameterSpec spec = new IvParameterSpec(); byte[] spec = Hex.Decode("1234567890abcdef"); try { key = new DesParameters(Hex.Decode("0123456789abcdef")); inCipher = CipherUtilities.GetCipher(algorithm); outCipher = CipherUtilities.GetCipher(algorithm); if (algorithm.StartsWith("DES/ECB")) { outCipher.Init(true, key); } else { outCipher.Init(true, new ParametersWithIV(key, spec)); } } catch (Exception e) { return(new SimpleTestResult(false, Name + ": " + algorithm + " failed initialisation - " + e.ToString(), e)); } try { if (algorithm.StartsWith("DES/ECB")) { inCipher.Init(false, key); } else { inCipher.Init(false, new ParametersWithIV(key, spec)); } } catch (Exception e) { return(new SimpleTestResult(false, Name + ": " + algorithm + " failed initialisation - " + e.ToString(), e)); } // // encryption pass // bOut = new MemoryStream(); cOut = new CipherStream(bOut, null, outCipher); try { for (int i = 0; i != input.Length / 2; i++) { cOut.WriteByte(input[i]); } cOut.Write(input, input.Length / 2, input.Length - input.Length / 2); cOut.Close(); } catch (IOException e) { return(new SimpleTestResult(false, Name + ": " + algorithm + " failed encryption - " + e.ToString())); } byte[] bytes = bOut.ToArray(); if (!Arrays.AreEqual(bytes, output)) { return(new SimpleTestResult(false, Name + ": " + algorithm + " failed encryption - expected " + Hex.ToHexString(output) + " got " + Hex.ToHexString(bytes))); } // // decryption pass // bIn = new MemoryStream(bytes, false); cIn = new CipherStream(bIn, inCipher, null); try { BinaryReader dIn = new BinaryReader(cIn); bytes = new byte[input.Length]; for (int i = 0; i != input.Length / 2; i++) { bytes[i] = dIn.ReadByte(); } int remaining = bytes.Length - input.Length / 2; byte[] extra = dIn.ReadBytes(remaining); if (extra.Length < remaining) { throw new EndOfStreamException(); } extra.CopyTo(bytes, input.Length / 2); } catch (Exception e) { return(new SimpleTestResult(false, Name + ": " + algorithm + " failed encryption - " + e.ToString())); } if (!Arrays.AreEqual(bytes, input)) { return(new SimpleTestResult(false, Name + ": " + algorithm + " failed decryption - expected " + Hex.ToHexString(input) + " got " + Hex.ToHexString(bytes))); } return(new SimpleTestResult(true, Name + ": " + algorithm + " Okay")); }
private void doTestEcb( int strength, byte[] keyBytes, byte[] input, byte[] output) { IBufferedCipher inCipher, outCipher; CipherStream cIn, cOut; MemoryStream bIn, bOut; KeyParameter key = ParameterUtilities.CreateKeyParameter("GOST28147", keyBytes); inCipher = CipherUtilities.GetCipher("GOST28147/ECB/NoPadding"); outCipher = CipherUtilities.GetCipher("GOST28147/ECB/NoPadding"); outCipher.Init(true, key); inCipher.Init(false, key); // // encryption pass // bOut = new MemoryStream(); cOut = new CipherStream(bOut, null, outCipher); for (int i = 0; i != input.Length / 2; i++) { cOut.WriteByte(input[i]); } cOut.Write(input, input.Length / 2, input.Length - input.Length / 2); cOut.Close(); byte[] bytes = bOut.ToArray(); if (!AreEqual(bytes, output)) { Fail("GOST28147 failed encryption - expected " + Hex.ToHexString(output) + " got " + Hex.ToHexString(bytes)); } // // decryption pass // bIn = new MemoryStream(bytes, false); cIn = new CipherStream(bIn, inCipher, null); BinaryReader dIn = new BinaryReader(cIn); bytes = new byte[input.Length]; for (int i = 0; i != input.Length / 2; i++) { bytes[i] = dIn.ReadByte(); } int remaining = bytes.Length - input.Length / 2; byte[] extra = dIn.ReadBytes(remaining); if (extra.Length < remaining) { throw new EndOfStreamException(); } extra.CopyTo(bytes, input.Length / 2); if (!AreEqual(bytes, input)) { Fail("GOST28147 failed decryption - expected " + Hex.ToHexString(input) + " got " + Hex.ToHexString(bytes)); } }
private void OfbModeTest() { AllocateRandom(ref _iv, 16); AllocateRandom(ref _key, 32); KeyParams kp = new KeyParams(_key, _iv); RHX eng = new RHX(); OFB cipher = new OFB(eng); OFB cipher2 = new OFB(eng); ISO7816 padding = new ISO7816(); cipher.IsParallel = false; CipherStream cs = new CipherStream(cipher2, padding); for (int i = 0; i < 10; i++) { int sze = AllocateRandom(ref _plnText, 0, eng.BlockSize); int prlBlock = sze - (sze % (cipher.BlockSize * _processorCount)); _cmpText = new byte[sze]; _decText = new byte[sze]; _encText = new byte[sze]; MemoryStream mIn = new MemoryStream(_plnText); MemoryStream mOut = new MemoryStream(); MemoryStream mRes = new MemoryStream(); // *** Compare encryption output *** // // local processor cipher.Initialize(true, kp); BlockEncrypt(cipher, padding, _plnText, 0, ref _encText, 0); // streamcipher linear mode cs.IsParallel = false; // memorystream interface cs.Initialize(true, kp); cs.Write(mIn, mOut); if (!Evaluate.AreEqual(mOut.ToArray(), _encText)) { throw new Exception("CipherStreamTest: Encrypted arrays are not equal!"); } // byte array interface cs.Initialize(true, kp); cs.Write(_plnText, 0, ref _cmpText, 0); if (!Evaluate.AreEqual(_cmpText, _encText)) { throw new Exception("CipherStreamTest: Encrypted arrays are not equal!"); } // ***compare decryption output *** // // local processor cipher.Initialize(false, kp); BlockDecrypt(cipher, padding, _encText, 0, ref _decText, 0); if (!Evaluate.AreEqual(_plnText, _decText)) { throw new Exception("CipherStreamTest: Decrypted arrays are not equal!"); } // decrypt linear mode cipher2.IsParallel = false; mOut.Seek(0, SeekOrigin.Begin); cs.Initialize(false, kp); cs.Write(mOut, mRes); if (!Evaluate.AreEqual(mRes.ToArray(), _decText)) { throw new Exception("CipherStreamTest: Decrypted arrays are not equal!"); } // byte array interface cs.Initialize(false, kp); Array.Resize(ref _cmpText, _encText.Length); cs.Write(_encText, 0, ref _cmpText, 0); if (!Evaluate.AreEqual(_cmpText, _decText)) { throw new Exception("CipherStreamTest: Decrypted arrays are not equal!"); } } eng.Dispose(); }
private void doTest( string algorithm, byte[] input, byte[] output) { KeyParameter key = null; CipherKeyGenerator keyGen; SecureRandom rand; IBufferedCipher inCipher = null, outCipher = null; byte[] iv = null; CipherStream cIn, cOut; MemoryStream bIn, bOut; rand = new FixedSecureRandom(); string[] parts = algorithm.ToUpper(CultureInfo.InvariantCulture).Split('/'); string baseAlgorithm = parts[0]; string mode = parts.Length > 1 ? parts[1] : null; #if !INCLUDE_IDEA if (baseAlgorithm.Equals("IDEA")) { return; } #endif try { keyGen = GeneratorUtilities.GetKeyGenerator(baseAlgorithm); // TODO Add Algorithm property to CipherKeyGenerator? // if (!keyGen.getAlgorithm().Equals(baseAlgorithm)) // { // Fail("wrong key generator returned!"); // } // TODO Add new Init method to CipherKeyGenerator? // keyGen.Init(rand); keyGen.Init(new KeyGenerationParameters(rand, keyGen.DefaultStrength)); byte[] keyBytes = keyGen.GenerateKey(); if (algorithm.StartsWith("RC5")) { key = new RC5Parameters(keyBytes, rc5Rounds); } else { key = ParameterUtilities.CreateKeyParameter(baseAlgorithm, keyBytes); } inCipher = CipherUtilities.GetCipher(algorithm); outCipher = CipherUtilities.GetCipher(algorithm); if (!inCipher.AlgorithmName.ToUpper(CultureInfo.InvariantCulture).StartsWith(baseAlgorithm)) { Fail("wrong cipher returned!"); } ICipherParameters parameters = key; int ivLength = GetIVLength(algorithm); if (ivLength > 0) { if (baseAlgorithm == "RC2") { iv = rc2IV; } else if (baseAlgorithm == "RC5") { iv = rc5IV; } else if (baseAlgorithm == "RC5-64") { iv = rc564IV; } else { // NB: rand always generates same values each test run iv = rand.GenerateSeed(ivLength); } parameters = new ParametersWithIV(key, iv); } // NB: 'rand' still needed e.g. for some paddings parameters = new ParametersWithRandom(parameters, rand); outCipher.Init(true, parameters); } catch (Exception e) { Fail("" + algorithm + " failed initialisation - " + e.ToString(), e); } // // grab the iv if there is one // try { // The Java version set this implicitly, but we set it explicity //byte[] iv = outCipher.getIV(); if (iv != null) { // TODO Examine short IV handling for these FIPS-compliant modes in Java build if (mode.StartsWith("CFB") || mode.StartsWith("GOFB") || mode.StartsWith("OFB") || mode.StartsWith("OPENPGPCFB")) { // These modes automatically pad out the IV if it is short } else { try { byte[] nIv = new byte[iv.Length - 1]; inCipher.Init(false, new ParametersWithIV(key, nIv)); Fail("failed to pick up short IV"); } //catch (InvalidAlgorithmParameterException e) catch (ArgumentException) { // ignore - this is what we want... } } //IvParameterSpec spec = new IvParameterSpec(iv); inCipher.Init(false, new ParametersWithIV(key, iv)); } else { inCipher.Init(false, key); } } catch (Exception e) { Fail("" + algorithm + " failed initialisation - " + e.ToString()); } // // encryption pass // bOut = new MemoryStream(); cOut = new CipherStream(bOut, null, outCipher); try { for (int i = 0; i != input.Length / 2; i++) { cOut.WriteByte(input[i]); } cOut.Write(input, input.Length / 2, input.Length - input.Length / 2); cOut.Close(); } catch (IOException e) { Fail("" + algorithm + " failed encryption - " + e.ToString()); } byte[] bytes = bOut.ToArray(); if (!AreEqual(bytes, output)) { Fail("" + algorithm + " failed encryption - expected " + Hex.ToHexString(output) + " got " + Hex.ToHexString(bytes)); } // // decryption pass // bIn = new MemoryStream(bytes, false); cIn = new CipherStream(bIn, inCipher, null); try { BinaryReader dIn = new BinaryReader(cIn); bytes = new byte[input.Length]; for (int i = 0; i != input.Length / 2; i++) { bytes[i] = dIn.ReadByte(); } int remaining = bytes.Length - input.Length / 2; byte[] extra = dIn.ReadBytes(remaining); if (extra.Length < remaining) { throw new EndOfStreamException(); } extra.CopyTo(bytes, input.Length / 2); } catch (Exception e) { Fail("" + algorithm + " failed decryption - " + e.ToString()); } if (!AreEqual(bytes, input)) { Fail("" + algorithm + " failed decryption - expected " + Hex.ToHexString(input) + " got " + Hex.ToHexString(bytes)); } }
private static bool EncryptFile(ref string filename) { byte[] data = null; try { data = File.ReadAllBytes(filename); } catch (Exception) { Console.WriteLine("error loading file to encrypt"); Environment.Exit(-1); return(false); } if (null == data) { Console.WriteLine("error loading file to encrypt (2)"); Environment.Exit(-1); return(false); } SecureRandom random = new SecureRandom(); byte[] secretKeyData = new byte[32]; random.NextBytes(secretKeyData); byte[] IV = new byte[16]; for (int i = 0; i < IV.Length; i++) { IV[i] = 0x00; } KeyParameter secretKey = new KeyParameter(secretKeyData); IBufferedCipher cipher = CipherUtilities.GetCipher("AES/GCM/NoPadding"); ParametersWithIV aesIVKeyParam = new ParametersWithIV(secretKey, IV); cipher.Init(true, aesIVKeyParam); MemoryStream bOut = new MemoryStream(); CipherStream cOut = new CipherStream(bOut, null, cipher); cOut.Write(data, 0, data.Length); cOut.Close(); byte[] encryted = bOut.ToArray(); X509CertificateParser certParser = new X509CertificateParser(); Org.BouncyCastle.X509.X509Certificate cert = certParser.ReadCertificate(EncryptionCertificate); AsymmetricKeyParameter pubkey = cert.GetPublicKey(); //Pkcs1Encoding encryptEngine = new Pkcs1Encoding(new RsaEngine()); // V2 OaepEncoding encryptEngine = new OaepEncoding(new RsaEngine()); // V3 encryptEngine.Init(true, pubkey); byte[] keyblock = encryptEngine.ProcessBlock(secretKeyData, 0, secretKeyData.Length); List <byte> ResultBlock = new List <byte>(); ResultBlock.AddRange(encryted); ResultBlock.AddRange(keyblock); filename += ".enc"; File.WriteAllBytes(filename, ResultBlock.ToArray()); return(true); }