public void AESDecryption() { var dataString = "YSholLwd6hNXsLPHW+DZQsdhFutxTGa04L6E4ySBQ4ihyjZ/7iH9VdqAiEsmFLrNNaHT+RfGAJfqmwoAfS2E0uJI/dY3UkuiBq152iKnoWkEhphdkAeerQwBbCCl82F6/2ezoyBbTomwkalyV32djQF7Xh5jxJGw1xorldxX6WUJ/a3g4EPU7zAIVBElx+kOJm4TwfiznJoNAArVFp96MxjDe4aHrVNpPSFzQrVKdgTVsXuqTaX5j0Dq1bHfZZ539L7C/yTT1mSCO9BCWdyclquDdKwf40V+Up0eMYgV8tGMqI5r0I8OaU7djD66Jv/HICikqFOLwPoHj7uQby/SXMKPKxA/7UVfDFeNHrC7ZXdIj2LDv7NC2WHG/c92qDoORbuO20+dLWUGqyKnwYx4Xh7EqBfVM2uQErbH9pk2DZ1WL93I6zdoGtRwzQBI7GwRY0KtPchJICdHkjA42s3U0g=="; var keyString = "1q3kw4BhAAtT0SJkZ0a8EA=="; var expected = "{\"uuid\":\"3622482f-465b-4f6b-9beb-44f508b59016\",\"event\":\"/restapi/v1.0/account/~/extension/850957020/message-store\",\"timestamp\":\"2016-05-25T00:54:36.834Z\",\"subscriptionId\":\"57b5d366-ab22-490b-9754-b60fa6aab373\",\"body\":{\"extensionId\":850957020,\"lastUpdated\":\"2016-05-25T00:54:22.055+0000\",\"changes\":[{\"type\":\"SMS\",\"newCount\":0,\"updatedCount\":1}]}}"; var key = Convert.FromBase64String(keyString); var keyParameter = ParameterUtilities.CreateKeyParameter("AES", key); var cipher = CipherUtilities.GetCipher("AES/ECB/PKCS7Padding"); cipher.Init(false, keyParameter); var data = Convert.FromBase64String(dataString); var memoryStream = new MemoryStream(data, false); var cipherStream = new CipherStream(memoryStream, cipher, null); var bufferSize = 1024; var buffer = new byte[bufferSize]; var length = 0; var resultStream = new MemoryStream(); while ((length = cipherStream.Read(buffer, 0, bufferSize)) > 0) { resultStream.Write(buffer, 0, length); } var result = Encoding.UTF8.GetString(resultStream.ToArray()); Assert.AreEqual(expected, result); }
public MonoAesStream(System.IO.Stream stream, byte[] key) { BaseStream = stream; BufferedBlockCipher enc = GenerateAES(key, true); BufferedBlockCipher dec = GenerateAES(key, false); cstream = new CipherStream(stream, dec, enc); }
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 void doCipherTest( int strength, byte[] keyBytes, byte[] input, byte[] output) { KeyParameter key = ParameterUtilities.CreateKeyParameter("SEED", keyBytes); IBufferedCipher inCipher = CipherUtilities.GetCipher("SEED/ECB/NoPadding"); IBufferedCipher outCipher = CipherUtilities.GetCipher("SEED/ECB/NoPadding"); try { outCipher.Init(true, key); } catch (Exception e) { Fail("SEED failed initialisation - " + e.ToString(), e); } try { inCipher.Init(false, key); } catch (Exception e) { Fail("SEED failed initialisation - " + e.ToString(), 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("SEED failed encryption - " + e.ToString(), e); } byte[] bytes = bOut.ToArray(); if (!AreEqual(bytes, output)) { Fail("SEED 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("SEED failed encryption - " + e.ToString(), e); } if (!AreEqual(bytes, input)) { Fail("SEED failed decryption - expected " + Hex.ToHexString(input) + " got " + Hex.ToHexString(bytes)); } }
/// <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; } }
/// <summary> /// <p> /// If buffer is non null stream assumed to be partial, otherwise the length will be used /// to output a fixed length packet. /// </p> /// <p> /// The stream created can be closed off by either calling Close() /// on the stream or Close() on the generator. Closing the returned /// stream does not close off the Stream parameter <c>outStr</c>. /// </p> /// </summary> private Stream Open( Stream outStr, long length, byte[] buffer) { if (cOut != null) throw new InvalidOperationException("generator already in open state"); if (methods.Count == 0) throw new InvalidOperationException("No encryption methods specified"); if (outStr == null) throw new ArgumentNullException("outStr"); pOut = new BcpgOutputStream(outStr); KeyParameter key; if (methods.Count == 1) { if (methods[0] is PbeMethod) { PbeMethod m = (PbeMethod)methods[0]; key = m.GetKey(); } else { key = PgpUtilities.MakeRandomKey(defAlgorithm, rand); byte[] sessionInfo = CreateSessionInfo(defAlgorithm, key); PubMethod m = (PubMethod)methods[0]; try { m.AddSessionInfo(sessionInfo, rand); } catch (Exception e) { throw new PgpException("exception encrypting session key", e); } } pOut.WritePacket((ContainedPacket)methods[0]); } else // multiple methods { key = PgpUtilities.MakeRandomKey(defAlgorithm, rand); byte[] sessionInfo = CreateSessionInfo(defAlgorithm, key); for (int i = 0; i != methods.Count; i++) { EncMethod m = (EncMethod)methods[i]; try { m.AddSessionInfo(sessionInfo, rand); } catch (Exception e) { throw new PgpException("exception encrypting session key", e); } pOut.WritePacket(m); } } string cName = PgpUtilities.GetSymmetricCipherName(defAlgorithm); if (cName == null) { throw new PgpException("null cipher specified"); } try { if (withIntegrityPacket) { cName += "/CFB/NoPadding"; } else { cName += "/OpenPGPCFB/NoPadding"; } c = CipherUtilities.GetCipher(cName); // TODO Confirm the IV should be all zero bytes (not inLineIv - see below) byte[] iv = new byte[c.GetBlockSize()]; c.Init(true, new ParametersWithRandom(new ParametersWithIV(key, iv), rand)); if (buffer == null) { // // we have to Add block size + 2 for the Generated IV and + 1 + 22 if integrity protected // if (withIntegrityPacket) { pOut = new BcpgOutputStream(outStr, PacketTag.SymmetricEncryptedIntegrityProtected, length + c.GetBlockSize() + 2 + 1 + 22); pOut.WriteByte(1); // version number } else { pOut = new BcpgOutputStream(outStr, PacketTag.SymmetricKeyEncrypted, length + c.GetBlockSize() + 2, oldFormat); } } else { if (withIntegrityPacket) { pOut = new BcpgOutputStream(outStr, PacketTag.SymmetricEncryptedIntegrityProtected, buffer); pOut.WriteByte(1); // version number } else { pOut = new BcpgOutputStream(outStr, PacketTag.SymmetricKeyEncrypted, buffer); } } int blockSize = c.GetBlockSize(); byte[] inLineIv = new byte[blockSize + 2]; rand.NextBytes(inLineIv, 0, blockSize); Array.Copy(inLineIv, inLineIv.Length - 4, inLineIv, inLineIv.Length - 2, 2); Stream myOut = cOut = new CipherStream(pOut, null, c); if (withIntegrityPacket) { string digestName = PgpUtilities.GetDigestName(HashAlgorithmTag.Sha1); IDigest digest = DigestUtilities.GetDigest(digestName); myOut = digestOut = new DigestStream(myOut, null, digest); } myOut.Write(inLineIv, 0, inLineIv.Length); return new WrappedGeneratorStream(this, myOut); } catch (Exception e) { throw new PgpException("Exception creating cipher", e); } }
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 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)); } }
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"); }
/// <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.Dispose(); 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 object Decrypt(string dataString) { var key = Convert.FromBase64String(subscriptionInfo.DeliveryMode.EncryptionKey); var keyParameter = ParameterUtilities.CreateKeyParameter("AES", key); var cipher = CipherUtilities.GetCipher("AES/ECB/PKCS7Padding"); cipher.Init(false, keyParameter); var data = Convert.FromBase64String(dataString); var memoryStream = new MemoryStream(data, false); var cipherStream = new CipherStream(memoryStream, cipher, null); var bufferSize = 1024; var buffer = new byte[bufferSize]; var length = 0; var resultStream = new MemoryStream(); while ((length = cipherStream.Read(buffer, 0, bufferSize)) > 0) { resultStream.Write(buffer, 0, length); } var resultBytes = resultStream.ToArray(); var result = Encoding.UTF8.GetString(resultBytes, 0, resultBytes.Length); return JsonConvert.DeserializeObject(result); }
private void doTest( 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("DESEDE"); keyGen.Init(new KeyGenerationParameters(rand, strength)); key = new DesEdeParameters(keyGen.GenerateKey()); inCipher = CipherUtilities.GetCipher("DESEDE/ECB/PKCS7Padding"); outCipher = CipherUtilities.GetCipher("DESEDE/ECB/PKCS7Padding"); outCipher.Init(true, new ParametersWithRandom(key, rand)); } catch (Exception e) { Fail("DESEDE failed initialisation - " + e.ToString()); } try { inCipher.Init(false, key); } catch (Exception e) { Fail("DESEDE 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("DESEDE failed encryption - " + e.ToString()); } byte[] bytes = bOut.ToArray(); if (!Arrays.AreEqual(bytes, output)) { Fail("DESEDE 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("DESEDE failed encryption - " + e.ToString()); } if (!Arrays.AreEqual(bytes, input)) { Fail("DESEDE failed decryption - expected " + Hex.ToHexString(input) + " got " + Hex.ToHexString(bytes)); } // TODO Put back in // // // // keyspec test // // // try // { // SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DESede"); // DESedeKeySpec keySpec = (DESedeKeySpec)keyFactory.getKeySpec((SecretKey)key, DESedeKeySpec.class); // // if (!equalArray(key.getEncoded(), keySpec.getKey(), 16)) // { // Fail("DESEDE KeySpec does not match key."); // } // } // catch (Exception e) // { // Fail("DESEDE failed keyspec - " + e.ToString()); // } }
public static void Main(string[] args) { string password=null; bool encrypt=false; string salt=DEFAULT_SALT; string algorithm=null; string mode=null; string padding=null; string output=null; string type=null; string digest=null; int keySize=DEFAULT_KEY_SIZE; int iterations=DEFAULT_ITERATIONS; bool showHelp=false; OptionSet p = new OptionSet () { {"a|algo=","Encryption algorithm (AES, RC4, RC2, DES, BLOWFISH, TWOFISH)",v=>algorithm=v}, {"m|mode=","Block cipher mode (NONE, CBC, CTR, CFB, OFB)",v=>mode=v}, {"b|padding=","Block padding (NONE, PKCS7, ISO10126d2, ISO7816d4, X932, ZEROBYTE)",v=>padding=v}, {"p|password="******"Encryption password",v=>password=v}, {"k|keysize=","Key size",(int v)=>keySize=v}, {"d|digest=","Digest algorithm (SHA1, SHA224, SHA256, SHA384, SHA512, MD2, MD4, MD5)", v=>digest=v}, {"s|salt=","Salt phrase",v=>salt=v}, {"i|iterations=","Number of iterations",(int v)=>iterations=v}, {"e|encrypt","Encrypt",v=>encrypt= v!= null}, {"t|type=","Type (PKCS12, OPENSSL)",v=>type=v}, {"o|output=","Output directory",v=>output=v}, {"h|help","Help", v => showHelp = v != null} }; List<string> files; try { files = p.Parse (args); if (showHelp) { ShowHelp (p); return; } if(files.Count==0 || output==null || password==null || algorithm==null){ throw new OptionException(); } } catch (OptionException e) { Console.WriteLine ("kpbe: Missing options"); Console.WriteLine ("Try `kpbe --help' for more information."); return; } BasePbeCipher pbeCipher=null; try{ Pbe pbe=new Pbe(algorithm.ToUpper(), mode, padding, digest, password.ToCharArray(), Utils.ToByteArray(salt), iterations,keySize); pbeCipher=new Pkcs12PbeCipher(pbe); if(type!=null && type.ToUpper().Equals(Kpbe.Types.OPENSSL)){ pbeCipher=new OpenSSLPbeCipher(pbe); } }catch(Exception e){ Console.WriteLine("kpbe: "+e.Message); return; } foreach(string file in files){ FileInfo fi=new FileInfo(file); if(!fi.Exists){ Console.WriteLine ("kpbe: File "+file+" not found."); return; } try{ DirectoryInfo odir=Directory.CreateDirectory(output); Stream ins=new FileStream(file, FileMode.Open); Stream outs=new FileStream(odir.FullName+"/"+fi.Name, FileMode.Create); CipherStream cipherStream=new CipherStream(ins,pbeCipher.createCipher(encrypt), null); int ch; while ((ch = cipherStream.ReadByte()) >= 0) { outs.WriteByte((byte) ch); } cipherStream.Close(); outs.Close(); }catch(CryptoException e){ Console.WriteLine("kpbe: "+e.Message); }catch(ArgumentException e){ Console.WriteLine("kpbe: "+e.Message); }catch(Exception e){ Console.WriteLine(e); } } }
protected Stream Open( Stream outStream, string encryptionOid, KeyParameter encKey, Asn1Encodable asn1Params, Asn1EncodableVector recipientInfos) { Asn1Object asn1Object; ICipherParameters cipherParameters; if (asn1Params != null) { asn1Object = asn1Params.ToAsn1Object(); cipherParameters = ParameterUtilities.GetCipherParameters( encryptionOid, encKey, asn1Object); } else { asn1Object = DerNull.Instance; cipherParameters = encKey; } try { AlgorithmIdentifier encAlgId = new AlgorithmIdentifier( new DerObjectIdentifier(encryptionOid), asn1Object); // // ContentInfo // BerSequenceGenerator cGen = new BerSequenceGenerator(outStream); cGen.AddObject(CmsObjectIdentifiers.EnvelopedData); // // Encrypted Data // BerSequenceGenerator envGen = new BerSequenceGenerator( cGen.GetRawOutputStream(), 0, true); envGen.AddObject(this.Version); DerSet derSet = _berEncodeRecipientSet ? new BerSet(recipientInfos) : new DerSet(recipientInfos); byte[] derSetEncoding = derSet.GetEncoded(); envGen.GetRawOutputStream().Write(derSetEncoding, 0, derSetEncoding.Length); IBufferedCipher cipher = CipherUtilities.GetCipher(encryptionOid); cipher.Init(true, cipherParameters); BerSequenceGenerator eiGen = new BerSequenceGenerator( envGen.GetRawOutputStream()); eiGen.AddObject(PkcsObjectIdentifiers.Data); byte[] tmp = encAlgId.GetEncoded(); eiGen.GetRawOutputStream().Write(tmp, 0, tmp.Length); BerOctetStringGenerator octGen = new BerOctetStringGenerator( eiGen.GetRawOutputStream(), 0, false); Stream octetOutputStream = _bufferSize != 0 ? octGen.GetOctetOutputStream(new byte[_bufferSize]) : octGen.GetOctetOutputStream(); CipherStream cOut = new CipherStream(octetOutputStream, null, cipher); return new CmsEnvelopedDataOutputStream(cOut, cGen, envGen, eiGen); } 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); } }
private Stream Open( Stream outStream, AlgorithmIdentifier encAlgID, ICipherParameters cipherParameters, Asn1EncodableVector recipientInfos) { try { // // ContentInfo // BerSequenceGenerator cGen = new BerSequenceGenerator(outStream); cGen.AddObject(CmsObjectIdentifiers.EnvelopedData); // // Encrypted Data // BerSequenceGenerator envGen = new BerSequenceGenerator( cGen.GetRawOutputStream(), 0, true); envGen.AddObject(this.Version); Stream envRaw = envGen.GetRawOutputStream(); Asn1Generator recipGen = _berEncodeRecipientSet ? (Asn1Generator) new BerSetGenerator(envRaw) : new DerSetGenerator(envRaw); foreach (Asn1Encodable ae in recipientInfos) { recipGen.AddObject(ae); } recipGen.Close(); BerSequenceGenerator eiGen = new BerSequenceGenerator(envRaw); eiGen.AddObject(CmsObjectIdentifiers.Data); eiGen.AddObject(encAlgID); Stream octetOutputStream = CmsUtilities.CreateBerOctetOutputStream( eiGen.GetRawOutputStream(), 0, false, _bufferSize); IBufferedCipher cipher = CipherUtilities.GetCipher(encAlgID.ObjectID); cipher.Init(true, new ParametersWithRandom(cipherParameters, rand)); CipherStream cOut = new CipherStream(octetOutputStream, null, cipher); return new CmsEnvelopedDataOutputStream(this, cOut, cGen, envGen, eiGen); } 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); } }
public CmsEnvelopedDataOutputStream( CmsEnvelopedGenerator outer, CipherStream outStream, BerSequenceGenerator cGen, BerSequenceGenerator envGen, BerSequenceGenerator eiGen) { _outer = outer; _out = outStream; _cGen = cGen; _envGen = envGen; _eiGen = eiGen; }
/// <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 { 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); }