private void InitializeRSA() { string[] keyComponents = publicKey.Split('|'); var modulus = new Org.BouncyCastle.Math.BigInteger(keyComponents[1].ToLower(), 16); var exponent = new Org.BouncyCastle.Math.BigInteger(keyComponents[0].ToLower(), 16); RsaKeyParameters keyParams = new RsaKeyParameters(false, modulus, exponent); rsaCipher = CipherUtilities.GetCipher("RSA/None/PKCS1Padding"); rsaCipher.Init(true, keyParams); }
public byte[] EnDecrypt(bool forEncrypt, byte[] inBytes) { cipher = CipherUtilities.GetCipher(algorithm); cipher.Init(forEncrypt, key); int outBytesSize = cipher.GetOutputSize(inBytes.Length); byte[] outBytes = new byte[outBytesSize]; int outLentgh; outLentgh = cipher.ProcessBytes(inBytes, 0, inBytes.Length, outBytes, 0); outLentgh += cipher.DoFinal(outBytes, outLentgh); if (outLentgh != outBytesSize) { return null; } return outBytes; }
private void doTestException( string name, int ivLength) { try { byte[] key128 = { (byte)128, (byte)131, (byte)133, (byte)134, (byte)137, (byte)138, (byte)140, (byte)143, (byte)128, (byte)131, (byte)133, (byte)134, (byte)137, (byte)138, (byte)140, (byte)143 }; byte[] key256 = { (byte)128, (byte)131, (byte)133, (byte)134, (byte)137, (byte)138, (byte)140, (byte)143, (byte)128, (byte)131, (byte)133, (byte)134, (byte)137, (byte)138, (byte)140, (byte)143, (byte)128, (byte)131, (byte)133, (byte)134, (byte)137, (byte)138, (byte)140, (byte)143, (byte)128, (byte)131, (byte)133, (byte)134, (byte)137, (byte)138, (byte)140, (byte)143 }; byte[] keyBytes; if (name.Equals("HC256")) { keyBytes = key256; } else { keyBytes = key128; } KeyParameter cipherKey = ParameterUtilities.CreateKeyParameter(name, keyBytes); ICipherParameters cipherParams = cipherKey; if (ivLength > 0) { cipherParams = new ParametersWithIV(cipherParams, new byte[ivLength]); } IBufferedCipher ecipher = CipherUtilities.GetCipher(name); ecipher.Init(true, cipherParams); byte[] cipherText = new byte[0]; try { // According specification Method engineUpdate(byte[] input, // int inputOffset, int inputLen, byte[] output, int // outputOffset) // throws ShortBufferException - if the given output buffer is // too // small to hold the result ecipher.ProcessBytes(new byte[20], 0, 20, cipherText, 0); // Fail("failed exception test - no ShortBufferException thrown"); Fail("failed exception test - no DataLengthException thrown"); } // catch (ShortBufferException e) catch (DataLengthException) { // ignore } // NB: The lightweight engine doesn't take public/private keys // try // { // IBufferedCipher c = CipherUtilities.GetCipher(name); // // // Key k = new PublicKey() // // { // // // // public string getAlgorithm() // // { // // return "STUB"; // // } // // // // public string getFormat() // // { // // return null; // // } // // // // public byte[] getEncoded() // // { // // return null; // // } // // // // }; // IAsymmetricKeyParameter k = new AsymmetricKeyParameter(false); // c.Init(true, k); // // Fail("failed exception test - no InvalidKeyException thrown for public key"); // } // catch (InvalidKeyException) // { // // okay // } // // try // { // IBufferedCipher c = CipherUtilities.GetCipher(name); // // // Key k = new PrivateKey() // // { // // // // public string getAlgorithm() // // { // // return "STUB"; // // } // // // // public string getFormat() // // { // // return null; // // } // // // // public byte[] getEncoded() // // { // // return null; // // } // // // // }; // // IAsymmetricKeyParameter k = new AsymmetricKeyParameter(true); // c.Init(false, k); // // Fail("failed exception test - no InvalidKeyException thrown for private key"); // } // catch (InvalidKeyException) // { // // okay // } } catch (Exception e) { Fail("unexpected exception.", e); } }
internal Stream DoGetDataStream(byte[] rawPassPhrase, bool clearPassPhrase) { try { SymmetricKeyAlgorithmTag keyAlgorithm = keyData.EncAlgorithm; KeyParameter key = PgpUtilities.DoMakeKeyFromPassPhrase( keyAlgorithm, keyData.S2k, rawPassPhrase, clearPassPhrase); byte[] secKeyData = keyData.GetSecKeyData(); if (secKeyData != null && secKeyData.Length > 0) { IBufferedCipher keyCipher = CipherUtilities.GetCipher( PgpUtilities.GetSymmetricCipherName(keyAlgorithm) + "/CFB/NoPadding"); keyCipher.Init(false, new ParametersWithIV(key, new byte[keyCipher.GetBlockSize()])); byte[] keyBytes = keyCipher.DoFinal(secKeyData); keyAlgorithm = (SymmetricKeyAlgorithmTag)keyBytes[0]; key = ParameterUtilities.CreateKeyParameter( PgpUtilities.GetSymmetricCipherName(keyAlgorithm), keyBytes, 1, keyBytes.Length - 1); } IBufferedCipher c = CreateStreamCipher(keyAlgorithm); byte[] iv = new byte[c.GetBlockSize()]; c.Init(false, new ParametersWithIV(key, iv)); encStream = BcpgInputStream.Wrap(new CipherStream(encData.GetInputStream(), c, null)); if (encData is SymmetricEncIntegrityPacket) { truncStream = new TruncatedStream(encStream); string digestName = PgpUtilities.GetDigestName(HashAlgorithmTag.Sha1); IDigest digest = DigestUtilities.GetDigest(digestName); encStream = new DigestStream(truncStream, digest, null); } if (Streams.ReadFully(encStream, iv, 0, iv.Length) < iv.Length) { throw new EndOfStreamException("unexpected end of stream."); } int v1 = encStream.ReadByte(); int v2 = encStream.ReadByte(); if (v1 < 0 || v2 < 0) { throw new EndOfStreamException("unexpected end of stream."); } // Note: the oracle attack on the "quick check" bytes is not deemed // a security risk for PBE (see PgpPublicKeyEncryptedData) bool repeatCheckPassed = iv[iv.Length - 2] == (byte)v1 && iv[iv.Length - 1] == (byte)v2; // Note: some versions of PGP appear to produce 0 for the extra // bytes rather than repeating the two previous bytes bool zeroesCheckPassed = v1 == 0 && v2 == 0; if (!repeatCheckPassed && !zeroesCheckPassed) { throw new PgpDataValidationException("quick check failed."); } return(encStream); } catch (PgpException e) { throw e; } catch (Exception e) { throw new PgpException("Exception creating cipher", e); } }
private CmsEnvelopedData Generate(CmsProcessable content, string encryptionOid, CipherKeyGenerator keyGen) { AlgorithmIdentifier algorithmIdentifier = null; KeyParameter keyParameter; Asn1OctetString encryptedContent; try { byte[] array = keyGen.GenerateKey(); keyParameter = ParameterUtilities.CreateKeyParameter(encryptionOid, array); Asn1Encodable asn1Params = GenerateAsn1Parameters(encryptionOid, array); algorithmIdentifier = GetAlgorithmIdentifier(encryptionOid, keyParameter, asn1Params, out ICipherParameters cipherParameters); IBufferedCipher cipher = CipherUtilities.GetCipher(encryptionOid); cipher.Init(forEncryption: true, new ParametersWithRandom(cipherParameters, rand)); MemoryStream memoryStream = new MemoryStream(); CipherStream cipherStream = new CipherStream(memoryStream, null, cipher); content.Write(cipherStream); Platform.Dispose(cipherStream); 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(); foreach (RecipientInfoGenerator recipientInfoGenerator in recipientInfoGenerators) { try { asn1EncodableVector.Add(recipientInfoGenerator.Generate(keyParameter, 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, algorithmIdentifier, encryptedContent); Asn1Set unprotectedAttrs = null; if (unprotectedAttributeGenerator != null) { Org.BouncyCastle.Asn1.Cms.AttributeTable attributes = 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)); }
internal static byte[] AESKeyWrapDecrypt(byte[] rgbKey, byte[] rgbEncryptedWrappedKeyData) { int N = (rgbEncryptedWrappedKeyData.Length >> 3) - 1; // The information wrapped need not actually be a key, but it needs to be a multiple of 64 bits if ((rgbEncryptedWrappedKeyData.Length % 8 != 0) || N <= 0) { throw new System.Security.Cryptography.CryptographicException(SR.Cryptography_Xml_KW_BadKeySize); } byte[] rgbOutput = new byte[N << 3]; IBufferedCipher dec = null; try { // Use ECB mode, no padding dec = CipherUtilities.GetCipher("AES/ECB/NOPADDING"); dec.Init(false, new KeyParameter(rgbKey)); // special case: only 1 block -- 8 bytes if (N == 1) { byte[] temp = dec.DoFinal(rgbEncryptedWrappedKeyData); // checksum the key for (int index = 0; index < 8; index++) { if (temp[index] != s_rgbAES_KW_IV[index]) { throw new System.Security.Cryptography.CryptographicException(SR.Cryptography_Xml_BadWrappedKeySize); } } // rgbOutput is LSB(temp) Buffer.BlockCopy(temp, 8, rgbOutput, 0, 8); return(rgbOutput); } // second case: more than 1 block long t = 0; // initialize the C_i's Buffer.BlockCopy(rgbEncryptedWrappedKeyData, 8, rgbOutput, 0, rgbOutput.Length); byte[] rgbA = new byte[8]; byte[] rgbBlock = new byte[16]; Buffer.BlockCopy(rgbEncryptedWrappedKeyData, 0, rgbA, 0, 8); for (int j = 5; j >= 0; j--) { for (int i = N; i >= 1; i--) { t = i + j * N; for (int k = 0; k < 8; k++) { byte tmp = (byte)((t >> (8 * (7 - k))) & 0xFF); rgbA[k] ^= tmp; } Buffer.BlockCopy(rgbA, 0, rgbBlock, 0, 8); Buffer.BlockCopy(rgbOutput, 8 * (i - 1), rgbBlock, 8, 8); byte[] rgbB = dec.DoFinal(rgbBlock); Buffer.BlockCopy(rgbB, 8, rgbOutput, 8 * (i - 1), 8); Buffer.BlockCopy(rgbB, 0, rgbA, 0, 8); } } // checksum the key for (int index = 0; index < 8; index++) { if (rgbA[index] != s_rgbAES_KW_IV[index]) { throw new System.Security.Cryptography.CryptographicException(SR.Cryptography_Xml_BadWrappedKeySize); } } return(rgbOutput); } finally { } }
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.Algorithm); 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 void DoTest( int strength, byte[] keyBytes, byte[] input, byte[] output) { KeyParameter key = ParameterUtilities.CreateKeyParameter("Noekeon", keyBytes); IBufferedCipher inCipher = CipherUtilities.GetCipher("Noekeon/ECB/NoPadding"); IBufferedCipher outCipher = CipherUtilities.GetCipher("Noekeon/ECB/NoPadding"); try { outCipher.Init(true, key); } catch (Exception e) { Fail("Noekeon failed initialisation - " + e.Message, e); } try { inCipher.Init(false, key); } catch (Exception e) { Fail("Noekeoen failed initialisation - " + e.Message, 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("Noekeon failed encryption - " + e.Message, e); } byte[] bytes = bOut.ToArray(); if (!AreEqual(bytes, output)) { Fail("Noekeon 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("Noekeon failed encryption - " + e.Message, e); } if (!AreEqual(bytes, input)) { Fail("Noekeon failed decryption - expected " + Hex.ToHexString(input) + " got " + Hex.ToHexString(bytes)); } }
public void Init(bool forWrapping, ICipherParameters parameters) { this.forWrapping = forWrapping; cipher.Init(forWrapping, parameters); }
/// <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)); }
private static void DecryptThread(IBufferedCipher cipher, byte[] input, BlockingCollection <string> producerConsumerCollection, bool allPaddings = false) { var taskOutputs = new StringBuilder(); int lineCount = 0; IBlockCipherPadding[] paddings; if (allPaddings) { paddings = new IBlockCipherPadding[] { new ZeroBytePadding(), new ISO10126d2Padding(), new ISO7816d4Padding(), new Pkcs7Padding(), new TbcPadding(), new X923Padding(), new X923Padding(), }; } else { paddings = new IBlockCipherPadding[] { new Pkcs7Padding() }; } while (!producerConsumerCollection.IsCompleted) { string line; try { line = producerConsumerCollection.Take(); } catch (InvalidOperationException) { if (producerConsumerCollection.IsCompleted) { break; } throw; } // Use that line as the key. byte[] key = Encoding.ASCII.GetBytes(line); // For each possible padding... foreach (IBlockCipherPadding padding in paddings) { // Decrypt byte[] output; try { cipher.Init(false, new KeyParameter(key)); output = cipher.DoFinal(input); cipher.Reset(); } catch (InvalidCipherTextException) { // TODO: Possibly filder out those inputs before and/or tell the user not to generate them. continue; } // Convert to hexadecimal. foreach (byte b in output) { taskOutputs.Append(HexStringTable[b]); } taskOutputs.AppendFormat(" `{0}` [{1}]", line, padding.PaddingName); taskOutputs.AppendLine(); ++lineCount; } // Output the hashed values in a batch. if (taskOutputs.Length > 100000) { Console.Write(taskOutputs.ToString()); taskOutputs.Clear(); lineCount = 0; } } // Output the last hashed values. Console.Write(taskOutputs.ToString()); }
internal static byte[] Crypt(bool encrypt, byte[] bytes, char[] password, string dekAlgName, byte[] iv) { ParseDekAlgName(dekAlgName, out var baseAlg, out var mode); string text; switch (mode) { case PemMode.CBC: case PemMode.ECB: text = "PKCS5Padding"; break; case PemMode.CFB: case PemMode.OFB: text = "NoPadding"; break; default: throw new EncryptionException("Unknown DEK algorithm: " + dekAlgName); } byte[] array = iv; string text2; switch (baseAlg) { case PemBaseAlg.AES_128: case PemBaseAlg.AES_192: case PemBaseAlg.AES_256: text2 = "AES"; if (array.Length > 8) { array = new byte[8]; global::System.Array.Copy((global::System.Array)iv, 0, (global::System.Array)array, 0, array.Length); } break; case PemBaseAlg.BF: text2 = "BLOWFISH"; break; case PemBaseAlg.DES: text2 = "DES"; break; case PemBaseAlg.DES_EDE: case PemBaseAlg.DES_EDE3: text2 = "DESede"; break; case PemBaseAlg.RC2: case PemBaseAlg.RC2_40: case PemBaseAlg.RC2_64: text2 = "RC2"; break; default: throw new EncryptionException("Unknown DEK algorithm: " + dekAlgName); } string algorithm = string.Concat(new object[5] { text2, "/", mode, "/", text }); IBufferedCipher cipher = CipherUtilities.GetCipher(algorithm); ICipherParameters parameters = GetCipherParameters(password, baseAlg, array); if (mode != PemMode.ECB) { parameters = new ParametersWithIV(parameters, iv); } cipher.Init(encrypt, parameters); return(cipher.DoFinal(bytes)); }
public override void PerformTest() { byte[] input = Hex.Decode("1234567890abcdefabcdef1234567890fedbca098765"); // // DES // IBufferedCipher cEnc = CipherUtilities.GetCipher("DES/CBC/PKCS7Padding"); cEnc.Init( true, new ParametersWithIV( new DesParameters(Hex.Decode("30e69252758e5346")), Hex.Decode("7c1c1ab9c454a688"))); byte[] outBytes = cEnc.DoFinal(input); char[] password = "******".ToCharArray(); IBufferedCipher cDec = makePbeCipherUsingParam( "PBEWithSHA1AndDES", false, password, Hex.Decode("7d60435f02e9e0ae"), 2048); byte[] inBytes = cDec.DoFinal(outBytes); if (!AreEqual(input, inBytes)) { Fail("DES failed"); } cDec = makePbeCipherWithoutParam( "PBEWithSHA1AndDES", false, password, Hex.Decode("7d60435f02e9e0ae"), 2048); inBytes = cDec.DoFinal(outBytes); if (!AreEqual(input, inBytes)) { Fail("DES failed without param"); } // // DESede // cEnc = CipherUtilities.GetCipher("DESede/CBC/PKCS7Padding"); cEnc.Init( true, new ParametersWithIV( new DesParameters(Hex.Decode("732f2d33c801732b7206756cbd44f9c1c103ddd97c7cbe8e")), Hex.Decode("b07bf522c8d608b8"))); outBytes = cEnc.DoFinal(input); cDec = makePbeCipherUsingParam( "PBEWithSHAAnd3-KeyTripleDES-CBC", false, password, Hex.Decode("7d60435f02e9e0ae"), 2048); inBytes = cDec.DoFinal(outBytes); if (!AreEqual(input, inBytes)) { Fail("DESede failed"); } // // 40Bit RC2 // cEnc = CipherUtilities.GetCipher("RC2/CBC/PKCS7Padding"); cEnc.Init( true, new ParametersWithIV( new RC2Parameters(Hex.Decode("732f2d33c8")), Hex.Decode("b07bf522c8d608b8"))); outBytes = cEnc.DoFinal(input); cDec = makePbeCipherUsingParam( "PBEWithSHAAnd40BitRC2-CBC", false, password, Hex.Decode("7d60435f02e9e0ae"), 2048); inBytes = cDec.DoFinal(outBytes); if (!AreEqual(input, inBytes)) { Fail("RC2 failed"); } // // 128bit RC4 // cEnc = CipherUtilities.GetCipher("RC4"); cEnc.Init( true, ParameterUtilities.CreateKeyParameter("RC4", Hex.Decode("732f2d33c801732b7206756cbd44f9c1"))); outBytes = cEnc.DoFinal(input); cDec = makePbeCipherUsingParam( "PBEWithSHAAnd128BitRC4", false, password, Hex.Decode("7d60435f02e9e0ae"), 2048); inBytes = cDec.DoFinal(outBytes); if (!AreEqual(input, inBytes)) { Fail("RC4 failed"); } cDec = makePbeCipherWithoutParam( "PBEWithSHAAnd128BitRC4", false, password, Hex.Decode("7d60435f02e9e0ae"), 2048); inBytes = cDec.DoFinal(outBytes); if (!AreEqual(input, inBytes)) { Fail("RC4 failed without param"); } for (int i = 0; i != pkcs12Tests.Length; i++) { pkcs12Tests[i].PerformTest(); } for (int i = 0; i != openSSLTests.Length; i++) { openSSLTests[i].PerformTest(); } doTestPbeHMac("PBEWithHMacSHA1", hMac1); doTestPbeHMac("PBEWithHMacRIPEMD160", hMac2); }
private static void DecryptThread(IBufferedCipher cipher, byte[] input, BlockingCollection<string> producerConsumerCollection, bool allPaddings = false) { var taskOutputs = new StringBuilder(); int lineCount = 0; IBlockCipherPadding[] paddings; if (allPaddings) { paddings = new IBlockCipherPadding[] { new ZeroBytePadding(), new ISO10126d2Padding(), new ISO7816d4Padding(), new Pkcs7Padding(), new TbcPadding(), new X923Padding(), new X923Padding(), }; } else { paddings = new IBlockCipherPadding[] {new Pkcs7Padding()}; } while (!producerConsumerCollection.IsCompleted) { string line; try { line = producerConsumerCollection.Take(); } catch (InvalidOperationException) { if (producerConsumerCollection.IsCompleted) break; throw; } // Use that line as the key. byte[] key = Encoding.ASCII.GetBytes(line); // For each possible padding... foreach (IBlockCipherPadding padding in paddings) { // Decrypt byte[] output; try { cipher.Init(false, new KeyParameter(key)); output = cipher.DoFinal(input); cipher.Reset(); } catch (InvalidCipherTextException) { // TODO: Possibly filder out those inputs before and/or tell the user not to generate them. continue; } // Convert to hexadecimal. foreach (byte b in output) { taskOutputs.Append(HexStringTable[b]); } taskOutputs.AppendFormat(" `{0}` [{1}]", line, padding.PaddingName); taskOutputs.AppendLine(); ++lineCount; } // Output the hashed values in a batch. if (taskOutputs.Length > 100000) { Console.Write(taskOutputs.ToString()); taskOutputs.Clear(); lineCount = 0; } } // Output the last hashed values. Console.Write(taskOutputs.ToString()); }
public void Encryption(Stream inputStream, int subBlockSize) { bool ifBlock = false; byte[] data; using (MemoryStream ms = new MemoryStream()) { inputStream.CopyTo(ms); data = ms.ToArray(); } IBlockCipher engine = null; switch (this.Algorithm) { case "IDEA": engine = new IdeaEngine(); break; case "DES": engine = new DesEngine(); break; case "AES": engine = new AesEngine(); break; } IBufferedCipher cipher = null; BufferedBlockCipher blockCipher = null; switch (this.CipherMode) { case "CBC": blockCipher = new PaddedBufferedBlockCipher(new CbcBlockCipher(engine), new Pkcs7Padding()); ifBlock = true; break; case "ECB": cipher = CipherUtilities.GetCipher(this.Algorithm + "/ECB/PKCS7Padding"); cipher.Init(true, new KeyParameter(this.Key)); this.EncryptedData = cipher.DoFinal(data); break; case "CFB": blockCipher = new PaddedBufferedBlockCipher(new CfbBlockCipher(engine, subBlockSize), new Pkcs7Padding()); ifBlock = true; break; case "OFB": blockCipher = new PaddedBufferedBlockCipher(new OfbBlockCipher(engine, subBlockSize), new Pkcs7Padding()); ifBlock = true; break; default: Console.WriteLine("Default case"); break; } if (ifBlock) { ICipherParameters cipherParams = null; this.IvVector = new byte[8]; SecureRandom rand = new SecureRandom(); rand.NextBytes(this.IvVector); KeyParameter kluczParam = new KeyParameter(this.Key); cipherParams = new ParametersWithIV(kluczParam, this.IvVector); blockCipher.Init(true, cipherParams); this.EncryptedData = new byte[blockCipher.GetOutputSize(data.Length)]; int bytesLength = blockCipher.ProcessBytes(data, 0, data.Length, this.EncryptedData, 0); blockCipher.DoFinal(this.EncryptedData, bytesLength); ifBlock = false; } }
public static void Init() { publicKey = (RsaKeyParameters)PublicKeyFactory.CreateKey(Convert.FromBase64String("MFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBAM5U06JAbYWdRBrnMdE2bEuDmWgUav7xNKm7i8s1Uy/fvpvfxLeoWowLGIBKz0kDLIvhuLV8Lv4XV0+aXdl2j4kCAwEAAQ==")); cipher = CipherUtilities.GetCipher("RSA/ECB/PKCS1Padding"); cipher.Init(true, publicKey); }
// TODO Make private again and call from PerformTest public void doTestExceptions() { // TODO Put back in // SecretKeyFactory skF = null; // // try // { // skF = SecretKeyFactory.getInstance("DESede"); // } // catch (Exception e) // { // Fail("unexpected exception.", e); // } // // KeySpec ks = null; // SecretKey secKey = null; // byte[] bb = new byte[24]; // // try // { // skF.getKeySpec(null, null); // // Fail("failed exception test - no exception thrown"); // } // catch (InvalidKeySpecException e) // { // // ignore okay // } // catch (Exception e) // { // Fail("failed exception test.", e); // } // try // { // ks = (KeySpec)new DESedeKeySpec(bb); // skF.getKeySpec(null, ks.getClass()); // // Fail("failed exception test - no exception thrown"); // } // catch (InvalidKeySpecException e) // { // // ignore okay; // } // catch (Exception e) // { // Fail("failed exception test.", e); // } // try // { // skF.getKeySpec(secKey, null); // } // catch (InvalidKeySpecException e) // { // // ignore okay // } // catch (Exception e) // { // Fail("failed exception test.", e); // } try { CipherKeyGenerator kg = GeneratorUtilities.GetKeyGenerator("DESede"); try { kg.Init(new KeyGenerationParameters(new SecureRandom(), int.MinValue)); Fail("failed exception test - no exception thrown"); } // catch (InvalidParameterException) catch (ArgumentException) { // ignore okay } catch (Exception e) { Fail("failed exception test.", e); } } catch (Exception e) { Fail("unexpected exception.", e); } // TODO Put back in // try // { // skF = SecretKeyFactory.getInstance("DESede"); // // try // { // skF.translateKey(null); // // Fail("failed exception test - no exception thrown"); // } // catch (InvalidKeyException) // { // // ignore okay // } // catch (Exception e) // { // Fail("failed exception test.", e); // } // } // catch (Exception e) // { // Fail("unexpected exception.", e); // } // try // { // byte[] rawDESKey = { (byte)128, (byte)131, (byte)133, (byte)134, // (byte)137, (byte)138, (byte)140, (byte)143 }; // //// SecretKeySpec cipherKey = new SecretKeySpec(rawDESKey, "DES"); // KeyParameter cipherKey = new DesParameters(rawDESKey); // // IBufferedCipher cipher = CipherUtilities.GetCipher("DES/CBC/NoPadding"); // // try // { // // According specification engineInit(int opmode, Key key, // // SecureRandom random) throws InvalidKeyException if this // // cipher is being // // initialized for decryption and requires algorithm parameters // // that cannot be determined from the given key //// cipher.Init(false, cipherKey, (SecureRandom)null); // cipher.Init(false, new ParametersWithRandom(cipherKey, new SecureRandom())); // // Fail("failed exception test - no InvalidKeyException thrown"); // } // catch (InvalidKeyException) // { // // ignore // } // } // catch (Exception e) // { // Fail("unexpected exception.", e); // } try { // byte[] rawDESKey = { -128, -125, -123, -122, -119, -118 }; byte[] rawDESKey = { 128, 131, 133, 134, 137, 138 }; // SecretKeySpec cipherKey = new SecretKeySpec(rawDESKey, "DES"); // IBufferedCipher cipher = CipherUtilities.GetCipher("DES/ECB/NoPadding"); try { KeyParameter cipherKey = new DesParameters(rawDESKey); // According specification engineInit(int opmode, Key key, // SecureRandom random) throws InvalidKeyException if the given // key is inappropriate for initializing this cipher // cipher.Init(true, cipherKey); // Fail("failed exception test - no InvalidKeyException thrown"); Fail("failed exception test - no ArgumentException thrown"); } // catch (InvalidKeyException) catch (ArgumentException) { // ignore } } catch (Exception e) { Fail("unexpected exception.", e); } // try // { //// byte[] rawDESKey = { -128, -125, -123, -122, -119, -118, -117, -115, -114 }; // byte[] rawDESKey = { 128, 131, 133, 134, 137, 138, 139, 141, 142 }; // //// SecretKeySpec cipherKey = new SecretKeySpec(rawDESKey, "DES"); // KeyParameter cipherKey = new DesParameters(rawDESKey); // // IBufferedCipher cipher = CipherUtilities.GetCipher("DES/ECB/NoPadding"); // try // { // // According specification engineInit(int opmode, Key key, // // SecureRandom random) throws InvalidKeyException if the given // // key is inappropriate for initializing this cipher // cipher.Init(true, cipherKey); // // Fail("failed exception test - no InvalidKeyException thrown"); // } // catch (InvalidKeyException) // { // // ignore // } // } // catch (Exception e) // { // Fail("unexpected exception.", e); // } try { byte[] rawDESKey = { (byte)128, (byte)131, (byte)133, (byte)134, (byte)137, (byte)138, (byte)140, (byte)143 }; // SecretKeySpec cipherKey = new SecretKeySpec(rawDESKey, "DES"); KeyParameter cipherKey = new DesParameters(rawDESKey); IBufferedCipher ecipher = CipherUtilities.GetCipher("DES/ECB/PKCS5Padding"); ecipher.Init(true, cipherKey); byte[] cipherText = new byte[0]; try { // According specification Method engineUpdate(byte[] input, // int inputOffset, int inputLen, byte[] output, int // outputOffset) // throws ShortBufferException - if the given output buffer is // too // small to hold the result // ecipher.update(new byte[20], 0, 20, cipherText); ecipher.ProcessBytes(new byte[20], 0, 20, cipherText, 0); // Fail("failed exception test - no ShortBufferException thrown"); Fail("failed exception test - no DataLengthException thrown"); } // catch (ShortBufferException) catch (DataLengthException) { // ignore } } catch (Exception e) { Fail("unexpected exception.", e); } // TODO Put back in // try // { // KeyGenerator keyGen = KeyGenerator.getInstance("DES"); // // keyGen.init((SecureRandom)null); // // // According specification engineGenerateKey() doesn't throw any exceptions. // // SecretKey key = keyGen.generateKey(); // if (key == null) // { // Fail("key is null!"); // } // } // catch (Exception e) // { // Fail("unexpected exception.", e); // } // // try // { // AlgorithmParameters algParams = AlgorithmParameters.getInstance("DES"); // // algParams.init(new IvParameterSpec(new byte[8])); // // // According specification engineGetEncoded() returns // // the parameters in their primary encoding format. The primary // // encoding // // format for parameters is ASN.1, if an ASN.1 specification for // // this type // // of parameters exists. // byte[] iv = algParams.getEncoded(); // // if (iv.Length!= 10) // { // Fail("parameters encoding wrong length - " + iv.Length); // } // } // catch (Exception e) // { // Fail("unexpected exception.", e); // } try { try { // AlgorithmParameters algParams = AlgorithmParameters.getInstance("DES"); byte[] encoding = new byte[10]; encoding[0] = 3; encoding[1] = 8; // algParams.init(encoding, "ASN.1"); ParameterUtilities.GetCipherParameters( "AES", ParameterUtilities.CreateKeyParameter("AES", new byte[16]), Asn1Object.FromByteArray(encoding)); // Fail("failed exception test - no IOException thrown"); Fail("failed exception test - no Exception thrown"); } // catch (IOException) catch (ArgumentException) { // okay } // try // { // IBufferedCipher c = CipherUtilities.GetCipher("DES"); // // Key k = new PublicKey() // { // // public string getAlgorithm() // { // return "STUB"; // } // // public string getFormat() // { // return null; // } // // public byte[] getEncoded() // { // return null; // } // // }; // // c.Init(true, k); // // Fail("failed exception test - no InvalidKeyException thrown for public key"); // } // catch (InvalidKeyException e) // { // // okay // } // // try // { // IBufferedCipher c = CipherUtilities.GetCipher("DES"); // // Key k = new PrivateKey() // { // // public string getAlgorithm() // { // return "STUB"; // } // // public string getFormat() // { // return null; // } // // public byte[] getEncoded() // { // return null; // } // // }; // // c.Init(false, k); // // Fail("failed exception test - no InvalidKeyException thrown for private key"); // } // catch (InvalidKeyException e) // { // // okay // } } catch (Exception e) { Fail("unexpected exception.", e); } }
public override void PerformTest() { IBufferedCipher c = CipherUtilities.GetCipher("AES/SIC/NoPadding"); // // NIST vectors // for (int i = 0; i != keys.Length; i++) { KeyParameter skey = ParameterUtilities.CreateKeyParameter("AES", keys[i]); c.Init(true, new ParametersWithIV(skey, Hex.Decode("F0F1F2F3F4F5F6F7F8F9FAFBFCFDFEFF"))); for (int j = 0; j != plain.Length; j++) { byte[] enc = c.ProcessBytes(plain[j]); if (!AreEqual(enc, cipher[i, j])) { Fail("AESSIC encrypt failed: key " + i + " block " + j); } } c.Init(false, new ParametersWithIV(skey, Hex.Decode("F0F1F2F3F4F5F6F7F8F9FAFBFCFDFEFF"))); for (int j = 0; j != plain.Length; j++) { byte[] enc = c.ProcessBytes(cipher[i, j]); if (!AreEqual(enc, plain[j])) { Fail("AESSIC decrypt failed: key " + i + " block " + j); } } } // // check CTR also recognised. // c = CipherUtilities.GetCipher("AES/CTR/NoPadding"); KeyParameter sk = ParameterUtilities.CreateKeyParameter("AES", Hex.Decode("2B7E151628AED2A6ABF7158809CF4F3C")); c.Init(true, new ParametersWithIV(sk, Hex.Decode("F0F1F2F3F4F5F6F7F8F9FAFBFCFD0001"))); byte[] crypt = c.DoFinal(Hex.Decode("00000000000000000000000000000000")); if (!AreEqual(crypt, Hex.Decode("D23513162B02D0F72A43A2FE4A5F97AB"))) { Fail("AESSIC failed test 2"); } // // check partial block processing // c = CipherUtilities.GetCipher("AES/CTR/NoPadding"); sk = ParameterUtilities.CreateKeyParameter("AES", Hex.Decode("2B7E151628AED2A6ABF7158809CF4F3C")); c.Init(true, new ParametersWithIV(sk, Hex.Decode("F0F1F2F3F4F5F6F7F8F9FAFBFCFD0001"))); crypt = c.DoFinal(Hex.Decode("12345678")); c.Init(false, new ParametersWithIV(sk, Hex.Decode("F0F1F2F3F4F5F6F7F8F9FAFBFCFD0001"))); crypt = c.DoFinal(crypt); if (!AreEqual(crypt, Hex.Decode("12345678"))) { Fail("AESSIC failed partial test"); } }
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()); // } }
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; 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 = SecureRandom.GetNextBytes(rand, 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("CCM") || mode.StartsWith("CFB") || mode.StartsWith("CTR") || mode.StartsWith("EAX") || mode.StartsWith("GCM") || mode.StartsWith("GOFB") || mode.StartsWith("OCB") || mode.StartsWith("OFB") || mode.StartsWith("OPENPGPCFB") || mode.StartsWith("SIC")) { // 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)); } }
public override void PerformTest() { byte[] input = new byte[] { (byte)0x54, (byte)0x85, (byte)0x9b, (byte)0x34, (byte)0x2c, (byte)0x49, (byte)0xea, (byte)0x2a }; byte[][] output = new byte[][] { Hex.Decode("8b427f781a2e59dd9def386f1956b996ee07f48c96880e65a368055ed8c0a8831669ef7250b40918b2b1d488547e72c84540e42bd07b03f14e226f04fbc2d929"), Hex.Decode("2ec6e1a1711b6c7b8cd3f6a25db21ab8bb0a5f1d6df2ef375fa708a43997730ffc7c98856dbbe36edddcdd1b2d2a53867d8355af94fea3aeec128da908e08f4c"), Hex.Decode("0850ac4e5a8118323200c8ed1e5aaa3d5e635172553ccac66a8e4153d35c79305c4440f11034ab147fccce21f18a50cf1c0099c08a577eb68237a91042278965"), Hex.Decode("1c9649bdccb51056751fe43837f4eb43bada472accf26f65231666d5de7d11950d8379b3596dfdf75c6234274896fa8d18ad0865d3be2ac4d6687151abdf01e93941dcef18fa63186c9351d1506c89d09733c5ff4304208c812bdd21a50f56fde115e629e0e973721c9fcc87e89295a79853dee613962a0b2f2fc57163fd99057a3c776f13c20c26407eb8863998d7e53b543ba8d0a295a9a68d1a149833078c9809ad6a6dad7fc22a95ad615a73138c54c018f40d99bf8eeecd45f5be526f2d6b01aeb56381991c1ab31a2e756f15e052b9cd5638b2eff799795c5bae493307d5eb9f8c21d438de131fe505a4e7432547ab19224094f9e4be1968bd0793b79d"), Hex.Decode("4c4afc0c24dddaedd4f9a3b23be30d35d8e005ffd36b3defc5d18acc830c3ed388ce20f43a00e614fd087c814197bc9fc2eff9ad4cc474a7a2ef3ed9c0f0a55eb23371e41ee8f2e2ed93ea3a06ca482589ab87e0d61dcffda5eea1241408e43ea1108726cdb87cc3aa5e9eaaa9f72507ca1352ac54a53920c94dccc768147933d8c50aefd9d1da10522a40133cd33dbc0524669e70f771a88d65c4716d471cd22b08b9f01f24e4e9fc7ffbcfa0e0a7aed47b345826399b26a73be112eb9c5e06fc6742fc3d0ef53d43896403c5105109cfc12e6deeaf4a48ba308e039774b9bdb31a9b9e133c81c321630cf0b4b2d1f90717b24c3268e1fea681ea9cdc709342"), Hex.Decode("06b5b26bd13515f799e5e37ca43cace15cd82fd4bf36b25d285a6f0998d97c8cb0755a28f0ae66618b1cd03e27ac95eaaa4882bc6dc0078cd457d4f7de4154173a9c7a838cfc2ac2f74875df462aae0cfd341645dc51d9a01da9bdb01507f140fa8a016534379d838cc3b2a53ac33150af1b242fc88013cb8d914e66c8182864ee6de88ce2879d4c05dd125409620a96797c55c832fb2fb31d4310c190b8ed2c95fdfda2ed87f785002faaec3f35ec05cf70a3774ce185e4882df35719d582dd55ac31257344a9cba95189dcbea16e8c6cb7a235a0384bc83b6183ca8547e670fe33b1b91725ae0c250c9eca7b5ba78bd77145b70270bf8ac31653006c02ca9c"), Hex.Decode("135f1be3d045526235bf9d5e43499d4ee1bfdf93370769ae56e85dbc339bc5b7ea3bee49717497ee8ac3f7cd6adb6fc0f17812390dcd65ac7b87fef7970d9ff9"), Hex.Decode("03c05add1e030178c352face07cafc9447c8f369b8f95125c0d311c16b6da48ca2067104cce6cd21ae7b163cd18ffc13001aecebdc2eb02b9e92681f84033a98"), Hex.Decode("00319bb9becb49f3ed1bca26d0fcf09b0b0a508e4d0bd43b350f959b72cd25b3af47d608fdcd248eada74fbe19990dbeb9bf0da4b4e1200243a14e5cab3f7e610c") }; SecureRandom rand = new MyFixedSecureRandom(); // KeyFactory fact = KeyFactory.GetInstance("RSA"); // // PrivateKey privKey = fact.generatePrivate(privKeySpec); // PublicKey pubKey = fact.generatePublic(pubKeySpec); AsymmetricKeyParameter privKey = privKeySpec; AsymmetricKeyParameter pubKey = pubKeySpec; // PrivateKey priv2048Key = fact.generatePrivate(priv2048KeySpec); // PublicKey pub2048Key = fact.generatePublic(pub2048KeySpec); AsymmetricKeyParameter priv2048Key = priv2048KeySpec; AsymmetricKeyParameter pub2048Key = pub2048KeySpec; // // No Padding // // Cipher c = Cipher.GetInstance("RSA"); IBufferedCipher c = CipherUtilities.GetCipher("RSA"); // c.init(Cipher.ENCRYPT_MODE, pubKey, rand); c.Init(true, pubKey); // new ParametersWithRandom(pubKey, rand)); byte[] outBytes = c.DoFinal(input); if (!AreEqual(outBytes, output[0])) { Fail("NoPadding test failed on encrypt expected " + Hex.ToHexString(output[0]) + " got " + Hex.ToHexString(outBytes)); } // c.init(Cipher.DECRYPT_MODE, privKey); c.Init(false, privKey); outBytes = c.DoFinal(outBytes); if (!AreEqual(outBytes, input)) { Fail("NoPadding test failed on decrypt expected " + Hex.ToHexString(input) + " got " + Hex.ToHexString(outBytes)); } // // No Padding - incremental // // c = Cipher.GetInstance("RSA"); c = CipherUtilities.GetCipher("RSA"); // c.init(Cipher.ENCRYPT_MODE, pubKey, rand); c.Init(true, pubKey); // new ParametersWithRandom(pubKey, rand)); c.ProcessBytes(input); outBytes = c.DoFinal(); if (!AreEqual(outBytes, output[0])) { Fail("NoPadding test failed on encrypt expected " + Hex.ToHexString(output[0]) + " got " + Hex.ToHexString(outBytes)); } // c.init(Cipher.DECRYPT_MODE, privKey); c.Init(false, privKey); outBytes = c.DoFinal(outBytes); if (!AreEqual(outBytes, input)) { Fail("NoPadding test failed on decrypt expected " + Hex.ToHexString(input) + " got " + Hex.ToHexString(outBytes)); } // // No Padding - incremental - explicit use of NONE in mode. // c = CipherUtilities.GetCipher("RSA/NONE/NoPadding"); // c.init(Cipher.ENCRYPT_MODE, pubKey, rand); c.Init(true, pubKey); // new ParametersWithRandom(pubKey, rand)); c.ProcessBytes(input); outBytes = c.DoFinal(); if (!AreEqual(outBytes, output[0])) { Fail("NoPadding test failed on encrypt expected " + Hex.ToHexString(output[0]) + " got " + Hex.ToHexString(outBytes)); } // c.init(Cipher.DECRYPT_MODE, privKey); c.Init(false, privKey); outBytes = c.DoFinal(outBytes); if (!AreEqual(outBytes, input)) { Fail("NoPadding test failed on decrypt expected " + Hex.ToHexString(input) + " got " + Hex.ToHexString(outBytes)); } // // No Padding - maximum.Length // c = CipherUtilities.GetCipher("RSA"); byte[] modBytes = ((RsaKeyParameters)pubKey).Modulus.ToByteArray(); byte[] maxInput = new byte[modBytes.Length - 1]; maxInput[0] |= 0x7f; c.Init(true, pubKey); // new ParametersWithRandom(pubKey, rand)); outBytes = c.DoFinal(maxInput); c.Init(false, privKey); outBytes = c.DoFinal(outBytes); if (!AreEqual(outBytes, maxInput)) { Fail("NoPadding test failed on decrypt expected " + Hex.ToHexString(maxInput) + " got " + Hex.ToHexString(outBytes)); } // // PKCS1 V 1.5 // c = CipherUtilities.GetCipher("RSA//PKCS1Padding"); c.Init(true, new ParametersWithRandom(pubKey, rand)); outBytes = c.DoFinal(input); if (!AreEqual(outBytes, output[1])) { Fail("PKCS1 test failed on encrypt expected " + Hex.ToHexString(output[1]) + " got " + Hex.ToHexString(outBytes)); } c.Init(false, privKey); outBytes = c.DoFinal(outBytes); if (!AreEqual(outBytes, input)) { Fail("PKCS1 test failed on decrypt expected " + Hex.ToHexString(input) + " got " + Hex.ToHexString(outBytes)); } // // PKCS1 V 1.5 - NONE // c = CipherUtilities.GetCipher("RSA/NONE/PKCS1Padding"); c.Init(true, new ParametersWithRandom(pubKey, rand)); outBytes = c.DoFinal(input); if (!AreEqual(outBytes, output[1])) { Fail("PKCS1 test failed on encrypt expected " + Hex.ToHexString(output[1]) + " got " + Hex.ToHexString(outBytes)); } c.Init(false, privKey); outBytes = c.DoFinal(outBytes); if (!AreEqual(outBytes, input)) { Fail("PKCS1 test failed on decrypt expected " + Hex.ToHexString(input) + " got " + Hex.ToHexString(outBytes)); } // // OAEP - SHA1 // c = CipherUtilities.GetCipher("RSA/NONE/OAEPPadding"); c.Init(true, new ParametersWithRandom(pubKey, rand)); outBytes = c.DoFinal(input); if (!AreEqual(outBytes, output[2])) { Fail("OAEP test failed on encrypt expected " + Hex.ToHexString(output[2]) + " got " + Hex.ToHexString(outBytes)); } c = CipherUtilities.GetCipher("RSA/NONE/OAEPWithSHA1AndMGF1Padding"); c.Init(false, privKey); outBytes = c.DoFinal(outBytes); if (!AreEqual(outBytes, input)) { Fail("OAEP test failed on decrypt expected " + Hex.ToHexString(input) + " got " + Hex.ToHexString(outBytes)); } // TODO // AlgorithmParameters oaepP = c.getParameters(); byte[] rop = new RsaesOaepParameters( new AlgorithmIdentifier(OiwObjectIdentifiers.IdSha1, DerNull.Instance), new AlgorithmIdentifier(PkcsObjectIdentifiers.IdMgf1, new AlgorithmIdentifier(OiwObjectIdentifiers.IdSha1, DerNull.Instance)), new AlgorithmIdentifier(PkcsObjectIdentifiers.IdPSpecified, new DerOctetString(new byte[0]))).GetEncoded(); // if (!AreEqual(oaepP.getEncoded(), rop.getEncoded())) // { // Fail("OAEP test failed default sha-1 parameters"); // } // // OAEP - SHA224 // c = CipherUtilities.GetCipher("RSA/NONE/OAEPWithSHA224AndMGF1Padding"); c.Init(true, new ParametersWithRandom(pub2048Key, rand)); outBytes = c.DoFinal(input); if (!AreEqual(outBytes, output[3])) { Fail("OAEP SHA-224 test failed on encrypt expected " + Hex.ToHexString(output[2]) + " got " + Hex.ToHexString(outBytes)); } c.Init(false, priv2048Key); outBytes = c.DoFinal(outBytes); if (!AreEqual(outBytes, input)) { Fail("OAEP SHA-224 test failed on decrypt expected " + Hex.ToHexString(input) + " got " + Hex.ToHexString(outBytes)); } // oaepP = c.getParameters(); rop = new RsaesOaepParameters( new AlgorithmIdentifier(NistObjectIdentifiers.IdSha224, DerNull.Instance), new AlgorithmIdentifier(PkcsObjectIdentifiers.IdMgf1, new AlgorithmIdentifier(NistObjectIdentifiers.IdSha224, DerNull.Instance)), new AlgorithmIdentifier(PkcsObjectIdentifiers.IdPSpecified, new DerOctetString(new byte[0]))).GetEncoded(); // if (!AreEqual(oaepP.getEncoded(), rop.getEncoded()) // { // Fail("OAEP test failed default sha-224 parameters"); // } // // OAEP - SHA 256 // c = CipherUtilities.GetCipher("RSA/NONE/OAEPWithSHA256AndMGF1Padding"); c.Init(true, new ParametersWithRandom(pub2048Key, rand)); outBytes = c.DoFinal(input); if (!AreEqual(outBytes, output[4])) { Fail("OAEP SHA-256 test failed on encrypt expected " + Hex.ToHexString(output[2]) + " got " + Hex.ToHexString(outBytes)); } c.Init(false, priv2048Key); outBytes = c.DoFinal(outBytes); if (!AreEqual(outBytes, input)) { Fail("OAEP SHA-256 test failed on decrypt expected " + Hex.ToHexString(input) + " got " + Hex.ToHexString(outBytes)); } // oaepP = c.getParameters(); rop = new RsaesOaepParameters( new AlgorithmIdentifier(NistObjectIdentifiers.IdSha256, DerNull.Instance), new AlgorithmIdentifier(PkcsObjectIdentifiers.IdMgf1, new AlgorithmIdentifier(NistObjectIdentifiers.IdSha256, DerNull.Instance)), new AlgorithmIdentifier(PkcsObjectIdentifiers.IdPSpecified, new DerOctetString(new byte[0]))).GetEncoded(); // if (!AreEqual(oaepP.getEncoded(), rop.getEncoded()) // { // Fail("OAEP test failed default sha-256 parameters"); // } // // OAEP - SHA 384 // c = CipherUtilities.GetCipher("RSA/NONE/OAEPWithSHA384AndMGF1Padding"); c.Init(true, new ParametersWithRandom(pub2048Key, rand)); outBytes = c.DoFinal(input); if (!AreEqual(outBytes, output[5])) { Fail("OAEP SHA-384 test failed on encrypt expected " + Hex.ToHexString(output[2]) + " got " + Hex.ToHexString(outBytes)); } c.Init(false, priv2048Key); outBytes = c.DoFinal(outBytes); if (!AreEqual(outBytes, input)) { Fail("OAEP SHA-384 test failed on decrypt expected " + Hex.ToHexString(input) + " got " + Hex.ToHexString(outBytes)); } // oaepP = c.getParameters(); rop = new RsaesOaepParameters( new AlgorithmIdentifier(NistObjectIdentifiers.IdSha384, DerNull.Instance), new AlgorithmIdentifier(PkcsObjectIdentifiers.IdMgf1, new AlgorithmIdentifier(NistObjectIdentifiers.IdSha384, DerNull.Instance)), new AlgorithmIdentifier(PkcsObjectIdentifiers.IdPSpecified, new DerOctetString(new byte[0]))).GetEncoded(); // if (!AreEqual(oaepP.getEncoded(), rop.getEncoded()) // { // Fail("OAEP test failed default sha-384 parameters"); // } // // OAEP - MD5 // c = CipherUtilities.GetCipher("RSA/NONE/OAEPWithMD5AndMGF1Padding"); c.Init(true, new ParametersWithRandom(pubKey, rand)); outBytes = c.DoFinal(input); if (!AreEqual(outBytes, output[6])) { Fail("OAEP MD5 test failed on encrypt expected " + Hex.ToHexString(output[2]) + " got " + Hex.ToHexString(outBytes)); } c.Init(false, privKey); outBytes = c.DoFinal(outBytes); if (!AreEqual(outBytes, input)) { Fail("OAEP MD5 test failed on decrypt expected " + Hex.ToHexString(input) + " got " + Hex.ToHexString(outBytes)); } // oaepP = c.getParameters(); rop = new RsaesOaepParameters( new AlgorithmIdentifier(PkcsObjectIdentifiers.MD5, DerNull.Instance), new AlgorithmIdentifier(PkcsObjectIdentifiers.IdMgf1, new AlgorithmIdentifier(PkcsObjectIdentifiers.MD5, DerNull.Instance)), new AlgorithmIdentifier(PkcsObjectIdentifiers.IdPSpecified, new DerOctetString(new byte[0]))).GetEncoded(); // if (!AreEqual(oaepP.getEncoded(), rop.getEncoded()) // { // Fail("OAEP test failed default md5 parameters"); // } // // OAEP - SHA1 with default parameters // c = CipherUtilities.GetCipher("RSA/NONE/OAEPPadding"); // TODO // c.init(Cipher.ENCRYPT_MODE, pubKey, OAEPParameterSpec.DEFAULT, rand); // // outBytes = c.DoFinal(input); // // if (!AreEqual(outBytes, output[2])) // { // Fail("OAEP test failed on encrypt expected " + Encoding.ASCII.GetString(Hex.Encode(output[2])) + " got " + Encoding.ASCII.GetString(Hex.Encode(outBytes))); // } // // c = CipherUtilities.GetCipher("RSA/NONE/OAEPWithSHA1AndMGF1Padding"); // // c.Init(false, privKey); // // outBytes = c.DoFinal(outBytes); // // if (!AreEqual(outBytes, input)) // { // Fail("OAEP test failed on decrypt expected " + Encoding.ASCII.GetString(Hex.Encode(input)) + " got " + Encoding.ASCII.GetString(Hex.Encode(outBytes))); // } // // oaepP = c.getParameters(); // // if (!AreEqual(oaepP.getEncoded(), new byte[] { 0x30, 0x00 })) // { // Fail("OAEP test failed default parameters"); // } // // OAEP - SHA1 with specified string // c = CipherUtilities.GetCipher("RSA/NONE/OAEPPadding"); // TODO // c.init(Cipher.ENCRYPT_MODE, pubKey, new OAEPParameterSpec("SHA1", "MGF1", new MGF1ParameterSpec("SHA1"), new PSource.PSpecified(new byte[] { 1, 2, 3, 4, 5 })), rand); // // outBytes = c.DoFinal(input); // // oaepP = c.getParameters(); rop = new RsaesOaepParameters( new AlgorithmIdentifier(OiwObjectIdentifiers.IdSha1, DerNull.Instance), new AlgorithmIdentifier(PkcsObjectIdentifiers.IdMgf1, new AlgorithmIdentifier(OiwObjectIdentifiers.IdSha1, DerNull.Instance)), new AlgorithmIdentifier(PkcsObjectIdentifiers.IdPSpecified, new DerOctetString(new byte[] { 1, 2, 3, 4, 5 }))).GetEncoded(); // if (!AreEqual(oaepP.getEncoded()) // { // Fail("OAEP test failed changed sha-1 parameters"); // } // // if (!AreEqual(outBytes, output[7])) // { // Fail("OAEP test failed on encrypt expected " + Encoding.ASCII.GetString(Hex.Encode(output[2])) + " got " + Encoding.ASCII.GetString(Hex.Encode(outBytes))); // } c = CipherUtilities.GetCipher("RSA/NONE/OAEPWithSHA1AndMGF1Padding"); // TODO // c.init(Cipher.DECRYPT_MODE, privKey, oaepP); // // outBytes = c.DoFinal(outBytes); // // if (!AreEqual(outBytes, input)) // { // Fail("OAEP test failed on decrypt expected " + Encoding.ASCII.GetString(Hex.Encode(input)) + " got " + Encoding.ASCII.GetString(Hex.Encode(outBytes))); // } // // iso9796-1 // byte[] isoInput = Hex.Decode("fedcba9876543210fedcba9876543210fedcba9876543210fedcba9876543210"); // PrivateKey isoPrivKey = fact.generatePrivate(isoPrivKeySpec); // PublicKey isoPubKey = fact.generatePublic(isoPubKeySpec); AsymmetricKeyParameter isoPrivKey = isoPrivKeySpec; AsymmetricKeyParameter isoPubKey = isoPubKeySpec; c = CipherUtilities.GetCipher("RSA/NONE/ISO9796-1Padding"); c.Init(true, isoPrivKey); outBytes = c.DoFinal(isoInput); if (!AreEqual(outBytes, output[8])) { Fail("ISO9796-1 test failed on encrypt expected " + Hex.ToHexString(output[3]) + " got " + Hex.ToHexString(outBytes)); } c.Init(false, isoPubKey); outBytes = c.DoFinal(outBytes); if (!AreEqual(outBytes, isoInput)) { Fail("ISO9796-1 test failed on decrypt expected " + Hex.ToHexString(input) + " got " + Hex.ToHexString(outBytes)); } // // // generation with parameters test. // IAsymmetricCipherKeyPairGenerator keyPairGen = GeneratorUtilities.GetKeyPairGenerator("RSA"); // // 768 bit RSA with e = 2^16-1 // keyPairGen.Init( new RsaKeyGenerationParameters( BigInteger.ValueOf(0x10001), new SecureRandom(), 768, 25)); AsymmetricCipherKeyPair kp = keyPairGen.GenerateKeyPair(); pubKey = kp.Public; privKey = kp.Private; c.Init(true, new ParametersWithRandom(pubKey, rand)); outBytes = c.DoFinal(input); c.Init(false, privKey); outBytes = c.DoFinal(outBytes); if (!AreEqual(outBytes, input)) { Fail("key generation test failed on decrypt expected " + Hex.ToHexString(input) + " got " + Hex.ToHexString(outBytes)); } // // comparison check // // KeyFactory keyFact = KeyFactory.GetInstance("RSA"); // // RSAPrivateCrtKey crtKey = (RSAPrivateCrtKey)keyFact.translateKey(privKey); RsaPrivateCrtKeyParameters crtKey = (RsaPrivateCrtKeyParameters)privKey; if (!privKey.Equals(crtKey)) { Fail("private key equality check failed"); } // RSAPublicKey copyKey = (RSAPublicKey)keyFact.translateKey(pubKey); RsaKeyParameters copyKey = (RsaKeyParameters)pubKey; if (!pubKey.Equals(copyKey)) { Fail("public key equality check failed"); } SecureRandom random = new SecureRandom(); rawModeTest("SHA1withRSA", X509ObjectIdentifiers.IdSha1, priv2048Key, pub2048Key, random); rawModeTest("MD5withRSA", PkcsObjectIdentifiers.MD5, priv2048Key, pub2048Key, random); rawModeTest("RIPEMD128withRSA", TeleTrusTObjectIdentifiers.RipeMD128, priv2048Key, pub2048Key, random); }
private byte[] RecoverSessionData(PgpPrivateKey privKey) { byte[][] secKeyData = keyData.GetEncSessionKey(); if (keyData.Algorithm == PublicKeyAlgorithmTag.ECDH) { ECDHPublicBcpgKey ecKey = (ECDHPublicBcpgKey)privKey.PublicKeyPacket.Key; X9ECParameters x9Params = ECKeyPairGenerator.FindECCurveByOid(ecKey.CurveOid); byte[] enc = secKeyData[0]; int pLen = ((((enc[0] & 0xff) << 8) + (enc[1] & 0xff)) + 7) / 8; byte[] pEnc = new byte[pLen]; Array.Copy(enc, 2, pEnc, 0, pLen); byte[] keyEnc = new byte[enc[pLen + 2]]; Array.Copy(enc, 2 + pLen + 1, keyEnc, 0, keyEnc.Length); ECPoint publicPoint = x9Params.Curve.DecodePoint(pEnc); ECPrivateKeyParameters privKeyParams = (ECPrivateKeyParameters)privKey.Key; ECPoint S = publicPoint.Multiply(privKeyParams.D).Normalize(); KeyParameter key = new KeyParameter(Rfc6637Utilities.CreateKey(privKey.PublicKeyPacket, S)); IWrapper w = PgpUtilities.CreateWrapper(ecKey.SymmetricKeyAlgorithm); w.Init(false, key); return(PgpPad.UnpadSessionData(w.Unwrap(keyEnc, 0, keyEnc.Length))); } IBufferedCipher cipher = GetKeyCipher(keyData.Algorithm); try { cipher.Init(false, privKey.Key); } catch (InvalidKeyException e) { throw new PgpException("error setting asymmetric cipher", e); } if (keyData.Algorithm == PublicKeyAlgorithmTag.RsaEncrypt || keyData.Algorithm == PublicKeyAlgorithmTag.RsaGeneral) { byte[] bi = secKeyData[0]; cipher.ProcessBytes(bi, 2, bi.Length - 2); } else { ElGamalPrivateKeyParameters k = (ElGamalPrivateKeyParameters)privKey.Key; int size = (k.Parameters.P.BitLength + 7) / 8; ProcessEncodedMpi(cipher, size, secKeyData[0]); ProcessEncodedMpi(cipher, size, secKeyData[1]); } try { return(cipher.DoFinal()); } catch (Exception e) { throw new PgpException("exception decrypting secret key", e); } }
public override void PerformTest() { PgpPublicKey pubKey = null; // // Read the public key // PgpObjectFactory pgpFact = new PgpObjectFactory(testPubKeyRing); PgpPublicKeyRing pgpPub = (PgpPublicKeyRing)pgpFact.NextPgpObject(); pubKey = pgpPub.GetPublicKey(); if (pubKey.BitStrength != 1024) { Fail("failed - key strength reported incorrectly."); } // // Read the private key // PgpSecretKeyRing sKey = new PgpSecretKeyRing(testPrivKeyRing); PgpSecretKey secretKey = sKey.GetSecretKey(); PgpPrivateKey pgpPrivKey = secretKey.ExtractPrivateKey(pass); // // signature generation // const string data = "hello world!"; byte[] dataBytes = Encoding.ASCII.GetBytes(data); MemoryStream bOut = new MemoryStream(); MemoryStream testIn = new MemoryStream(dataBytes, false); PgpSignatureGenerator sGen = new PgpSignatureGenerator(PublicKeyAlgorithmTag.Dsa, HashAlgorithmTag.Sha1); sGen.InitSign(PgpSignature.BinaryDocument, pgpPrivKey); PgpCompressedDataGenerator cGen = new PgpCompressedDataGenerator( CompressionAlgorithmTag.Zip); BcpgOutputStream bcOut = new BcpgOutputStream( cGen.Open(new UncloseableStream(bOut))); sGen.GenerateOnePassVersion(false).Encode(bcOut); PgpLiteralDataGenerator lGen = new PgpLiteralDataGenerator(); DateTime testDateTime = new DateTime(1973, 7, 27); Stream lOut = lGen.Open( new UncloseableStream(bcOut), PgpLiteralData.Binary, "_CONSOLE", dataBytes.Length, testDateTime); int ch; while ((ch = testIn.ReadByte()) >= 0) { lOut.WriteByte((byte)ch); sGen.Update((byte)ch); } lGen.Close(); sGen.Generate().Encode(bcOut); cGen.Close(); // // verify Generated signature // pgpFact = new PgpObjectFactory(bOut.ToArray()); PgpCompressedData c1 = (PgpCompressedData)pgpFact.NextPgpObject(); pgpFact = new PgpObjectFactory(c1.GetDataStream()); PgpOnePassSignatureList p1 = (PgpOnePassSignatureList)pgpFact.NextPgpObject(); PgpOnePassSignature ops = p1[0]; PgpLiteralData p2 = (PgpLiteralData)pgpFact.NextPgpObject(); if (!p2.ModificationTime.Equals(testDateTime)) { Fail("Modification time not preserved"); } Stream dIn = p2.GetInputStream(); ops.InitVerify(pubKey); while ((ch = dIn.ReadByte()) >= 0) { ops.Update((byte)ch); } PgpSignatureList p3 = (PgpSignatureList)pgpFact.NextPgpObject(); if (!ops.Verify(p3[0])) { Fail("Failed Generated signature check"); } // // test encryption // // // find a key sutiable for encryption // long pgpKeyID = 0; AsymmetricKeyParameter pKey = null; foreach (PgpPublicKey pgpKey in pgpPub.GetPublicKeys()) { if (pgpKey.Algorithm == PublicKeyAlgorithmTag.ElGamalEncrypt || pgpKey.Algorithm == PublicKeyAlgorithmTag.ElGamalGeneral) { pKey = pgpKey.GetKey(); pgpKeyID = pgpKey.KeyId; if (pgpKey.BitStrength != 1024) { Fail("failed - key strength reported incorrectly."); } // // verify the key // } } IBufferedCipher c = CipherUtilities.GetCipher("ElGamal/None/PKCS1Padding"); c.Init(true, pKey); byte[] inBytes = Encoding.ASCII.GetBytes("hello world"); byte[] outBytes = c.DoFinal(inBytes); pgpPrivKey = sKey.GetSecretKey(pgpKeyID).ExtractPrivateKey(pass); c.Init(false, pgpPrivKey.Key); outBytes = c.DoFinal(outBytes); if (!Arrays.AreEqual(inBytes, outBytes)) { Fail("decryption failed."); } // // encrypted message // byte[] text = { (byte)'h', (byte)'e', (byte)'l', (byte)'l', (byte)'o', (byte)' ', (byte)'w', (byte)'o', (byte)'r', (byte)'l',(byte)'d', (byte)'!', (byte)'\n' }; PgpObjectFactory pgpF = new PgpObjectFactory(encMessage); PgpEncryptedDataList encList = (PgpEncryptedDataList)pgpF.NextPgpObject(); PgpPublicKeyEncryptedData encP = (PgpPublicKeyEncryptedData)encList[0]; Stream clear = encP.GetDataStream(pgpPrivKey); pgpFact = new PgpObjectFactory(clear); c1 = (PgpCompressedData)pgpFact.NextPgpObject(); pgpFact = new PgpObjectFactory(c1.GetDataStream()); PgpLiteralData ld = (PgpLiteralData)pgpFact.NextPgpObject(); if (!ld.FileName.Equals("test.txt")) { throw new Exception("wrong filename in packet"); } Stream inLd = ld.GetDataStream(); byte[] bytes = Streams.ReadAll(inLd); if (!Arrays.AreEqual(bytes, text)) { Fail("wrong plain text in decrypted packet"); } // // signed and encrypted message // pgpF = new PgpObjectFactory(signedAndEncMessage); encList = (PgpEncryptedDataList)pgpF.NextPgpObject(); encP = (PgpPublicKeyEncryptedData)encList[0]; clear = encP.GetDataStream(pgpPrivKey); pgpFact = new PgpObjectFactory(clear); c1 = (PgpCompressedData)pgpFact.NextPgpObject(); pgpFact = new PgpObjectFactory(c1.GetDataStream()); p1 = (PgpOnePassSignatureList)pgpFact.NextPgpObject(); ops = p1[0]; ld = (PgpLiteralData)pgpFact.NextPgpObject(); bOut = new MemoryStream(); if (!ld.FileName.Equals("test.txt")) { throw new Exception("wrong filename in packet"); } inLd = ld.GetDataStream(); // // note: we use the DSA public key here. // ops.InitVerify(pgpPub.GetPublicKey()); while ((ch = inLd.ReadByte()) >= 0) { ops.Update((byte)ch); bOut.WriteByte((byte)ch); } p3 = (PgpSignatureList)pgpFact.NextPgpObject(); if (!ops.Verify(p3[0])) { Fail("Failed signature check"); } if (!Arrays.AreEqual(bOut.ToArray(), text)) { Fail("wrong plain text in decrypted packet"); } // // encrypt // MemoryStream cbOut = new MemoryStream(); PgpEncryptedDataGenerator cPk = new PgpEncryptedDataGenerator( SymmetricKeyAlgorithmTag.TripleDes, random); PgpPublicKey puK = sKey.GetSecretKey(pgpKeyID).PublicKey; cPk.AddMethod(puK); Stream cOut = cPk.Open(new UncloseableStream(cbOut), bOut.ToArray().Length); cOut.Write(text, 0, text.Length); cOut.Close(); pgpF = new PgpObjectFactory(cbOut.ToArray()); encList = (PgpEncryptedDataList)pgpF.NextPgpObject(); encP = (PgpPublicKeyEncryptedData)encList[0]; pgpPrivKey = sKey.GetSecretKey(pgpKeyID).ExtractPrivateKey(pass); clear = encP.GetDataStream(pgpPrivKey); outBytes = Streams.ReadAll(clear); if (!Arrays.AreEqual(outBytes, text)) { Fail("wrong plain text in Generated packet"); } // // use of PgpKeyPair // BigInteger g = new BigInteger("153d5d6172adb43045b68ae8e1de1070b6137005686d29d3d73a7749199681ee5b212c9b96bfdcfa5b20cd5e3fd2044895d609cf9b410b7a0f12ca1cb9a428cc", 16); BigInteger p = new BigInteger("9494fec095f3b85ee286542b3836fc81a5dd0a0349b4c239dd38744d488cf8e31db8bcb7d33b41abb9e5a33cca9144b1cef332c94bf0573bf047a3aca98cdf3b", 16); ElGamalParameters elParams = new ElGamalParameters(p, g); IAsymmetricCipherKeyPairGenerator kpg = GeneratorUtilities.GetKeyPairGenerator("ELGAMAL"); kpg.Init(new ElGamalKeyGenerationParameters(random, elParams)); AsymmetricCipherKeyPair kp = kpg.GenerateKeyPair(); PgpKeyPair pgpKp = new PgpKeyPair(PublicKeyAlgorithmTag.ElGamalGeneral, kp.Public, kp.Private, DateTime.UtcNow); PgpPublicKey k1 = pgpKp.PublicKey; PgpPrivateKey k2 = pgpKp.PrivateKey; // Test bug with ElGamal P size != 0 mod 8 (don't use these sizes at home!) for (int pSize = 257; pSize < 264; ++pSize) { // Generate some parameters of the given size ElGamalParametersGenerator epg = new ElGamalParametersGenerator(); epg.Init(pSize, 2, random); elParams = epg.GenerateParameters(); kpg = GeneratorUtilities.GetKeyPairGenerator("ELGAMAL"); kpg.Init(new ElGamalKeyGenerationParameters(random, elParams)); // Run a short encrypt/decrypt test with random key for the given parameters kp = kpg.GenerateKeyPair(); PgpKeyPair elGamalKeyPair = new PgpKeyPair( PublicKeyAlgorithmTag.ElGamalGeneral, kp, DateTime.UtcNow); cPk = new PgpEncryptedDataGenerator(SymmetricKeyAlgorithmTag.Cast5, random); puK = elGamalKeyPair.PublicKey; cPk.AddMethod(puK); cbOut = new MemoryStream(); cOut = cPk.Open(new UncloseableStream(cbOut), text.Length); cOut.Write(text, 0, text.Length); cOut.Close(); pgpF = new PgpObjectFactory(cbOut.ToArray()); encList = (PgpEncryptedDataList)pgpF.NextPgpObject(); encP = (PgpPublicKeyEncryptedData)encList[0]; pgpPrivKey = elGamalKeyPair.PrivateKey; // Note: This is where an exception would be expected if the P size causes problems clear = encP.GetDataStream(pgpPrivKey); byte[] decText = Streams.ReadAll(clear); if (!Arrays.AreEqual(text, decText)) { Fail("decrypted message incorrect"); } } // check sub key encoding foreach (PgpPublicKey pgpKey in pgpPub.GetPublicKeys()) { if (!pgpKey.IsMasterKey) { byte[] kEnc = pgpKey.GetEncoded(); PgpObjectFactory objF = new PgpObjectFactory(kEnc); // TODO Make PgpPublicKey a PgpObject or return a PgpPublicKeyRing // PgpPublicKey k = (PgpPublicKey)objF.NextPgpObject(); // // pKey = k.GetKey(); // pgpKeyID = k.KeyId; // if (k.BitStrength != 1024) // { // Fail("failed - key strength reported incorrectly."); // } // // if (objF.NextPgpObject() != null) // { // Fail("failed - stream not fully parsed."); // } } } }
internal static byte[] Crypt( bool encrypt, byte[] bytes, char[] password, string dekAlgName, byte[] iv) { PemBaseAlg baseAlg; PemMode mode; ParseDekAlgName(dekAlgName, out baseAlg, out mode); string padding; switch (mode) { case PemMode.CBC: case PemMode.ECB: padding = "PKCS5Padding"; break; case PemMode.CFB: case PemMode.OFB: padding = "NoPadding"; break; default: throw new EncryptionException("Unknown DEK algorithm: " + dekAlgName); } string algorithm; byte[] salt = iv; switch (baseAlg) { case PemBaseAlg.AES_128: case PemBaseAlg.AES_192: case PemBaseAlg.AES_256: algorithm = "AES"; if (salt.Length > 8) { salt = new byte[8]; Array.Copy(iv, 0, salt, 0, salt.Length); } break; case PemBaseAlg.BF: algorithm = "BLOWFISH"; break; case PemBaseAlg.DES: algorithm = "DES"; break; case PemBaseAlg.DES_EDE: case PemBaseAlg.DES_EDE3: algorithm = "DESede"; break; case PemBaseAlg.RC2: case PemBaseAlg.RC2_40: case PemBaseAlg.RC2_64: algorithm = "RC2"; break; default: throw new EncryptionException("Unknown DEK algorithm: " + dekAlgName); } string cipherName = algorithm + "/" + mode + "/" + padding; IBufferedCipher cipher = CipherUtilities.GetCipher(cipherName); ICipherParameters cParams = GetCipherParameters(password, baseAlg, salt); if (mode != PemMode.ECB) { cParams = new ParametersWithIV(cParams, iv); } cipher.Init(encrypt, cParams); return(cipher.DoFinal(bytes)); }
/// <summary>Return the decrypted data stream for the packet.</summary> public Stream GetDataStream( PgpPrivateKey privKey) { IBufferedCipher c1 = GetKeyCipher(keyData.Algorithm); try { c1.Init(false, privKey.Key); } catch (InvalidKeyException e) { throw new PgpException("error setting asymmetric cipher", e); } BigInteger[] keyD = keyData.GetEncSessionKey(); if (keyData.Algorithm == PublicKeyAlgorithmTag.RsaEncrypt || keyData.Algorithm == PublicKeyAlgorithmTag.RsaGeneral) { byte[] bi = keyD[0].ToByteArray(); if (bi[0] == 0) { c1.ProcessBytes(bi, 1, bi.Length - 1); } else { c1.ProcessBytes(bi, 0, bi.Length); } } else { ElGamalPrivateKeyParameters k = (ElGamalPrivateKeyParameters)privKey.Key; int size = (k.Parameters.P.BitLength + 7) / 8; byte[] bi = keyD[0].ToByteArray(); int diff = bi.Length - size; if (diff >= 0) { c1.ProcessBytes(bi, diff, size); } else { byte[] zeros = new byte[-diff]; c1.ProcessBytes(zeros); c1.ProcessBytes(bi); } bi = keyD[1].ToByteArray(); diff = bi.Length - size; if (diff >= 0) { c1.ProcessBytes(bi, diff, size); } else { byte[] zeros = new byte[-diff]; c1.ProcessBytes(zeros); c1.ProcessBytes(bi); } } byte[] plain; try { plain = c1.DoFinal(); } catch (Exception e) { throw new PgpException("exception decrypting secret key", e); } if (!ConfirmCheckSum(plain)) { throw new PgpKeyValidationException("key checksum failed"); } IBufferedCipher c2; string cipherName = PgpUtilities.GetSymmetricCipherName((SymmetricKeyAlgorithmTag)plain[0]); string cName = cipherName; try { if (encData is SymmetricEncIntegrityPacket) { cName += "/CFB/NoPadding"; } else { cName += "/OpenPGPCFB/NoPadding"; } c2 = CipherUtilities.GetCipher(cName); } // catch (NoSuchProviderException e) catch (PgpException e) { throw e; } catch (Exception e) { throw new PgpException("exception creating cipher", e); } if (c2 == null) { return(encData.GetInputStream()); } try { byte[] keyBytes = new byte[plain.Length - 3]; Array.Copy(plain, 1, keyBytes, 0, keyBytes.Length); KeyParameter key = ParameterUtilities.CreateKeyParameter( cipherName, keyBytes); byte[] iv = new byte[c2.GetBlockSize()]; c2.Init(false, new ParametersWithIV(key, iv)); encStream = BcpgInputStream.Wrap(new CipherStream(encData.GetInputStream(), c2, null)); if (encData is SymmetricEncIntegrityPacket) { truncStream = new TruncatedStream(encStream); encStream = new DigestStream(truncStream, DigestUtilities.GetDigest(PgpUtilities.GetDigestName(HashAlgorithmTag.Sha1)), null); } for (int i = 0; i != iv.Length; i++) { int ch = encStream.ReadByte(); if (ch < 0) { throw new EndOfStreamException("unexpected end of stream."); } iv[i] = (byte)ch; } int v1 = encStream.ReadByte(); int v2 = encStream.ReadByte(); if (v1 < 0 || v2 < 0) { throw new EndOfStreamException("unexpected end of stream."); } // Note: the oracle attack on the "quick check" bytes is deemed // a security risk for typical public key encryption usages, // therefore we do not perform the check. // bool repeatCheckPassed = // iv[iv.Length - 2] == (byte)v1 // && iv[iv.Length - 1] == (byte)v2; // // // Note: some versions of PGP appear to produce 0 for the extra // // bytes rather than repeating the two previous bytes // bool zeroesCheckPassed = // v1 == 0 // && v2 == 0; // // if (!repeatCheckPassed && !zeroesCheckPassed) // { // throw new PgpDataValidationException("quick check failed."); // } return(encStream); } catch (PgpException e) { throw e; } catch (Exception e) { throw new PgpException("Exception starting decryption", e); } }
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 byte[] ExtractKeyData( char[] passPhrase) { SymmetricKeyAlgorithmTag alg = secret.EncAlgorithm; byte[] encData = secret.GetSecretKeyData(); if (alg == SymmetricKeyAlgorithmTag.Null) { return(encData); } byte[] data; IBufferedCipher c = null; try { string cName = PgpUtilities.GetSymmetricCipherName(alg); c = CipherUtilities.GetCipher(cName + "/CFB/NoPadding"); } catch (Exception e) { throw new PgpException("Exception creating cipher", e); } // TODO Factor this block out as 'encryptData' try { KeyParameter key = PgpUtilities.MakeKeyFromPassPhrase(secret.EncAlgorithm, secret.S2k, passPhrase); byte[] iv = secret.GetIV(); if (secret.PublicKeyPacket.Version == 4) { c.Init(false, new ParametersWithIV(key, iv)); data = c.DoFinal(encData); bool useSha1 = secret.S2kUsage == SecretKeyPacket.UsageSha1; byte[] check = Checksum(useSha1, data, (useSha1) ? data.Length - 20 : data.Length - 2); for (int i = 0; i != check.Length; i++) { if (check[i] != data[data.Length - check.Length + i]) { throw new PgpException("Checksum mismatch at " + i + " of " + check.Length); } } } else // version 2 or 3, RSA only. { data = new byte[encData.Length]; // // read in the four numbers // int pos = 0; for (int i = 0; i != 4; i++) { c.Init(false, new ParametersWithIV(key, iv)); int encLen = (((encData[pos] << 8) | (encData[pos + 1] & 0xff)) + 7) / 8; data[pos] = encData[pos]; data[pos + 1] = encData[pos + 1]; pos += 2; c.DoFinal(encData, pos, encLen, data, pos); pos += encLen; if (i != 3) { Array.Copy(encData, pos - iv.Length, iv, 0, iv.Length); } } // // verify Checksum // int cs = ((encData[pos] << 8) & 0xff00) | (encData[pos + 1] & 0xff); int calcCs = 0; for (int j = 0; j < data.Length - 2; j++) { calcCs += data[j] & 0xff; } calcCs &= 0xffff; if (calcCs != cs) { throw new PgpException("Checksum mismatch: passphrase wrong, expected " + cs.ToString("X") + " found " + calcCs.ToString("X")); } } return(data); } catch (PgpException e) { throw e; } catch (Exception e) { throw new PgpException("Exception decrypting key", e); } }
private void doTestGP( int size, int privateValueSize, BigInteger g, BigInteger p) { IAsymmetricCipherKeyPairGenerator keyGen = GeneratorUtilities.GetKeyPairGenerator("ElGamal"); // DHParameterSpec elParams = new DHParameterSpec(p, g); // keyGen.initialize(elParams); ElGamalParameters elParams = new ElGamalParameters(p, g, privateValueSize); ElGamalKeyGenerationParameters elKgp = new ElGamalKeyGenerationParameters( new SecureRandom(), elParams); keyGen.Init(elKgp); AsymmetricCipherKeyPair keyPair = keyGen.GenerateKeyPair(); SecureRandom rand = new SecureRandom(); checkKeySize(privateValueSize, keyPair); IBufferedCipher cipher = CipherUtilities.GetCipher("ElGamal"); cipher.Init(true, new ParametersWithRandom(keyPair.Public, rand)); byte[] inBytes = Encoding.ASCII.GetBytes("This is a test"); if (cipher.GetOutputSize(inBytes.Length) != (size / 8) * 2) { Fail("getOutputSize wrong on encryption"); } byte[] outBytes = cipher.DoFinal(inBytes); cipher.Init(false, keyPair.Private); if (cipher.GetOutputSize(outBytes.Length) != (size / 8) - 1) { Fail("GetOutputSize wrong on decryption"); } // // No Padding - maximum length // byte[] modBytes = ((ElGamalPublicKeyParameters)keyPair.Public).Parameters.P.ToByteArray(); byte[] maxInput = new byte[modBytes.Length - 1]; maxInput[0] |= 0x7f; cipher.Init(true, new ParametersWithRandom(keyPair.Public, rand)); outBytes = cipher.DoFinal(maxInput); cipher.Init(false, keyPair.Private); outBytes = cipher.DoFinal(outBytes); if (!AreEqual(outBytes, maxInput)) { Fail("NoPadding test failed on decrypt expected " + Hex.ToHexString(maxInput) + " got " + Hex.ToHexString(outBytes)); } // // encrypt/decrypt // IBufferedCipher c1 = CipherUtilities.GetCipher("ElGamal"); IBufferedCipher c2 = CipherUtilities.GetCipher("ElGamal"); c1.Init(true, new ParametersWithRandom(keyPair.Public, rand)); byte[] out1 = c1.DoFinal(inBytes); c2.Init(false, keyPair.Private); byte[] out2 = c2.DoFinal(out1); if (!AreEqual(inBytes, out2)) { Fail(size + " encrypt test failed"); } // // encrypt/decrypt with update // int outLen = c1.ProcessBytes(inBytes, 0, 2, out1, 0); outLen += c1.DoFinal(inBytes, 2, inBytes.Length - 2, out1, outLen); outLen = c2.ProcessBytes(out1, 0, 2, out2, 0); outLen += c2.DoFinal(out1, 2, out1.Length - 2, out2, outLen); if (!AreEqual(inBytes, out2)) { Fail(size + " encrypt with update test failed"); } // // public key encoding test // // byte[] pubEnc = keyPair.Public.GetEncoded(); byte[] pubEnc = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(keyPair.Public).GetDerEncoded(); // KeyFactory keyFac = KeyFactory.GetInstance("ElGamal"); // X509EncodedKeySpec pubX509 = new X509EncodedKeySpec(pubEnc); // DHPublicKeyParameters pubKey = (DHPublicKeyParameters)keyFac.generatePublic(pubX509); ElGamalPublicKeyParameters pubKey = (ElGamalPublicKeyParameters) PublicKeyFactory.CreateKey(pubEnc); ElGamalParameters spec = pubKey.Parameters; if (!spec.G.Equals(elParams.G) || !spec.P.Equals(elParams.P)) { Fail(size + " bit public key encoding/decoding test failed on parameters"); } if (!((ElGamalPublicKeyParameters)keyPair.Public).Y.Equals(pubKey.Y)) { Fail(size + " bit public key encoding/decoding test failed on y value"); } /* * // * // public key serialisation test * // * // TODO Is there some standard this serialization must conform to? * BinaryFormatter formatter = new BinaryFormatter(); * * MemoryStream bOut = new MemoryStream(); * // ObjectOutputStream oOut = new ObjectOutputStream(bOut); * // oOut.writeObject(keyPair.Public); * formatter.Serialize(bOut, keyPair.Public); * * MemoryStream bIn = new MemoryStream(bOut.ToArray(), false); * // ObjectInputStream oIn = new ObjectInputStream(bIn); * // pubKey = (DHPublicKeyParameters)oIn.readObject(); * pubKey = (ElGamalPublicKeyParameters) formatter.Deserialize(bIn); * spec = pubKey.Parameters; * * if (!spec.G.Equals(elParams.G) || !spec.P.Equals(elParams.P)) * { * Fail(size + " bit public key serialisation test failed on parameters"); * } * * if (!((ElGamalPublicKeyParameters )keyPair.Public).Y.Equals(pubKey.Y)) * { * Fail(size + " bit public key serialisation test failed on y value"); * } */ // // private key encoding test // // TODO Keys don't support GetEncoded // byte[] privEnc = keyPair.Private.GetEncoded(); byte[] privEnc = PrivateKeyInfoFactory.CreatePrivateKeyInfo(keyPair.Private).GetDerEncoded(); // PKCS8EncodedKeySpec privPKCS8 = new PKCS8EncodedKeySpec(privEnc); // DHPrivateKeyParameters privKey = (DHPrivateKeyParameters)keyFac.generatePrivate(privPKCS8); ElGamalPrivateKeyParameters privKey = (ElGamalPrivateKeyParameters) PrivateKeyFactory.CreateKey(privEnc); spec = privKey.Parameters; if (!spec.G.Equals(elParams.G) || !spec.P.Equals(elParams.P)) { Fail(size + " bit private key encoding/decoding test failed on parameters"); } if (!((ElGamalPrivateKeyParameters)keyPair.Private).X.Equals(privKey.X)) { Fail(size + " bit private key encoding/decoding test failed on y value"); } /* * // * // private key serialisation test * // * bOut = new MemoryStream(); * // oOut = new ObjectOutputStream(bOut); * // oOut.writeObject(keyPair.Private); * formatter.Serialize(bOut, keyPair.Private); * * bIn = new MemoryStream(bOut.ToArray(), false); * // oIn = new ObjectInputStream(bIn); * // privKey = (DHPrivateKeyParameters)oIn.readObject(); * privKey = (ElGamalPrivateKeyParameters) formatter.Deserialize(bIn); * spec = privKey.Parameters; * * if (!spec.G.Equals(elParams.G) || !spec.P.Equals(elParams.P)) * { * Fail(size + " bit private key serialisation test failed on parameters"); * } * * if (!((ElGamalPrivateKeyParameters) keyPair.Private).X.Equals(privKey.X)) * { * Fail(size + " bit private key serialisation test failed on y value"); * } */ }
/// <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); Platform.Dispose(cOut); 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) { 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)); }
public void init(String srcFile, String dstFile, String opMode, int segmentSize, Int64 srcFileOffset = 0, Int64 dstFileOffset = 0) { //System.Console.WriteLine("cipherMode: {0}, segment: {1}, srcOffset: {2}, dstOffset: {3}", // opMode, segmentSize, srcFileOffset, dstFileOffset); //@todo: walidacja opMode z segmentSize //@todo: try..catch wyrzucający System.ArgumentException // w OFB i CFB dł. podbloku musi być wielokrotnością 8 b, np. OFB8, OFB16 mOpMode = opMode; mSegmentSize = segmentSize >> 3; // divide by 8, i.e. [b] => [B] mBufferSize = BUFFER_SIZE - (BUFFER_SIZE % mSegmentSize); // size of the single chunk of data read from disk // multiplicity of segment size // mSrcFileOffset = srcFileOffset; mDstFileOffset = dstFileOffset; // w trybie "in memory" nie potrzeba podawać plików if (srcFile != null && dstFile != null) { mSrcFile = File.OpenRead(srcFile); mDstFile = (Encryption ? new FileStream(dstFile, FileMode.OpenOrCreate | FileMode.Append, FileAccess.Write) : File.Create(dstFile)); mSrcFile.Seek(mSrcFileOffset, SeekOrigin.Begin); mDstFile.Seek(mDstFileOffset, SeekOrigin.Begin); } // inicjalizacja algorytmu Serpent if (mOpMode == "OFB" || mOpMode == "CFB") { mOpMode += segmentSize.ToString(); } if (mOpMode != "ECB") { var cipherId = "Serpent/" + mOpMode + "/NoPadding"; //System.Console.WriteLine(cipherId); mSerpent = CipherUtilities.GetCipher(cipherId); mSerpent.Init(Encryption, combineKeyWithIV(mSessionKey, mIV)); } else { mSerpent = new BufferedBlockCipher(new SerpentEngine()); mSerpent.Init(Encryption, mSessionKey); } System.Console.WriteLine("serpent init"); }
/// <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 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 async Task <Optional <string> > GetSecretAsync(string name, string version = null, Dictionary <string, string> encryptionContext = null, bool throwOnInvalidCipherTextException = true) { CredstashItem item; if (version == null) { var response = await _amazonDynamoDb.QueryAsync(new QueryRequest() { TableName = Options.Table, Limit = 1, ScanIndexForward = false, ConsistentRead = true, KeyConditions = new Dictionary <string, Condition>() { { "name", new Condition() { ComparisonOperator = ComparisonOperator.EQ, AttributeValueList = new List <AttributeValue>() { new AttributeValue(name) } } } } }).ConfigureAwait(false); item = CredstashItem.From(response.Items.FirstOrDefault()); } else { var response = await _amazonDynamoDb.GetItemAsync(new GetItemRequest() { TableName = Options.Table, Key = new Dictionary <string, AttributeValue>() { { "name", new AttributeValue(name) }, { "version", new AttributeValue(version) }, } }).ConfigureAwait(false); item = CredstashItem.From(response.Item); } if (item == null) { return(null); } DecryptResponse decryptResponse; try { decryptResponse = await _amazonKeyManagementService.DecryptAsync(new DecryptRequest() { CiphertextBlob = new MemoryStream(Convert.FromBase64String(item.Key)), EncryptionContext = encryptionContext }).ConfigureAwait(false); } catch (InvalidCiphertextException e) { if (throwOnInvalidCipherTextException) { throw new CredstashException("Could not decrypt hmac key with KMS. The credential may " + "require that an encryption context be provided to decrypt " + "it.", e); } return(new Optional <string>()); } catch (Exception e) { throw new CredstashException("Decryption error", e); } var bytes = decryptResponse.Plaintext.ToArray(); var key = new byte[32]; var hmacKey = new byte[32]; Buffer.BlockCopy(bytes, 0, key, 0, 32); Buffer.BlockCopy(bytes, 32, hmacKey, 0, 32); var contents = Convert.FromBase64String(item.Contents); var hmac = new HMACSHA256(hmacKey); var result = hmac.ComputeHash(contents); if (!result.ToHexString().Equals(item.Hmac)) { throw new CredstashException($"HMAC Failure for {item.Name} v{item.Version}"); } IBufferedCipher cipher = CipherUtilities.GetCipher("AES/CTR/NoPadding"); cipher.Init(false, new ParametersWithIV(ParameterUtilities.CreateKeyParameter("AES", key), _initializationVector)); byte[] plaintext = cipher.DoFinal(contents); return(Encoding.UTF8.GetString(plaintext)); }
public CmsReadable GetReadable(KeyParameter sKey) { try { this.cipher = CipherUtilities.GetCipher(this.algorithm.ObjectID); Asn1Encodable asn1Enc = this.algorithm.Parameters; Asn1Object asn1Params = asn1Enc == null ? null : asn1Enc.ToAsn1Object(); ICipherParameters cipherParameters = sKey; if (asn1Params != null && !(asn1Params is Asn1Null)) { cipherParameters = ParameterUtilities.GetCipherParameters( this.algorithm.ObjectID, cipherParameters, asn1Params); } else { string alg = this.algorithm.ObjectID.Id; if (alg.Equals(CmsEnvelopedDataGenerator.DesEde3Cbc) || alg.Equals(CmsEnvelopedDataGenerator.IdeaCbc) || alg.Equals(CmsEnvelopedDataGenerator.Cast5Cbc)) { cipherParameters = new ParametersWithIV(cipherParameters, new byte[8]); } } cipher.Init(false, cipherParameters); } 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("error decoding algorithm parameters.", e); } try { return new CmsProcessableInputStream( new CipherStream(readable.GetInputStream(), cipher, null)); } catch (IOException e) { throw new CmsException("error reading content.", e); } }
public void WriteObject( object obj, string algorithm, char[] password, SecureRandom random) { if (obj == null) { throw new ArgumentNullException("obj"); } if (algorithm == null) { throw new ArgumentNullException("algorithm"); } if (password == null) { throw new ArgumentNullException("password"); } if (random == null) { throw new ArgumentNullException("random"); } byte[] keyData = null; if (obj is RsaPrivateCrtKeyParameters) { RsaPrivateCrtKeyParameters k = (RsaPrivateCrtKeyParameters)obj; keyData = PrivateKeyInfoFactory.CreatePrivateKeyInfo(k).PrivateKey.GetEncoded(); } else { // TODO Support other types? throw new ArgumentException("Object type not supported: " + obj.GetType().FullName, "obj"); } byte[] salt = new byte[8]; random.NextBytes(salt); OpenSslPbeParametersGenerator pGen = new OpenSslPbeParametersGenerator(); pGen.Init(PbeParametersGenerator.Pkcs5PasswordToBytes(password), salt); ICipherParameters secretKey = null; if (algorithm.ToUpper(CultureInfo.InvariantCulture).Equals("DESEDE")) { // generate key int keyLength = 24; secretKey = pGen.GenerateDerivedParameters(keyLength * 8); } else { throw new IOException("unknown algorithm in WriteObject"); } byte[] encData = null; // cipher try { IBufferedCipher c = CipherUtilities.GetCipher("DESede/CBC/PKCS5Padding"); c.Init(true, new ParametersWithIV(secretKey, salt)); encData = c.DoFinal(keyData); } catch (Exception e) { throw new IOException("exception using cipher: " + e.ToString()); } // write the data string type = "RSA PRIVATE KEY"; WriteHeader(type); writer.WriteLine("Proc-Type: 4,ENCRYPTED"); writer.Write("DEK-Info: DES-EDE3-CBC,"); WriteHexEncoded(salt); writer.WriteLine(); WriteBase64Encoded(encData); WriteFooter(type); }
/// <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 bool VerifyDigest( byte[] digest, AsymmetricKeyParameter key, byte[] signature) { string algorithm = Helper.GetEncryptionAlgName(this.EncryptionAlgOid); try { if (algorithm.Equals("RSA")) { IBufferedCipher c = CmsEnvelopedHelper.Instance.CreateAsymmetricCipher("RSA/ECB/PKCS1Padding"); c.Init(false, key); byte[] decrypt = c.DoFinal(signature); DigestInfo digInfo = DerDecode(decrypt); if (!digInfo.AlgorithmID.ObjectID.Equals(digestAlgorithm.ObjectID)) { return(false); } if (!IsNull(digInfo.AlgorithmID.Parameters)) { return(false); } byte[] sigHash = digInfo.GetDigest(); return(Arrays.ConstantTimeAreEqual(digest, sigHash)); } else if (algorithm.Equals("DSA")) { ISigner sig = SignerUtilities.GetSigner("NONEwithDSA"); sig.Init(false, key); sig.BlockUpdate(digest, 0, digest.Length); return(sig.VerifySignature(signature)); } else { throw new CmsException("algorithm: " + algorithm + " not supported in base signatures."); } } catch (SecurityUtilityException e) { throw e; } catch (GeneralSecurityException e) { throw new CmsException("Exception processing signature: " + e, e); } catch (IOException e) { throw new CmsException("Exception decoding signature: " + e, e); } }