public override void Close() { _out.Close(); this.CloseParentContext(); base.Close(); }
private static byte[] RSAEncryptData(AsymmetricKeyParameter publicKey, byte[] originalDataBytes) { bool isEncryption = true; byte[] encryptedDataArray; using (MemoryStream originalDataStream = new MemoryStream(originalDataBytes, false)) { using (MemoryStream encryptedDataStream = new MemoryStream()) { IBufferedCipher rsacipher = RSACreateCipher(isEncryption, publicKey); using (CipherStream cipherStream = new CipherStream(originalDataStream, rsacipher, null)) { int oneByte; while ((oneByte = cipherStream.ReadByte()) >= 0) { encryptedDataStream.WriteByte((byte)oneByte); } cipherStream.Close(); cipherStream.Dispose(); } encryptedDataArray = encryptedDataStream.ToArray(); encryptedDataStream.Close(); encryptedDataStream.Dispose(); } originalDataStream.Close(); originalDataStream.Dispose(); } return(encryptedDataArray); }
public static string DecryptForJava(string input, string key) { var inputArrary = Convert.FromBase64String(input); var outCipher = CreateCipher(false, key); var encryptedDataStream = new MemoryStream(inputArrary, false); var dataStream = new MemoryStream(); var outCipherStream = new CipherStream(dataStream, null, outCipher); int ch; while ((ch = encryptedDataStream.ReadByte()) >= 0) { outCipherStream.WriteByte((byte)ch); } outCipherStream.Close(); encryptedDataStream.Close(); var dataBytes = dataStream.ToArray(); return(Encoding.UTF8.GetString(dataBytes)); }
public override void Close() { _out.Close(); _eiGen.Close(); // [TODO] unprotected attributes go here _envGen.Close(); _cGen.Close(); base.Close(); }
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); }
public static byte[] AESEncryptData(byte[] originalDataBytes, byte[] aesKeyByteData, byte[] iv = null) { bool isEncryption = true; MemoryStream originalDataStream = new MemoryStream(originalDataBytes, false); MemoryStream encryptedDataStream = new MemoryStream(); IBufferedCipher aesCipher = AESCreateCipher(isEncryption, aesKeyByteData, iv); CipherStream cipherStream = new CipherStream(originalDataStream, aesCipher, null); int oneByte; while ((oneByte = cipherStream.ReadByte()) >= 0) { encryptedDataStream.WriteByte((byte)oneByte); } encryptedDataStream.Close(); cipherStream.Close(); return(encryptedDataStream.ToArray()); }
private static byte[] RSAEntschluesselDaten(AsymmetricKeyParameter privateKey, byte[] encryptedDataBytes) { bool isEncryption = false; MemoryStream enryptedDataSream = new MemoryStream(encryptedDataBytes, false); MemoryStream decryptedDataStream = new MemoryStream(); IBufferedCipher aesCipher = RSACreateCipher(isEncryption, privateKey); CipherStream decodedCipherStream = new CipherStream(enryptedDataSream, aesCipher, null); int oneByte; while ((oneByte = decodedCipherStream.ReadByte()) >= 0) { decryptedDataStream.WriteByte((byte)oneByte); } decodedCipherStream.Close(); decryptedDataStream.Close(); return(decryptedDataStream.ToArray()); }
public static byte[] AESDecryptData(byte[] encryptedDataBytes, byte[] aesKeyByteData, byte[] iv = null) { bool isEncryption = false; MemoryStream enryptedDataSream = new MemoryStream(encryptedDataBytes, false); MemoryStream decryptedDataStream = new MemoryStream(); IBufferedCipher aesCipher = AESCreateCipher(isEncryption, aesKeyByteData, iv); CipherStream decodedCipherStream = new CipherStream(enryptedDataSream, aesCipher, null); int oneByte; while ((oneByte = decodedCipherStream.ReadByte()) >= 0) { decryptedDataStream.WriteByte((byte)oneByte); } decodedCipherStream.Close(); decryptedDataStream.Close(); return(decryptedDataStream.ToArray()); }
public override void Close() { _out.Close(); // TODO Parent context(s) should really be be closed explicitly _eiGen.Close(); if (_outer.unprotectedAttributeGenerator != null) { Asn1.Cms.AttributeTable attrTable = _outer.unprotectedAttributeGenerator.GetAttributes(Platform.CreateHashtable()); Asn1Set unprotectedAttrs = new BerSet(attrTable.ToAsn1EncodableVector()); _envGen.AddObject(new DerTaggedObject(false, 1, unprotectedAttrs)); } _envGen.Close(); _cGen.Close(); base.Close(); }
private byte[] decryptOnWrite(byte[] encryptedDataBytes) { MemoryStream encryptedDataStream = new MemoryStream(encryptedDataBytes, false); MemoryStream dataStream = new MemoryStream(); IBufferedCipher outCipher = createCipher(false); CipherStream outCipherStream = new CipherStream(dataStream, null, outCipher); int ch; while ((ch = encryptedDataStream.ReadByte()) >= 0) { outCipherStream.WriteByte((byte)ch); } outCipherStream.Close(); encryptedDataStream.Close(); byte[] dataBytes = dataStream.ToArray(); Assert.AreEqual(encryptedDataBytes.Length, dataBytes.Length); return(dataBytes); }
private byte[] encryptOnRead(byte[] dataBytes) { MemoryStream dataStream = new MemoryStream(dataBytes, false); MemoryStream encryptedDataStream = new MemoryStream(); IBufferedCipher inCipher = createCipher(true); CipherStream inCipherStream = new CipherStream(dataStream, inCipher, null); int ch; while ((ch = inCipherStream.ReadByte()) >= 0) { encryptedDataStream.WriteByte((byte)ch); } encryptedDataStream.Close(); inCipherStream.Close(); byte[] encryptedDataBytes = encryptedDataStream.ToArray(); Assert.AreEqual(dataBytes.Length, encryptedDataBytes.Length); return(encryptedDataBytes); }
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()); // } }
/// <inheritdoc /> protected override void FinishItem(PayloadItem item, CipherStream encryptor, MacStream authenticator) { if (Writing) { if (item.ExternalLength > 0 && encryptor.BytesIn != item.ExternalLength) { throw new InvalidDataException("Length written is not equal to predefined item external length."); } } else { if (encryptor.BytesIn != item.InternalLength) { throw new InvalidDataException("Length read is not equal to item internal length."); } if (encryptor.BytesOut != item.ExternalLength) { throw new InvalidDataException("Demultiplexed and decrypted length is not equal to specified item external length."); } encryptor.Close(); } if (Writing) { // Commit the determined internal length to item in payload manifest item.InternalLength = encryptor.BytesOut; EmitTrailer(authenticator); } else { ConsumeTrailer(authenticator); } // Final stages of Encrypt-then-MAC authentication scheme PayloadItem itemDto = item.CreateAuthenticatibleClone(); byte[] itemDtoAuthBytes = itemDto.SerialiseDto(); Debug.Print(DebugUtility.CreateReportString("FabricPayloadMux", "FinishItem", "Item DTO length", itemDtoAuthBytes.Length)); if (Writing) { authenticator.Update(itemDtoAuthBytes, 0, itemDtoAuthBytes.Length); authenticator.Close(); // Commit the MAC to item in payload manifest item.AuthenticationVerifiedOutput = authenticator.Mac.DeepCopy(); } else { authenticator.Update(itemDtoAuthBytes, 0, itemDtoAuthBytes.Length); authenticator.Close(); // Verify the authenticity of the item ciphertext and configuration if (authenticator.Mac.SequenceEqual_ConstantTime(item.AuthenticationVerifiedOutput) == false) { // Verification failed! throw new CiphertextAuthenticationException("Payload item not authenticated."); } } // Release the item's resources (implicitly - no references remain) _activeItemResources.Remove(item.Identifier); // Mark the item as completed in the register ItemCompletionRegister[Index] = true; ItemsCompleted++; // Close the source/destination item.StreamBinding.Close(); Debug.Print(DebugUtility.CreateReportString("FabricPayloadMux", "FinishItem", "[*** END OF ITEM", Index + " ***]")); }
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)); } }
/// <summary> /// Generate an enveloped object that contains a CMS Enveloped Data /// object using the passed in key generator. /// </summary> private CmsEnvelopedData Generate( CmsProcessable content, string encryptionOid, CipherKeyGenerator keyGen) { AlgorithmIdentifier encAlgId = null; KeyParameter encKey = null; Asn1OctetString encContent; try { IBufferedCipher cipher = CipherUtilities.GetCipher(encryptionOid); byte[] encKeyBytes = keyGen.GenerateKey(); encKey = ParameterUtilities.CreateKeyParameter(encryptionOid, encKeyBytes); Asn1Encodable asn1Params = null; try { if (encryptionOid.Equals(RC2Cbc)) { // mix in a bit extra... rand.SetSeed(DateTime.Now.Ticks); byte[] iv = rand.GenerateSeed(8); // TODO Is this detailed repeat of Java version really necessary? int effKeyBits = encKeyBytes.Length * 8; int parameterVersion; if (effKeyBits < 256) { parameterVersion = rc2Table[effKeyBits]; } else { parameterVersion = effKeyBits; } asn1Params = new RC2CbcParameter(parameterVersion, iv); } else { asn1Params = ParameterUtilities.GenerateParameters(encryptionOid, rand); } } catch (SecurityUtilityException) { // No problem... no parameters generated } Asn1Object asn1Object; ICipherParameters cipherParameters; if (asn1Params != null) { asn1Object = asn1Params.ToAsn1Object(); cipherParameters = ParameterUtilities.GetCipherParameters( encryptionOid, encKey, asn1Object); } else { asn1Object = DerNull.Instance; cipherParameters = encKey; } encAlgId = new AlgorithmIdentifier( new DerObjectIdentifier(encryptionOid), asn1Object); cipher.Init(true, cipherParameters); MemoryStream bOut = new MemoryStream(); CipherStream cOut = new CipherStream(bOut, null, cipher); content.Write(cOut); cOut.Close(); encContent = new BerOctetString(bOut.ToArray()); } catch (SecurityUtilityException e) { throw new CmsException("couldn't create cipher.", e); } catch (InvalidKeyException e) { throw new CmsException("key invalid in message.", e); } catch (IOException e) { throw new CmsException("exception decoding algorithm parameters.", e); } Asn1EncodableVector recipientInfos = new Asn1EncodableVector(); foreach (RecipientInf recipient in recipientInfs) { try { recipientInfos.Add(recipient.ToRecipientInfo(encKey)); } catch (IOException e) { throw new CmsException("encoding error.", e); } catch (InvalidKeyException e) { throw new CmsException("key inappropriate for algorithm.", e); } catch (GeneralSecurityException e) { throw new CmsException("error making encrypted content.", e); } } EncryptedContentInfo eci = new EncryptedContentInfo( PkcsObjectIdentifiers.Data, encAlgId, encContent); Asn1.Cms.ContentInfo contentInfo = new Asn1.Cms.ContentInfo( PkcsObjectIdentifiers.EnvelopedData, new EnvelopedData(null, new DerSet(recipientInfos), eci, null)); return(new CmsEnvelopedData(contentInfo)); }
/// <summary> /// Close the item decorator, check lengths, authenticate the item (emit or verify), /// and if writing, commit the authentication value to the payload item DTO. /// </summary> /// <param name="item">Payload item to finish.</param> /// <param name="encryptor">Item encryptor/cipher.</param> /// <param name="authenticator">Item authenticator/MAC.</param> protected override void FinishItem(PayloadItem item, CipherStream encryptor, MacStream authenticator) { try { encryptor.Close(); } catch (Exception e) { throw new Exception("Unknown error when finalising/closing cipher.", e); } try { if (Writing) { EmitTrailer(authenticator); } else { ConsumeTrailer(authenticator); } } catch (Exception e) { throw new Exception(String.Format("Unknown error when {0} item trailer.", Writing ? "emitting" : "consuming"), e); } // Length checks & commits if (Writing) { // Check if pre-stated length matches what was actually written if (item.ExternalLength > 0 && encryptor.BytesIn != item.ExternalLength) { throw new InvalidDataException( "Mismatch between stated item external length and actual input length."); } // Commit the determined internal length to item in payload manifest item.InternalLength = encryptor.BytesOut; } else { if (encryptor.BytesIn != item.InternalLength) { throw new InvalidOperationException("Probable decorator stack malfunction."); } if (encryptor.BytesOut != item.ExternalLength) { throw new InvalidDataException( "Mismatch between stated item external length and actual output length."); } } // Final stages of Encrypt-then-MAC authentication scheme PayloadItem itemDto = item.CreateAuthenticatibleClone(); byte[] itemDtoAuthBytes = itemDto.SerialiseDto(); #if PRINT_DTO_LENGTH Debug.Print(DebugUtility.CreateReportString("SimplePayloadMux", "FinishItem", "Payload item DTO length", itemDtoAuthBytes.Length)); #endif authenticator.Update(itemDtoAuthBytes, 0, itemDtoAuthBytes.Length); authenticator.Close(); // Authentication if (Writing) { // Commit the MAC to item in payload manifest item.AuthenticationVerifiedOutput = authenticator.Mac.DeepCopy(); } else { // Verify the authenticity of the item ciphertext and configuration if (authenticator.Mac.SequenceEqual_ConstantTime(item.AuthenticationVerifiedOutput) == false) { // Verification failed! throw new CiphertextAuthenticationException("Payload item not authenticated."); } } // Close the source/destination item.StreamBinding.Close(); // Mark the item as completed in the register ItemCompletionRegister[Index] = true; ItemsCompleted++; Debug.Print(DebugUtility.CreateReportString("SimplePayloadMux", "ExecuteOperation", "[*** END OF ITEM", String.Format("{0} ({1}) ***]", Index, item.Identifier))); }
private void doRunTest( string name, int ivLength) { string lCode = "ABCDEFGHIJKLMNOPQRSTUVWXY0123456789"; string baseName = name; if (name.IndexOf('/') >= 0) { baseName = name.Substring(0, name.IndexOf('/')); } CipherKeyGenerator kGen = GeneratorUtilities.GetKeyGenerator(baseName); IBufferedCipher inCipher = CipherUtilities.GetCipher(name); IBufferedCipher outCipher = CipherUtilities.GetCipher(name); KeyParameter key = ParameterUtilities.CreateKeyParameter(baseName, kGen.GenerateKey()); MemoryStream bIn = new MemoryStream(Encoding.ASCII.GetBytes(lCode), false); MemoryStream bOut = new MemoryStream(); // In the Java build, this IV would be implicitly created and then retrieved with getIV() ICipherParameters cipherParams = key; if (ivLength > 0) { cipherParams = new ParametersWithIV(cipherParams, new byte[ivLength]); } inCipher.Init(true, cipherParams); // TODO Should we provide GetIV() method on IBufferedCipher? //if (inCipher.getIV() != null) //{ // outCipher.Init(false, new ParametersWithIV(key, inCipher.getIV())); //} //else //{ // outCipher.Init(false, key); //} outCipher.Init(false, cipherParams); CipherStream cIn = new CipherStream(bIn, inCipher, null); CipherStream cOut = new CipherStream(bOut, null, outCipher); int c; while ((c = cIn.ReadByte()) >= 0) { cOut.WriteByte((byte)c); } cIn.Close(); cOut.Flush(); cOut.Close(); byte[] bs = bOut.ToArray(); string res = Encoding.ASCII.GetString(bs, 0, bs.Length); if (!res.Equals(lCode)) { Fail("Failed - decrypted data doesn't match."); } }
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 byte[] decryptOnRead(byte[] encryptedDataBytes) { MemoryStream encryptedDataStream = new MemoryStream(encryptedDataBytes, false); MemoryStream dataStream = new MemoryStream(); IBufferedCipher inCipher = createCipher(false); CipherStream inCipherStream = new CipherStream(encryptedDataStream, inCipher, null); int ch; while ((ch = inCipherStream.ReadByte()) >= 0) { dataStream.WriteByte((byte) ch); } inCipherStream.Close(); dataStream.Close(); byte[] dataBytes = dataStream.ToArray(); Assert.AreEqual(encryptedDataBytes.Length, dataBytes.Length); return dataBytes; }
/// <summary> /// Generate an enveloped object that contains a CMS Enveloped Data /// object using the passed in key generator. /// </summary> private CmsEnvelopedData Generate( CmsProcessable content, string encryptionOid, CipherKeyGenerator keyGen) { AlgorithmIdentifier encAlgId = null; KeyParameter encKey; Asn1OctetString encContent; try { byte[] encKeyBytes = keyGen.GenerateKey(); encKey = ParameterUtilities.CreateKeyParameter(encryptionOid, encKeyBytes); Asn1Encodable asn1Params = GenerateAsn1Parameters(encryptionOid, encKeyBytes); ICipherParameters cipherParameters; encAlgId = GetAlgorithmIdentifier( encryptionOid, encKey, asn1Params, out cipherParameters); IBufferedCipher cipher = CipherUtilities.GetCipher(encryptionOid); cipher.Init(true, new ParametersWithRandom(cipherParameters, rand)); MemoryStream bOut = new MemoryStream(); CipherStream cOut = new CipherStream(bOut, null, cipher); content.Write(cOut); cOut.Close(); encContent = new BerOctetString(bOut.ToArray()); } catch (SecurityUtilityException e) { throw new CmsException("couldn't create cipher.", e); } catch (InvalidKeyException e) { throw new CmsException("key invalid in message.", e); } catch (IOException e) { throw new CmsException("exception decoding algorithm parameters.", e); } Asn1EncodableVector recipientInfos = new Asn1EncodableVector(); foreach (RecipientInfoGenerator rig in recipientInfoGenerators) { try { recipientInfos.Add(rig.Generate(encKey, rand)); } catch (InvalidKeyException e) { throw new CmsException("key inappropriate for algorithm.", e); } catch (GeneralSecurityException e) { throw new CmsException("error making encrypted content.", e); } } EncryptedContentInfo eci = new EncryptedContentInfo( CmsObjectIdentifiers.Data, encAlgId, encContent); Asn1Set unprotectedAttrSet = null; if (unprotectedAttributeGenerator != null) { Asn1.Cms.AttributeTable attrTable = unprotectedAttributeGenerator.GetAttributes(Platform.CreateHashtable()); unprotectedAttrSet = new BerSet(attrTable.ToAsn1EncodableVector()); } ContentInfo contentInfo = new ContentInfo( CmsObjectIdentifiers.EnvelopedData, new EnvelopedData(null, new DerSet(recipientInfos), eci, unprotectedAttrSet)); return(new CmsEnvelopedData(contentInfo)); }
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); }
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 CmsEnvelopedData Generate(CmsProcessable content, string encryptionOid, CipherKeyGenerator keyGen) { AlgorithmIdentifier contentEncryptionAlgorithm = null; KeyParameter keyParameter; Asn1OctetString encryptedContent; try { byte[] array = keyGen.GenerateKey(); keyParameter = ParameterUtilities.CreateKeyParameter(encryptionOid, array); Asn1Encodable asn1Params = this.GenerateAsn1Parameters(encryptionOid, array); ICipherParameters parameters; contentEncryptionAlgorithm = this.GetAlgorithmIdentifier(encryptionOid, keyParameter, asn1Params, out parameters); IBufferedCipher cipher = CipherUtilities.GetCipher(encryptionOid); cipher.Init(true, new ParametersWithRandom(parameters, this.rand)); MemoryStream memoryStream = new MemoryStream(); CipherStream cipherStream = new CipherStream(memoryStream, null, cipher); content.Write(cipherStream); cipherStream.Close(); encryptedContent = new BerOctetString(memoryStream.ToArray()); } catch (SecurityUtilityException e) { throw new CmsException("couldn't create cipher.", e); } catch (InvalidKeyException e2) { throw new CmsException("key invalid in message.", e2); } catch (IOException e3) { throw new CmsException("exception decoding algorithm parameters.", e3); } Asn1EncodableVector asn1EncodableVector = new Asn1EncodableVector(new Asn1Encodable[0]); foreach (RecipientInfoGenerator recipientInfoGenerator in this.recipientInfoGenerators) { try { asn1EncodableVector.Add(new Asn1Encodable[] { recipientInfoGenerator.Generate(keyParameter, this.rand) }); } catch (InvalidKeyException e4) { throw new CmsException("key inappropriate for algorithm.", e4); } catch (GeneralSecurityException e5) { throw new CmsException("error making encrypted content.", e5); } } EncryptedContentInfo encryptedContentInfo = new EncryptedContentInfo(CmsObjectIdentifiers.Data, contentEncryptionAlgorithm, encryptedContent); Asn1Set unprotectedAttrs = null; if (this.unprotectedAttributeGenerator != null) { Org.BouncyCastle.Asn1.Cms.AttributeTable attributes = this.unprotectedAttributeGenerator.GetAttributes(Platform.CreateHashtable()); unprotectedAttrs = new BerSet(attributes.ToAsn1EncodableVector()); } ContentInfo contentInfo = new ContentInfo(CmsObjectIdentifiers.EnvelopedData, new EnvelopedData(null, new DerSet(asn1EncodableVector), encryptedContentInfo, unprotectedAttrs)); return(new CmsEnvelopedData(contentInfo)); }