private static void requestParse( byte[] request, string algorithm) { TimeStampRequest req = new TimeStampRequest(request); if (!req.MessageImprintAlgOid.Equals(algorithm)) { Assert.Fail("failed to get expected algorithm - got " + req.MessageImprintAlgOid + " not " + algorithm); } if (request != sha1Request && request != sha1noNonse) { if (!req.ReqPolicy.Equals(TspTestUtil.EuroPkiTsaTestPolicy.Id)) { Assert.Fail("" + algorithm + " failed policy check."); } if (request == ripemd160Request) { if (!req.CertReq) { Assert.Fail("" + algorithm + " failed certReq check."); } } } Assert.AreEqual(1, req.Version, "version not 1"); Assert.IsNull(req.GetCriticalExtensionOids(), "critical extensions found when none expected"); Assert.IsNull(req.GetNonCriticalExtensionOids(), "non-critical extensions found when none expected"); if (request != sha1noNonse) { if (req.Nonce == null) { Assert.Fail("" + algorithm + " nonse not found when one expected."); } } else { if (req.Nonce != null) { Assert.Fail("" + algorithm + " nonse not found when one not expected."); } } try { req.Validate(TspAlgorithms.Allowed, null, null); } catch (Exception) { Assert.Fail("validation exception."); } if (!Arrays.AreEqual(req.GetEncoded(), request)) { Assert.Fail("" + algorithm + " failed encode check."); } }
private void DoEngineTestFp() { BigInteger SM2_ECC_P = new BigInteger("8542D69E4C044F18E8B92435BF6FF7DE457283915C45517D722EDB8B08F1DFC3", 16); BigInteger SM2_ECC_A = new BigInteger("787968B4FA32C3FD2417842E73BBFEFF2F3C848B6831D7E0EC65228B3937E498", 16); BigInteger SM2_ECC_B = new BigInteger("63E4C6D3B23B0C849CF84241484BFE48F61D59A5B16BA06E6E12D1DA27C5249A", 16); BigInteger SM2_ECC_N = new BigInteger("8542D69E4C044F18E8B92435BF6FF7DD297720630485628D5AE74EE7C32E79B7", 16); BigInteger SM2_ECC_H = BigInteger.One; BigInteger SM2_ECC_GX = new BigInteger("421DEBD61B62EAB6746434EBC3CC315E32220B3BADD50BDC4C4E6C147FEDD43D", 16); BigInteger SM2_ECC_GY = new BigInteger("0680512BCBB42C07D47349D2153B70C4E5D7FDFCBFA36EA1A85841B9E46E09A2", 16); ECCurve curve = new FpCurve(SM2_ECC_P, SM2_ECC_A, SM2_ECC_B, SM2_ECC_N, SM2_ECC_H); ECPoint g = curve.CreatePoint(SM2_ECC_GX, SM2_ECC_GY); ECDomainParameters domainParams = new ECDomainParameters(curve, g, SM2_ECC_N); ECKeyPairGenerator keyPairGenerator = new ECKeyPairGenerator(); ECKeyGenerationParameters aKeyGenParams = new ECKeyGenerationParameters(domainParams, new TestRandomBigInteger("1649AB77A00637BD5E2EFE283FBF353534AA7F7CB89463F208DDBC2920BB0DA0", 16)); keyPairGenerator.Init(aKeyGenParams); AsymmetricCipherKeyPair aKp = keyPairGenerator.GenerateKeyPair(); ECPublicKeyParameters aPub = (ECPublicKeyParameters)aKp.Public; ECPrivateKeyParameters aPriv = (ECPrivateKeyParameters)aKp.Private; SM2Engine sm2Engine = new SM2Engine(); byte[] m = Strings.ToByteArray("encryption standard"); sm2Engine.Init(true, new ParametersWithRandom(aPub, new TestRandomBigInteger("4C62EEFD6ECFC2B95B92FD6C3D9575148AFA17425546D49018E5388D49DD7B4F", 16))); byte[] enc = sm2Engine.ProcessBlock(m, 0, m.Length); IsTrue("enc wrong", Arrays.AreEqual(Hex.Decode( "04245C26 FB68B1DD DDB12C4B 6BF9F2B6 D5FE60A3 83B0D18D 1C4144AB F17F6252" + "E776CB92 64C2A7E8 8E52B199 03FDC473 78F605E3 6811F5C0 7423A24B 84400F01" + "B8650053 A89B41C4 18B0C3AA D00D886C 00286467 9C3D7360 C30156FA B7C80A02" + "76712DA9 D8094A63 4B766D3A 285E0748 0653426D"), enc)); sm2Engine.Init(false, aPriv); byte[] dec = sm2Engine.ProcessBlock(enc, 0, enc.Length); IsTrue("dec wrong", Arrays.AreEqual(m, dec)); enc[80] = (byte)(enc[80] + 1); try { sm2Engine.ProcessBlock(enc, 0, enc.Length); Fail("no exception"); } catch (InvalidCipherTextException e) { IsTrue("wrong exception", "invalid cipher text".Equals(e.Message)); } // long message sm2Engine = new SM2Engine(); m = new byte[4097]; for (int i = 0; i != m.Length; i++) { m[i] = (byte)i; } sm2Engine.Init(true, new ParametersWithRandom(aPub, new TestRandomBigInteger("4C62EEFD6ECFC2B95B92FD6C3D9575148AFA17425546D49018E5388D49DD7B4F", 16))); enc = sm2Engine.ProcessBlock(m, 0, m.Length); sm2Engine.Init(false, aPriv); dec = sm2Engine.ProcessBlock(enc, 0, enc.Length); IsTrue("dec wrong", Arrays.AreEqual(m, dec)); }
private ITestResult KeyWrapTests() { //KW mode (PADDING NOT SUPPORTED) //test 1 byte[] key = Hex.Decode("000102030405060708090A0B0C0D0E0F"); byte[] textToWrap = Hex.Decode("101112131415161718191A1B1C1D1E1F"); byte[] expectedWrappedText = Hex.Decode("1DC91DC6E52575F6DBED25ADDA95A1B6AD3E15056E489738972C199FB9EE2913"); byte[] output = new byte[expectedWrappedText.Length]; Dstu7624WrapEngine wrapper = new Dstu7624WrapEngine(128); wrapper.Init(true, new KeyParameter(key)); output = wrapper.Wrap(textToWrap, 0, textToWrap.Length); if (!Arrays.AreEqual(output, expectedWrappedText)) { return(new SimpleTestResult(false, Name + ": Failed KW (wrapping) test 1 - expected " + Hex.ToHexString(expectedWrappedText) + " got " + Hex.ToHexString(output))); } wrapper.Init(false, new KeyParameter(key)); output = wrapper.Unwrap(expectedWrappedText, 0, expectedWrappedText.Length); if (!Arrays.AreEqual(output, textToWrap)) { return(new SimpleTestResult(false, Name + ": Failed KW (unwrapping) test 1 - expected " + Hex.ToHexString(textToWrap) + " got " + Hex.ToHexString(output))); } //test 2 key = Hex.Decode("000102030405060708090A0B0C0D0E0F"); textToWrap = Hex.Decode("101112131415161718191A1B1C1D1E1F20219000000000000000800000000000"); expectedWrappedText = Hex.Decode("0EA983D6CE48484D51462C32CC61672210FCC44196ABE635BAF878FDB83E1A63114128585D49DB355C5819FD38039169"); output = new byte[expectedWrappedText.Length]; wrapper.Init(true, new KeyParameter(key)); output = wrapper.Wrap(textToWrap, 0, textToWrap.Length); if (!Arrays.AreEqual(output, expectedWrappedText)) { return(new SimpleTestResult(false, Name + ": Failed KW (wrapping) test 2 - expected " + Hex.ToHexString(expectedWrappedText) + " got " + Hex.ToHexString(output))); } wrapper.Init(false, new KeyParameter(key)); output = wrapper.Unwrap(expectedWrappedText, 0, expectedWrappedText.Length); if (!Arrays.AreEqual(output, textToWrap)) { return(new SimpleTestResult(false, Name + ": Failed KW (unwrapping) test 2 - expected " + Hex.ToHexString(textToWrap) + " got " + Hex.ToHexString(output))); } //test 3 key = Hex.Decode("000102030405060708090A0B0C0D0E0F101112131415161718191A1B1C1D1E1F"); textToWrap = Hex.Decode("202122232425262728292A2B2C2D2E2F303132333435363738393A3B3C3D3E3F404142434445464748494A4B4C4D4E4F"); expectedWrappedText = Hex.Decode("2D09A7C18E6A5A0816331EC27CEA596903F77EC8D63F3BDB73299DE7FD9F4558E05992B0B24B39E02EA496368E0841CC1E3FA44556A3048C5A6E9E335717D17D"); output = new byte[expectedWrappedText.Length]; wrapper = new Dstu7624WrapEngine(128); wrapper.Init(true, new KeyParameter(key)); output = wrapper.Wrap(textToWrap, 0, textToWrap.Length); if (!Arrays.AreEqual(output, expectedWrappedText)) { return(new SimpleTestResult(false, Name + ": Failed KW (wrapping) test 3 - expected " + Hex.ToHexString(expectedWrappedText) + " got " + Hex.ToHexString(output))); } wrapper.Init(false, new KeyParameter(key)); output = wrapper.Unwrap(expectedWrappedText, 0, expectedWrappedText.Length); if (!Arrays.AreEqual(output, textToWrap)) { return(new SimpleTestResult(false, Name + ": Failed KW (unwrapping) test 3 - expected " + Hex.ToHexString(textToWrap) + " got " + Hex.ToHexString(output))); } //test 4 key = Hex.Decode("000102030405060708090A0B0C0D0E0F101112131415161718191A1B1C1D1E1F"); textToWrap = Hex.Decode("202122232425262728292A2B2C2D2E2F303132333435363738393A3B3C3D3E3F404142434445464E8040000000000020"); expectedWrappedText = Hex.Decode("37E3EECB91150C6FA04CFD19D6FC57B7168C9FA5C5ED18601C68EE4AFD7301F8C8C51D7A0A5CD34F6FAB0D8AF11845CC1E4B16E0489FDA1D76BA4EFCFD161F76"); output = new byte[expectedWrappedText.Length]; wrapper = new Dstu7624WrapEngine(128); wrapper.Init(true, new KeyParameter(key)); output = wrapper.Wrap(textToWrap, 0, textToWrap.Length); if (!Arrays.AreEqual(output, expectedWrappedText)) { return(new SimpleTestResult(false, Name + ": Failed KW (wrapping) test 4 - expected " + Hex.ToHexString(expectedWrappedText) + " got " + Hex.ToHexString(output))); } wrapper.Init(false, new KeyParameter(key)); output = wrapper.Unwrap(expectedWrappedText, 0, expectedWrappedText.Length); if (!Arrays.AreEqual(output, textToWrap)) { return(new SimpleTestResult(false, Name + ": Failed KW (unwrapping) test 4 - expected " + Hex.ToHexString(textToWrap) + " got " + Hex.ToHexString(output))); } //test 5 key = Hex.Decode("000102030405060708090A0B0C0D0E0F101112131415161718191A1B1C1D1E1F"); textToWrap = Hex.Decode("202122232425262728292A2B2C2D2E2F303132333435363738393A3B3C3D3E3F404142434445464748494A4B4C4D4E4F505152535455565758595A5B5C5D5E5F606162636465666768696A6B6C6D6E6F707172737475767778797A7B7C7D7E7F"); expectedWrappedText = Hex.Decode("BE59D3C3C31B2685A8FA57CD000727F16AF303F0D87BC2D7ABD80DC2796BBC4CDBC4E0408943AF4DAF7DE9084DC81BFEF15FDCDD0DF399983DF69BF730D7AE2A199CA4F878E4723B7171DD4D1E8DF59C0F25FA0C20946BA64F9037D724BB1D50B6C2BD9788B2AF83EF6163087CD2D4488BC19F3A858D813E3A8947A529B6D65D"); output = new byte[expectedWrappedText.Length]; wrapper = new Dstu7624WrapEngine(256); wrapper.Init(true, new KeyParameter(key)); output = wrapper.Wrap(textToWrap, 0, textToWrap.Length); if (!Arrays.AreEqual(output, expectedWrappedText)) { return(new SimpleTestResult(false, Name + ": Failed KW (wrapping) test 5 - expected " + Hex.ToHexString(expectedWrappedText) + " got " + Hex.ToHexString(output))); } wrapper.Init(false, new KeyParameter(key)); output = wrapper.Unwrap(expectedWrappedText, 0, expectedWrappedText.Length); if (!Arrays.AreEqual(output, textToWrap)) { return(new SimpleTestResult(false, Name + ": Failed KW (unwrapping) test 5 - expected " + Hex.ToHexString(textToWrap) + " got " + Hex.ToHexString(output))); } //test 6 key = Hex.Decode("000102030405060708090A0B0C0D0E0F101112131415161718191A1B1C1D1E1F"); textToWrap = Hex.Decode("202122232425262728292A2B2C2D2E2F303132333435363738393A3B3C3D3E3F404142434445464748494A4B4C4D4E4F505152535455565758595A5B5C5D5E5F606162636465666768696A6B6C6D6E6F708802000000000000000000000000000080000000000000000000000000000000000000000000000000000000000000"); expectedWrappedText = Hex.Decode("CC41D643B08592F509432E3C6F4B73156907A53B9FFB99B157DEC708F917AEA1E41D76475EDFB138A8B0220A152B673E9713DE7A2791E3573FE257C3FF3C0DAA9AD13477E52770F54CBF94D1603AED7CA876FB7913BC359D2B89562299FA92D32A9C17DBE4CC21CCE097089B9FBC245580D6DB59F8731D864B604E654397E5F5E7A79A6A777C75856039C8C86140D0CB359CA3923D902D08269F8D48E7F0F085"); output = new byte[expectedWrappedText.Length]; wrapper = new Dstu7624WrapEngine(256); wrapper.Init(true, new KeyParameter(key)); output = wrapper.Wrap(textToWrap, 0, textToWrap.Length); if (!Arrays.AreEqual(output, expectedWrappedText)) { return(new SimpleTestResult(false, Name + ": Failed KW (wrapping) test 6 - expected " + Hex.ToHexString(expectedWrappedText) + " got " + Hex.ToHexString(output))); } wrapper.Init(false, new KeyParameter(key)); output = wrapper.Unwrap(expectedWrappedText, 0, expectedWrappedText.Length); if (!Arrays.AreEqual(output, textToWrap)) { return(new SimpleTestResult(false, Name + ": Failed KW (unwrapping) test 6 - expected " + Hex.ToHexString(textToWrap) + " got " + Hex.ToHexString(output))); } //test 7 key = Hex.Decode("000102030405060708090A0B0C0D0E0F101112131415161718191A1B1C1D1E1F202122232425262728292A2B2C2D2E2F303132333435363738393A3B3C3D3E3F"); textToWrap = Hex.Decode("404142434445464748494A4B4C4D4E4F505152535455565758595A5B5C5D5E5F606162636465666768696A6B6C6D6E6F707172737475767778797A7B7C7D7E7F808182838485868788898A8B8C8D8E8F909192939495969798999A9B9C9D9E9F"); expectedWrappedText = Hex.Decode("599217EB2B5270ECEF0BB716D70E251234A2451CE04FCFBAEEA92022C581F19B7C9386BB7476B4AD721D40778F49062C3605F1E8FAC9F3F3AC04E46E89E1844DBF4F18FA9303B288741ABD71013CF208F31B4C76FBE342F89B1ABFD97E830457555651B74D3CCDBF94CC5E5EEC22821536A96F44C8BC4346B0271303E67FD313"); output = new byte[expectedWrappedText.Length]; wrapper = new Dstu7624WrapEngine(256); wrapper.Init(true, new KeyParameter(key)); output = wrapper.Wrap(textToWrap, 0, textToWrap.Length); if (!Arrays.AreEqual(output, expectedWrappedText)) { return(new SimpleTestResult(false, Name + ": Failed KW (wrapping) test 7 - expected " + Hex.ToHexString(expectedWrappedText) + " got " + Hex.ToHexString(output))); } wrapper.Init(false, new KeyParameter(key)); output = wrapper.Unwrap(expectedWrappedText, 0, expectedWrappedText.Length); if (!Arrays.AreEqual(output, textToWrap)) { return(new SimpleTestResult(false, Name + ": Failed KW (unwrapping) test 7 - expected " + Hex.ToHexString(textToWrap) + " got " + Hex.ToHexString(output))); } //test 8 key = Hex.Decode("000102030405060708090A0B0C0D0E0F101112131415161718191A1B1C1D1E1F202122232425262728292A2B2C2D2E2F303132333435363738393A3B3C3D3E3F"); textToWrap = Hex.Decode("404142434445464748494A4B4C4D4E4F505152535455565758595A5B5C5D5E5F606162636465666768696A6B6C6D6E6F707172737475767778797A7B7C7D7E7F808182838485868788898A8B8C8D8E8F908802000000000000000000000000000080000000000000000000000000000000000000000000000000000000000000"); expectedWrappedText = Hex.Decode("B92E58F53C38F7D23F1068FA98B921AC800AD0D1947BD620700D0B6088F87D03D6A516F54198154D0C71169C2BCF520F3DF3DF527FC23E800E9A65158D45BB253A3BD0493E4822DF0DB5A366BC2F47551C5D477DDDE724A0B869F562223CEDB9D4AA36C750FA864ADF938273FBC859F7D4930F6B70C6474304AB670BA32CB0C41023769338A29EA1555F526CDFEB75C72212CD2D29F4BA49C2A62ACBE4F3272B"); output = new byte[expectedWrappedText.Length]; wrapper = new Dstu7624WrapEngine(256); wrapper.Init(true, new KeyParameter(key)); output = wrapper.Wrap(textToWrap, 0, textToWrap.Length); if (!Arrays.AreEqual(output, expectedWrappedText)) { return(new SimpleTestResult(false, Name + ": Failed KW (wrapping) test 8 - expected " + Hex.ToHexString(expectedWrappedText) + " got " + Hex.ToHexString(output))); } wrapper.Init(false, new KeyParameter(key)); output = wrapper.Unwrap(expectedWrappedText, 0, expectedWrappedText.Length); if (!Arrays.AreEqual(output, textToWrap)) { return(new SimpleTestResult(false, Name + ": Failed KW (unwrapping) test 8 - expected " + Hex.ToHexString(textToWrap) + " got " + Hex.ToHexString(output))); } //test 9 key = Hex.Decode("000102030405060708090A0B0C0D0E0F101112131415161718191A1B1C1D1E1F202122232425262728292A2B2C2D2E2F303132333435363738393A3B3C3D3E3F"); textToWrap = Hex.Decode("404142434445464748494A4B4C4D4E4F505152535455565758595A5B5C5D5E5F606162636465666768696A6B6C6D6E6F707172737475767778797A7B7C7D7E7F808182838485868788898A8B8C8D8E8F909192939495969798999A9B9C9D9E9FA0A1A2A3A4A5A6A7A8A9AAABACADAEAFB0B1B2B3B4B5B6B7B8B9BABBBCBDBEBF"); expectedWrappedText = Hex.Decode("9618AE6065069D5054464040F17337D58BEB51AE92391D740BDF7ABB239709C46270832039FF045BCF7878E7DA9C3B4CF89326CA8B4D29DB8680EEAE1B5A18463284713A323A69AEBF33CFC4B11283C7C8041FFC97668EDF727823411C9559816C108C11EC401643765527860D8DA0ED7254792C21DB775DEB1D6971C924CC83EB626173D894694943B1828ABDE8F9495BCEBA9AC3A4A03592C085AA29CC9A0C65786E631A702D589B819C89E79EEFF29C4EC312C8860BB68F02272EA770FB8D"); output = new byte[expectedWrappedText.Length]; wrapper = new Dstu7624WrapEngine(512); wrapper.Init(true, new KeyParameter(key)); output = wrapper.Wrap(textToWrap, 0, textToWrap.Length); if (!Arrays.AreEqual(output, expectedWrappedText)) { return(new SimpleTestResult(false, Name + ": Failed KW (wrapping) test 9 - expected " + Hex.ToHexString(expectedWrappedText) + " got " + Hex.ToHexString(output))); } wrapper.Init(false, new KeyParameter(key)); output = wrapper.Unwrap(expectedWrappedText, 0, expectedWrappedText.Length); if (!Arrays.AreEqual(output, textToWrap)) { return(new SimpleTestResult(false, Name + ": Failed KW (unwrapping) test 9 - expected " + Hex.ToHexString(textToWrap) + " got " + Hex.ToHexString(output))); } //test 10 key = Hex.Decode("000102030405060708090A0B0C0D0E0F101112131415161718191A1B1C1D1E1F202122232425262728292A2B2C2D2E2F303132333435363738393A3B3C3D3E3F"); textToWrap = Hex.Decode("404142434445464748494A4B4C4D4E4F505152535455565758595A5B5C5D5E5F606162636465666768696A6B6C6D6E6F707172737475767778797A7B7C7D7E7F808182838485868788898A8B8C8D8E8F909192939495969798999A9B9C9D9E9FA0A1A2A3A4A5A6A7A8A9AAABACADAEAFB0B1B2B3B4B5B6B7B8B9BABBBCBDBEBFC0C1C2C3C4C5C6C7C8C9CACBCCCDCECFD0D1D2D3D4D5D6D7D8D9DADBDCDDDEDFE00805000000000000000000000000000000000000000000000000000000000000800000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"); expectedWrappedText = Hex.Decode("3A05BB41513555F171E9234D4834EDAD16C0BAA6136197650138219C5DA406A703C39259E9DCCF6F2691EC691CE7414B5D3CDA006DE6D6C62142FAAA742C5F8AF64FCE95BE7ABA7FE5E06C3C33EE67BAEAB196E3A71132CAE78CD605A22E34D53CD159217E7B692CC79FAC66BF5E08DBC4FE274299474E176DDDF9F462AC63F4872E9B7F16B98AA56707EE5F2F94616CFC6A9548ADBD7DCB73664C331213964593F712ECCDFA7A94E3ABA7995176EA4B7E77096A3A3FF4E4087F430B62D5DEE64999F235FA9EAC79896A1C2258BF1DFC8A6AD0E5E7E06EAEEA0CCC2DEF62F67ECE8D12EFF432277C40A7BF1A23440B3533AF1E2F7AE1BBC076D12628BB4BC7B2E4D4B4353BCEAF9A67276B3FA23CADCA80062B95EBB2D51510AFA16F97249DF98E7B845C9A410F24B3C8B3E838E58D22BC2D14F46190FC1BFDB60C9691404F99"); output = new byte[expectedWrappedText.Length]; wrapper = new Dstu7624WrapEngine(512); wrapper.Init(true, new KeyParameter(key)); output = wrapper.Wrap(textToWrap, 0, textToWrap.Length); if (!Arrays.AreEqual(output, expectedWrappedText)) { return(new SimpleTestResult(false, Name + ": Failed KW (wrapping) test 10 - expected " + Hex.ToHexString(expectedWrappedText) + " got " + Hex.ToHexString(output))); } wrapper.Init(false, new KeyParameter(key)); output = wrapper.Unwrap(expectedWrappedText, 0, expectedWrappedText.Length); if (!Arrays.AreEqual(output, textToWrap)) { return(new SimpleTestResult(false, Name + ": Failed KW (unwrapping) test 10 - expected " + Hex.ToHexString(textToWrap) + " got " + Hex.ToHexString(output))); } return(new SimpleTestResult(true, Name + ": Okay")); }
public bool Match( X509Certificate x509Cert) { try { if (holder.BaseCertificateID != null) { return(holder.BaseCertificateID.Serial.Value.Equals(x509Cert.SerialNumber) && MatchesDN(x509Cert.IssuerDN, holder.BaseCertificateID.Issuer)); } if (holder.EntityName != null) { if (MatchesDN(x509Cert.SubjectDN, holder.EntityName)) { return(true); } } if (holder.ObjectDigestInfo != null) { IDigestFactory <AlgorithmIdentifier> digestFact = new PkixDigestFactory(holder.ObjectDigestInfo.DigestAlgorithm); IStreamCalculator <IBlockResult> digestCalc = digestFact.CreateCalculator(); switch (DigestedObjectType) { case ObjectDigestInfo.PublicKey: { // TODO: DSA Dss-parms //byte[] b = x509Cert.GetPublicKey().getEncoded(); // TODO Is this the right way to encode? byte[] b = x509Cert.GetPublicKey().GetEncoded(); digestCalc.Stream.Write(b, 0, b.Length); break; } case ObjectDigestInfo.PublicKeyCert: { byte[] b = x509Cert.GetEncoded(); digestCalc.Stream.Write(b, 0, b.Length); break; } // TODO Default handler? } digestCalc.Stream.Close(); if (!Arrays.AreEqual(GetObjectDigest(), digestCalc.GetResult().Collect())) { return(false); } } } catch (CertificateEncodingException) { return(false); } return(false); }
public void Init(byte[] H) { if (M == null) { M = new uint[32][][]; } else if (Arrays.AreEqual(this.H, H)) { return; } this.H = Arrays.Clone(H); M[0] = new uint[16][]; M[1] = new uint[16][]; M[0][0] = new uint[4]; M[1][0] = new uint[4]; M[1][8] = GcmUtilities.AsUints(H); for (int num = 4; num >= 1; num >>= 1) { uint[] array = (uint[])M[1][num + num].Clone(); GcmUtilities.MultiplyP(array); M[1][num] = array; } uint[] array2 = (uint[])M[1][1].Clone(); GcmUtilities.MultiplyP(array2); M[0][8] = array2; for (int num2 = 4; num2 >= 1; num2 >>= 1) { uint[] array3 = (uint[])M[0][num2 + num2].Clone(); GcmUtilities.MultiplyP(array3); M[0][num2] = array3; } int num3 = 0; while (true) { for (int i = 2; i < 16; i += i) { for (int j = 1; j < i; j++) { uint[] array4 = (uint[])M[num3][i].Clone(); GcmUtilities.Xor(array4, M[num3][j]); M[num3][i + j] = array4; } } if (++num3 == 32) { break; } if (num3 > 1) { M[num3] = new uint[16][]; M[num3][0] = new uint[4]; for (int num4 = 8; num4 > 0; num4 >>= 1) { uint[] array5 = (uint[])M[num3 - 2][num4].Clone(); GcmUtilities.MultiplyP8(array5); M[num3][num4] = array5; } } } }
private bool DoVerify(AsymmetricKeyParameter key) { //IL_019b: Expected O, but got Unknown //IL_03a0: Expected O, but got Unknown string digestAlgName = Helper.GetDigestAlgName(DigestAlgOid); IDigest digestInstance = Helper.GetDigestInstance(digestAlgName); DerObjectIdentifier algorithm = encryptionAlgorithm.Algorithm; Asn1Encodable parameters = encryptionAlgorithm.Parameters; ISigner signer; if (algorithm.Equals(PkcsObjectIdentifiers.IdRsassaPss)) { if (parameters == null) { throw new CmsException("RSASSA-PSS signature must specify algorithm parameters"); } try { RsassaPssParameters instance = RsassaPssParameters.GetInstance(parameters.ToAsn1Object()); if (!instance.HashAlgorithm.Algorithm.Equals(digestAlgorithm.Algorithm)) { throw new CmsException("RSASSA-PSS signature parameters specified incorrect hash algorithm"); } if (!instance.MaskGenAlgorithm.Algorithm.Equals(PkcsObjectIdentifiers.IdMgf1)) { throw new CmsException("RSASSA-PSS signature parameters specified unknown MGF"); } IDigest digest = DigestUtilities.GetDigest(instance.HashAlgorithm.Algorithm); int intValue = instance.SaltLength.Value.IntValue; byte b = (byte)instance.TrailerField.Value.IntValue; if (b != 1) { throw new CmsException("RSASSA-PSS signature parameters must have trailerField of 1"); } signer = new PssSigner(new RsaBlindedEngine(), digest, intValue); } catch (global::System.Exception e) { throw new CmsException("failed to set RSASSA-PSS signature parameters", e); } } else { string algorithm2 = digestAlgName + "with" + Helper.GetEncryptionAlgName(EncryptionAlgOid); signer = Helper.GetSignatureInstance(algorithm2); } try { if (digestCalculator != null) { resultDigest = digestCalculator.GetDigest(); } else { if (content != null) { content.Write((Stream)(object)new DigOutputStream(digestInstance)); } else if (signedAttributeSet == null) { throw new CmsException("data not encapsulated in signature - use detached constructor."); } resultDigest = DigestUtilities.DoFinal(digestInstance); } } catch (IOException val) { IOException e2 = val; throw new CmsException("can't process mime object to create signature.", (global::System.Exception)(object) e2); } Asn1Object singleValuedSignedAttribute = GetSingleValuedSignedAttribute(CmsAttributes.ContentType, "content-type"); if (singleValuedSignedAttribute == null) { if (!isCounterSignature && signedAttributeSet != null) { throw new CmsException("The content-type attribute type MUST be present whenever signed attributes are present in signed-data"); } } else { if (isCounterSignature) { throw new CmsException("[For counter signatures,] the signedAttributes field MUST NOT contain a content-type attribute"); } if (!(singleValuedSignedAttribute is DerObjectIdentifier)) { throw new CmsException("content-type attribute value not of ASN.1 type 'OBJECT IDENTIFIER'"); } DerObjectIdentifier derObjectIdentifier = (DerObjectIdentifier)singleValuedSignedAttribute; if (!derObjectIdentifier.Equals(contentType)) { throw new CmsException("content-type attribute value does not match eContentType"); } } Asn1Object singleValuedSignedAttribute2 = GetSingleValuedSignedAttribute(CmsAttributes.MessageDigest, "message-digest"); if (singleValuedSignedAttribute2 == null) { if (signedAttributeSet != null) { throw new CmsException("the message-digest signed attribute type MUST be present when there are any signed attributes present"); } } else { if (!(singleValuedSignedAttribute2 is Asn1OctetString)) { throw new CmsException("message-digest attribute value not of ASN.1 type 'OCTET STRING'"); } Asn1OctetString asn1OctetString = (Asn1OctetString)singleValuedSignedAttribute2; if (!Arrays.AreEqual(resultDigest, asn1OctetString.GetOctets())) { throw new CmsException("message-digest attribute value does not match calculated value"); } } Org.BouncyCastle.Asn1.Cms.AttributeTable signedAttributes = SignedAttributes; if (signedAttributes != null && signedAttributes.GetAll(CmsAttributes.CounterSignature).Count > 0) { throw new CmsException("A countersignature attribute MUST NOT be a signed attribute"); } Org.BouncyCastle.Asn1.Cms.AttributeTable unsignedAttributes = UnsignedAttributes; if (unsignedAttributes != null) { { global::System.Collections.IEnumerator enumerator = unsignedAttributes.GetAll(CmsAttributes.CounterSignature).GetEnumerator(); try { while (enumerator.MoveNext()) { Attribute attribute = (Attribute)enumerator.get_Current(); if (attribute.AttrValues.Count < 1) { throw new CmsException("A countersignature attribute MUST contain at least one AttributeValue"); } } } finally { global::System.IDisposable disposable = enumerator as global::System.IDisposable; if (disposable != null) { disposable.Dispose(); } } } } try { signer.Init(forSigning: false, key); if (signedAttributeSet == null) { if (digestCalculator != null) { return(VerifyDigest(resultDigest, key, GetSignature())); } if (content != null) { content.Write((Stream)(object)new SigOutputStream(signer)); } } else { byte[] encodedSignedAttributes = GetEncodedSignedAttributes(); signer.BlockUpdate(encodedSignedAttributes, 0, encodedSignedAttributes.Length); } return(signer.VerifySignature(GetSignature())); } catch (InvalidKeyException e3) { throw new CmsException("key not appropriate to signature in message.", e3); } catch (IOException val2) { IOException e4 = val2; throw new CmsException("can't process mime object to create signature.", (global::System.Exception)(object) e4); } catch (SignatureException ex) { throw new CmsException("invalid signature format in message: " + ((global::System.Exception)ex).get_Message(), ex); } }
public static ICipherParameters GenerateCipherParameters( string algorithm, char[] password, bool wrongPkcs12Zero, Asn1Encodable pbeParameters) { string mechanism = (string)algorithms[Platform.ToUpperInvariant(algorithm)]; byte[] keyBytes = null; byte[] salt = null; int iterationCount = 0; if (IsPkcs12(mechanism)) { Pkcs12PbeParams pbeParams = Pkcs12PbeParams.GetInstance(pbeParameters); salt = pbeParams.GetIV(); iterationCount = pbeParams.Iterations.IntValue; keyBytes = PbeParametersGenerator.Pkcs12PasswordToBytes(password, wrongPkcs12Zero); } else if (IsPkcs5Scheme2(mechanism)) { // See below } else { PbeParameter pbeParams = PbeParameter.GetInstance(pbeParameters); salt = pbeParams.GetSalt(); iterationCount = pbeParams.IterationCount.IntValue; keyBytes = PbeParametersGenerator.Pkcs5PasswordToBytes(password); } ICipherParameters parameters = null; if (IsPkcs5Scheme2(mechanism)) { PbeS2Parameters s2p = PbeS2Parameters.GetInstance(pbeParameters.ToAsn1Object()); AlgorithmIdentifier encScheme = s2p.EncryptionScheme; DerObjectIdentifier encOid = encScheme.Algorithm; Asn1Object encParams = encScheme.Parameters.ToAsn1Object(); // TODO What about s2p.KeyDerivationFunc.Algorithm? Pbkdf2Params pbeParams = Pbkdf2Params.GetInstance(s2p.KeyDerivationFunc.Parameters.ToAsn1Object()); byte[] iv; if (encOid.Equals(PkcsObjectIdentifiers.RC2Cbc)) // PKCS5.B.2.3 { RC2CbcParameter rc2Params = RC2CbcParameter.GetInstance(encParams); iv = rc2Params.GetIV(); } else { iv = Asn1OctetString.GetInstance(encParams).GetOctets(); } salt = pbeParams.GetSalt(); iterationCount = pbeParams.IterationCount.IntValue; keyBytes = PbeParametersGenerator.Pkcs5PasswordToBytes(password); int keyLength = pbeParams.KeyLength != null ? pbeParams.KeyLength.IntValue * 8 : GeneratorUtilities.GetDefaultKeySize(encOid); PbeParametersGenerator gen = MakePbeGenerator( (string)algorithmType[mechanism], null, keyBytes, salt, iterationCount); parameters = gen.GenerateDerivedParameters(encOid.Id, keyLength); if (iv != null) { // FIXME? OpenSSL weirdness with IV of zeros (for ECB keys?) if (Arrays.AreEqual(iv, new byte[iv.Length])) { //Console.Error.Write("***** IV all 0 (length " + iv.Length + ") *****"); } else { parameters = new ParametersWithIV(parameters, iv); } } } else if (Platform.StartsWith(mechanism, "PBEwithSHA-1")) { PbeParametersGenerator generator = MakePbeGenerator( (string)algorithmType[mechanism], new Sha1Digest(), keyBytes, salt, iterationCount); if (mechanism.Equals("PBEwithSHA-1and128bitAES-CBC-BC")) { parameters = generator.GenerateDerivedParameters("AES", 128, 128); } else if (mechanism.Equals("PBEwithSHA-1and192bitAES-CBC-BC")) { parameters = generator.GenerateDerivedParameters("AES", 192, 128); } else if (mechanism.Equals("PBEwithSHA-1and256bitAES-CBC-BC")) { parameters = generator.GenerateDerivedParameters("AES", 256, 128); } else if (mechanism.Equals("PBEwithSHA-1and128bitRC4")) { parameters = generator.GenerateDerivedParameters("RC4", 128); } else if (mechanism.Equals("PBEwithSHA-1and40bitRC4")) { parameters = generator.GenerateDerivedParameters("RC4", 40); } else if (mechanism.Equals("PBEwithSHA-1and3-keyDESEDE-CBC")) { parameters = generator.GenerateDerivedParameters("DESEDE", 192, 64); } else if (mechanism.Equals("PBEwithSHA-1and2-keyDESEDE-CBC")) { parameters = generator.GenerateDerivedParameters("DESEDE", 128, 64); } else if (mechanism.Equals("PBEwithSHA-1and128bitRC2-CBC")) { parameters = generator.GenerateDerivedParameters("RC2", 128, 64); } else if (mechanism.Equals("PBEwithSHA-1and40bitRC2-CBC")) { parameters = generator.GenerateDerivedParameters("RC2", 40, 64); } else if (mechanism.Equals("PBEwithSHA-1andDES-CBC")) { parameters = generator.GenerateDerivedParameters("DES", 64, 64); } else if (mechanism.Equals("PBEwithSHA-1andRC2-CBC")) { parameters = generator.GenerateDerivedParameters("RC2", 64, 64); } } else if (Platform.StartsWith(mechanism, "PBEwithSHA-256")) { PbeParametersGenerator generator = MakePbeGenerator( (string)algorithmType[mechanism], new Sha256Digest(), keyBytes, salt, iterationCount); if (mechanism.Equals("PBEwithSHA-256and128bitAES-CBC-BC")) { parameters = generator.GenerateDerivedParameters("AES", 128, 128); } else if (mechanism.Equals("PBEwithSHA-256and192bitAES-CBC-BC")) { parameters = generator.GenerateDerivedParameters("AES", 192, 128); } else if (mechanism.Equals("PBEwithSHA-256and256bitAES-CBC-BC")) { parameters = generator.GenerateDerivedParameters("AES", 256, 128); } } else if (Platform.StartsWith(mechanism, "PBEwithMD5")) { PbeParametersGenerator generator = MakePbeGenerator( (string)algorithmType[mechanism], new MD5Digest(), keyBytes, salt, iterationCount); if (mechanism.Equals("PBEwithMD5andDES-CBC")) { parameters = generator.GenerateDerivedParameters("DES", 64, 64); } else if (mechanism.Equals("PBEwithMD5andRC2-CBC")) { parameters = generator.GenerateDerivedParameters("RC2", 64, 64); } else if (mechanism.Equals("PBEwithMD5and128bitAES-CBC-OpenSSL")) { parameters = generator.GenerateDerivedParameters("AES", 128, 128); } else if (mechanism.Equals("PBEwithMD5and192bitAES-CBC-OpenSSL")) { parameters = generator.GenerateDerivedParameters("AES", 192, 128); } else if (mechanism.Equals("PBEwithMD5and256bitAES-CBC-OpenSSL")) { parameters = generator.GenerateDerivedParameters("AES", 256, 128); } } else if (Platform.StartsWith(mechanism, "PBEwithMD2")) { PbeParametersGenerator generator = MakePbeGenerator( (string)algorithmType[mechanism], new MD2Digest(), keyBytes, salt, iterationCount); if (mechanism.Equals("PBEwithMD2andDES-CBC")) { parameters = generator.GenerateDerivedParameters("DES", 64, 64); } else if (mechanism.Equals("PBEwithMD2andRC2-CBC")) { parameters = generator.GenerateDerivedParameters("RC2", 64, 64); } } else if (Platform.StartsWith(mechanism, "PBEwithHmac")) { string digestName = mechanism.Substring("PBEwithHmac".Length); IDigest digest = DigestUtilities.GetDigest(digestName); PbeParametersGenerator generator = MakePbeGenerator( (string)algorithmType[mechanism], digest, keyBytes, salt, iterationCount); int bitLen = digest.GetDigestSize() * 8; parameters = generator.GenerateDerivedMacParameters(bitLen); } Array.Clear(keyBytes, 0, keyBytes.Length); return(FixDesParity(mechanism, parameters)); }
public bool Match( // Certificate cert) X509Certificate x509Cert) { // if (!(cert is X509Certificate)) // { // return false; // } // // X509Certificate x509Cert = (X509Certificate)cert; try { if (holder.BaseCertificateID != null) { return(holder.BaseCertificateID.Serial.Value.Equals(x509Cert.SerialNumber) && MatchesDN(PrincipalUtilities.GetIssuerX509Principal(x509Cert), holder.BaseCertificateID.Issuer)); } if (holder.EntityName != null) { if (MatchesDN(PrincipalUtilities.GetSubjectX509Principal(x509Cert), holder.EntityName)) { return(true); } } if (holder.ObjectDigestInfo != null) { IDigest md = null; try { md = DigestUtilities.GetDigest(DigestAlgorithm); } catch (Exception) { return(false); } switch (DigestedObjectType) { case ObjectDigestInfo.PublicKey: { // TODO: DSA Dss-parms //byte[] b = x509Cert.GetPublicKey().getEncoded(); // TODO Is this the right way to encode? byte[] b = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo( x509Cert.GetPublicKey()).GetEncoded(); md.BlockUpdate(b, 0, b.Length); break; } case ObjectDigestInfo.PublicKeyCert: { byte[] b = x509Cert.GetEncoded(); md.BlockUpdate(b, 0, b.Length); break; } // TODO Default handler? } // TODO Shouldn't this be the other way around? if (!Arrays.AreEqual(DigestUtilities.DoFinal(md), GetObjectDigest())) { return(false); } } } catch (CertificateEncodingException) { return(false); } return(false); }
public override void PerformTest() { Asn1Sequence obj = (Asn1Sequence)Asn1Object.FromByteArray(pkcs12); Pfx bag = new Pfx(obj); ContentInfo info = bag.AuthSafe; MacData mData = bag.MacData; DigestInfo dInfo = mData.Mac; AlgorithmIdentifier algId = dInfo.AlgorithmID; byte[] salt = mData.GetSalt(); int itCount = mData.IterationCount.IntValue; byte[] octets = ((Asn1OctetString)info.Content).GetOctets(); AuthenticatedSafe authSafe = new AuthenticatedSafe( (Asn1Sequence)Asn1Object.FromByteArray(octets)); ContentInfo[] c = authSafe.GetContentInfo(); // // private key section // if (!c[0].ContentType.Equals(PkcsObjectIdentifiers.Data)) { Fail("Failed comparison data test"); } octets = ((Asn1OctetString)c[0].Content).GetOctets(); Asn1Sequence seq = (Asn1Sequence)Asn1Object.FromByteArray(octets); SafeBag b = new SafeBag((Asn1Sequence)seq[0]); if (!b.BagID.Equals(PkcsObjectIdentifiers.Pkcs8ShroudedKeyBag)) { Fail("Failed comparison shroudedKeyBag test"); } EncryptedPrivateKeyInfo encInfo = EncryptedPrivateKeyInfo.GetInstance(b.BagValue); encInfo = new EncryptedPrivateKeyInfo(encInfo.EncryptionAlgorithm, encInfo.GetEncryptedData()); b = new SafeBag(PkcsObjectIdentifiers.Pkcs8ShroudedKeyBag, encInfo.ToAsn1Object(), b.BagAttributes); byte[] encodedBytes = new DerSequence(b).GetEncoded(); c[0] = new ContentInfo(PkcsObjectIdentifiers.Data, new BerOctetString(encodedBytes)); // // certificates // if (!c[1].ContentType.Equals(PkcsObjectIdentifiers.EncryptedData)) { Fail("Failed comparison encryptedData test"); } EncryptedData eData = EncryptedData.GetInstance(c[1].Content); c[1] = new ContentInfo(PkcsObjectIdentifiers.EncryptedData, eData); // // create an octet stream to represent the BER encoding of authSafe // authSafe = new AuthenticatedSafe(c); info = new ContentInfo(PkcsObjectIdentifiers.Data, new BerOctetString(authSafe.GetEncoded())); mData = new MacData(new DigestInfo(algId, dInfo.GetDigest()), salt, itCount); bag = new Pfx(info, mData); // // comparison test // if (!Arrays.AreEqual(bag.GetEncoded(), pkcs12)) { Fail("Failed comparison test"); } }
internal override void Evaluate() { byte[] origK = parent.mK; byte[] origV = parent.mV; long origReseedCounter = parent.mReseedCounter; IEntropySource origEntropySource = parent.mEntropySource; try { byte[] personalization = Hex.Decode("404142434445464748494A4B4C4D4E4F505152535455565758595A5B5C5D5E5F606162636465666768696A6B6C6D6E6F70717273747576"); byte[] nonce = Hex.Decode("2021222324"); int entropyStrength = DrbgUtilities.GetMaxSecurityStrength(parent.mHMac); byte[][] expected = (byte[][])kats[algorithm.Name]; parent.init(parent.mHMac, parent.mSecurityStrength, new DrbgUtilities.KatEntropyProvider().Get(entropyStrength), personalization, nonce); byte[] output = new byte[expected[0].Length]; parent.Generate(output, null, true); if (!Arrays.AreEqual(expected[0], output)) { Fail("DRBG Block 1 KAT failure"); } output = new byte[expected[1].Length]; parent.Generate(output, null, true); if (!Arrays.AreEqual(expected[1], output)) { Fail("DRBG Block 2 KAT failure"); } try { parent.init(parent.mHMac, parent.mSecurityStrength, new DrbgUtilities.LyingEntropySource(entropyStrength), personalization, nonce); Fail("DRBG LyingEntropySource not detected in init"); } catch (InvalidOperationException e) { if (!e.Message.Equals("Insufficient entropy provided by entropy source")) { Fail("DRBG self test failed init entropy check"); } } try { parent.init(parent.mHMac, parent.mSecurityStrength, new DrbgUtilities.LyingEntropySource(20), personalization, nonce); Fail("DRBG insufficient EntropySource not detected"); } catch (ArgumentException e) { if (!e.Message.Equals("Not enough entropy for security strength required")) { Fail("DRBG self test failed init entropy check"); } } try { parent.mEntropySource = new DrbgUtilities.LyingEntropySource(entropyStrength); parent.Reseed(null); Fail("DRBG LyingEntropySource not detected in reseed"); } catch (InvalidOperationException e) { if (!e.Message.Equals("Insufficient entropy provided by entropy source")) { Fail("DRBG self test failed reseed entropy check"); } } try { parent.init(parent.mHMac, entropyStrength + 1, new DrbgUtilities.KatEntropyProvider().Get(entropyStrength), personalization, nonce); Fail("DRBG successful initialise with too high security strength"); } catch (ArgumentException e) { if (!e.Message.Equals("Requested security strength is not supported by the derivation function")) { Fail("DRBG self test failed init security strength check"); } } } finally { parent.mK = origK; parent.mV = origV; parent.mReseedCounter = origReseedCounter; parent.mEntropySource = origEntropySource; } }
internal override void Evaluate() { byte[] origK = parent.mK; byte[] origV = parent.mV; long origReseedCounter = parent.mReseedCounter; IEntropySource origEntropySource = parent.mEntropySource; try { byte[] additionalInput = Hex.Decode("404142434445464748494A4B4C4D4E4F505152535455565758595A5B5C5D5E5F606162636465666768696A6B6C6D6E6F70717273747576"); int entropyStrength = DrbgUtilities.GetMaxSecurityStrength(parent.mHMac); byte[][] expected = (byte[][])reseedKats[algorithm.Name]; byte[][] internalValues = (byte[][])reseedValues[algorithm.Name]; parent.mK = Arrays.Clone(internalValues[0]); parent.mV = Arrays.Clone(internalValues[1]); parent.mEntropySource = new DrbgUtilities.KatEntropyProvider().Get(entropyStrength); parent.Reseed(additionalInput); if (parent.mReseedCounter != 1) { Fail("DRBG reseedCounter failed to reset"); } byte[] output = new byte[expected[0].Length]; parent.Generate(output, null, false); if (!Arrays.AreEqual(expected[0], output)) { Fail("DRBG Block 1 reseed KAT failure"); } output = new byte[expected[1].Length]; parent.Generate(output, null, false); if (!Arrays.AreEqual(expected[1], output)) { Fail("DRBG Block 2 reseed KAT failure"); } try { parent.mEntropySource = new DrbgUtilities.LyingEntropySource(entropyStrength); parent.Reseed(null); Fail("DRBG LyingEntropySource not detected"); } catch (InvalidOperationException e) { if (!e.Message.Equals("Insufficient entropy provided by entropy source")) { Fail("DRBG self test failed reseed entropy check"); } } } finally { parent.mK = origK; parent.mV = origV; parent.mReseedCounter = origReseedCounter; parent.mEntropySource = origEntropySource; } }
public void Load( Stream input, char[] password) { if (input == null) { throw new ArgumentNullException("input"); } if (password == null) { throw new ArgumentNullException("password"); } Asn1Sequence obj = (Asn1Sequence)Asn1Object.FromStream(input); Pfx bag = new Pfx(obj); ContentInfo info = bag.AuthSafe; bool unmarkedKey = false; bool wrongPkcs12Zero = false; if (bag.MacData != null) // check the mac code { MacData mData = bag.MacData; DigestInfo dInfo = mData.Mac; AlgorithmIdentifier algId = dInfo.AlgorithmID; byte[] salt = mData.GetSalt(); int itCount = mData.IterationCount.IntValue; byte[] data = ((Asn1OctetString)info.Content).GetOctets(); byte[] mac = CalculatePbeMac(algId.ObjectID, salt, itCount, password, false, data); byte[] dig = dInfo.GetDigest(); if (!Arrays.AreEqual(mac, dig)) { if (password.Length > 0) { throw new IOException("PKCS12 key store MAC invalid - wrong password or corrupted file."); } // Try with incorrect zero length password mac = CalculatePbeMac(algId.ObjectID, salt, itCount, password, true, data); if (!Arrays.AreEqual(mac, dig)) { throw new IOException("PKCS12 key store MAC invalid - wrong password or corrupted file."); } wrongPkcs12Zero = true; } } keys.Clear(); localIds.Clear(); ArrayList chain = new ArrayList(); if (info.ContentType.Equals(PkcsObjectIdentifiers.Data)) { byte[] octs = ((Asn1OctetString)info.Content).GetOctets(); AuthenticatedSafe authSafe = new AuthenticatedSafe( (Asn1Sequence)Asn1OctetString.FromByteArray(octs)); ContentInfo[] cis = authSafe.GetContentInfo(); foreach (ContentInfo ci in cis) { DerObjectIdentifier oid = ci.ContentType; if (oid.Equals(PkcsObjectIdentifiers.Data)) { byte[] octets = ((Asn1OctetString)ci.Content).GetOctets(); Asn1Sequence seq = (Asn1Sequence)Asn1Object.FromByteArray(octets); foreach (Asn1Sequence subSeq in seq) { SafeBag b = new SafeBag(subSeq); if (b.BagID.Equals(PkcsObjectIdentifiers.Pkcs8ShroudedKeyBag)) { EncryptedPrivateKeyInfo eIn = EncryptedPrivateKeyInfo.GetInstance(b.BagValue); PrivateKeyInfo privInfo = PrivateKeyInfoFactory.CreatePrivateKeyInfo( password, wrongPkcs12Zero, eIn); AsymmetricKeyParameter privKey = PrivateKeyFactory.CreateKey(privInfo); // // set the attributes on the key // Hashtable attributes = new Hashtable(); AsymmetricKeyEntry pkcs12Key = new AsymmetricKeyEntry(privKey, attributes); string alias = null; Asn1OctetString localId = null; if (b.BagAttributes != null) { foreach (Asn1Sequence sq in b.BagAttributes) { DerObjectIdentifier aOid = (DerObjectIdentifier)sq[0]; Asn1Set attrSet = (Asn1Set)sq[1]; Asn1Encodable attr = null; if (attrSet.Count > 0) { // TODO We should be adding all attributes in the set attr = attrSet[0]; // TODO We might want to "merge" attribute sets with // the same OID - currently, differing values give an error if (attributes.ContainsKey(aOid.Id)) { // OK, but the value has to be the same if (!attributes[aOid.Id].Equals(attr)) { throw new IOException("attempt to add existing attribute with different value"); } } else { attributes.Add(aOid.Id, attr); } if (aOid.Equals(PkcsObjectIdentifiers.Pkcs9AtFriendlyName)) { alias = ((DerBmpString)attr).GetString(); // TODO Do these in a separate loop, just collect aliases here keys[alias] = pkcs12Key; } else if (aOid.Equals(PkcsObjectIdentifiers.Pkcs9AtLocalKeyID)) { localId = (Asn1OctetString)attr; } } } } if (localId != null) { byte[] hex = Hex.Encode(localId.GetOctets()); string name = Encoding.ASCII.GetString(hex, 0, hex.Length); if (alias == null) { keys[name] = pkcs12Key; } else { // TODO There may have been more than one alias localIds[alias] = name; } } else { unmarkedKey = true; keys["unmarked"] = pkcs12Key; } } else if (b.BagID.Equals(PkcsObjectIdentifiers.CertBag)) { chain.Add(b); } else { Console.WriteLine("extra " + b.BagID); Console.WriteLine("extra " + Asn1Dump.DumpAsString(b)); } } } else if (oid.Equals(PkcsObjectIdentifiers.EncryptedData)) { EncryptedData d = EncryptedData.GetInstance(ci.Content); byte[] octets = CryptPbeData(false, d.EncryptionAlgorithm, password, wrongPkcs12Zero, d.Content.GetOctets()); Asn1Sequence seq = (Asn1Sequence)Asn1Object.FromByteArray(octets); foreach (Asn1Sequence subSeq in seq) { SafeBag b = new SafeBag(subSeq); if (b.BagID.Equals(PkcsObjectIdentifiers.CertBag)) { chain.Add(b); } else if (b.BagID.Equals(PkcsObjectIdentifiers.Pkcs8ShroudedKeyBag)) { EncryptedPrivateKeyInfo eIn = EncryptedPrivateKeyInfo.GetInstance(b.BagValue); PrivateKeyInfo privInfo = PrivateKeyInfoFactory.CreatePrivateKeyInfo( password, wrongPkcs12Zero, eIn); AsymmetricKeyParameter privKey = PrivateKeyFactory.CreateKey(privInfo); // // set the attributes on the key // Hashtable attributes = new Hashtable(); AsymmetricKeyEntry pkcs12Key = new AsymmetricKeyEntry(privKey, attributes); string alias = null; Asn1OctetString localId = null; foreach (Asn1Sequence sq in b.BagAttributes) { DerObjectIdentifier aOid = (DerObjectIdentifier)sq[0]; Asn1Set attrSet = (Asn1Set)sq[1]; Asn1Encodable attr = null; if (attrSet.Count > 0) { // TODO We should be adding all attributes in the set attr = attrSet[0]; // TODO We might want to "merge" attribute sets with // the same OID - currently, differing values give an error if (attributes.ContainsKey(aOid.Id)) { // OK, but the value has to be the same if (!attributes[aOid.Id].Equals(attr)) { throw new IOException("attempt to add existing attribute with different value"); } } else { attributes.Add(aOid.Id, attr); } if (aOid.Equals(PkcsObjectIdentifiers.Pkcs9AtFriendlyName)) { alias = ((DerBmpString)attr).GetString(); // TODO Do these in a separate loop, just collect aliases here keys[alias] = pkcs12Key; } else if (aOid.Equals(PkcsObjectIdentifiers.Pkcs9AtLocalKeyID)) { localId = (Asn1OctetString)attr; } } } // TODO Should we be checking localIds != null here // as for PkcsObjectIdentifiers.Data version above? byte[] hex = Hex.Encode(localId.GetOctets()); string name = Encoding.ASCII.GetString(hex, 0, hex.Length); if (alias == null) { keys[name] = pkcs12Key; } else { // TODO There may have been more than one alias localIds[alias] = name; } } else if (b.BagID.Equals(PkcsObjectIdentifiers.KeyBag)) { PrivateKeyInfo privKeyInfo = PrivateKeyInfo.GetInstance(b.BagValue); AsymmetricKeyParameter privKey = PrivateKeyFactory.CreateKey(privKeyInfo); // // set the attributes on the key // string alias = null; Asn1OctetString localId = null; Hashtable attributes = new Hashtable(); AsymmetricKeyEntry pkcs12Key = new AsymmetricKeyEntry(privKey, attributes); foreach (Asn1Sequence sq in b.BagAttributes) { DerObjectIdentifier aOid = (DerObjectIdentifier)sq[0]; Asn1Set attrSet = (Asn1Set)sq[1]; Asn1Encodable attr = null; if (attrSet.Count > 0) { // TODO We should be adding all attributes in the set attr = attrSet[0]; // TODO We might want to "merge" attribute sets with // the same OID - currently, differing values give an error if (attributes.ContainsKey(aOid.Id)) { // OK, but the value has to be the same if (!attributes[aOid.Id].Equals(attr)) { throw new IOException("attempt to add existing attribute with different value"); } } else { attributes.Add(aOid.Id, attr); } if (aOid.Equals(PkcsObjectIdentifiers.Pkcs9AtFriendlyName)) { alias = ((DerBmpString)attr).GetString(); // TODO Do these in a separate loop, just collect aliases here keys[alias] = pkcs12Key; } else if (aOid.Equals(PkcsObjectIdentifiers.Pkcs9AtLocalKeyID)) { localId = (Asn1OctetString)attr; } } } // TODO Should we be checking localIds != null here // as for PkcsObjectIdentifiers.Data version above? byte[] hex = Hex.Encode(localId.GetOctets()); string name = Encoding.ASCII.GetString(hex, 0, hex.Length); if (alias == null) { keys[name] = pkcs12Key; } else { // TODO There may have been more than one alias localIds[alias] = name; } } else { Console.WriteLine("extra " + b.BagID); Console.WriteLine("extra " + Asn1Dump.DumpAsString(b)); } } } else { Console.WriteLine("extra " + oid); Console.WriteLine("extra " + Asn1Dump.DumpAsString(ci.Content)); } } } certs.Clear(); chainCerts.Clear(); keyCerts.Clear(); foreach (SafeBag b in chain) { CertBag cb = new CertBag((Asn1Sequence)b.BagValue); byte[] octets = ((Asn1OctetString)cb.CertValue).GetOctets(); X509Certificate cert = new X509CertificateParser().ReadCertificate(octets); // // set the attributes // Hashtable attributes = new Hashtable(); Asn1OctetString localId = null; string alias = null; if (b.BagAttributes != null) { foreach (Asn1Sequence sq in b.BagAttributes) { DerObjectIdentifier aOid = (DerObjectIdentifier)sq[0]; Asn1Set attrSet = (Asn1Set)sq[1]; if (attrSet.Count > 0) { // TODO We should be adding all attributes in the set Asn1Encodable attr = attrSet[0]; // TODO We might want to "merge" attribute sets with // the same OID - currently, differing values give an error if (attributes.ContainsKey(aOid.Id)) { // OK, but the value has to be the same if (!attributes[aOid.Id].Equals(attr)) { throw new IOException("attempt to add existing attribute with different value"); } } else { attributes.Add(aOid.Id, attr); } if (aOid.Equals(PkcsObjectIdentifiers.Pkcs9AtFriendlyName)) { alias = ((DerBmpString)attr).GetString(); } else if (aOid.Equals(PkcsObjectIdentifiers.Pkcs9AtLocalKeyID)) { localId = (Asn1OctetString)attr; } } } } CertId certId = new CertId(cert.GetPublicKey()); X509CertificateEntry pkcs12Cert = new X509CertificateEntry(cert, attributes); chainCerts[certId] = pkcs12Cert; if (unmarkedKey) { if (keyCerts.Count == 0) { byte[] hex = Hex.Encode(certId.Id); string name = Encoding.ASCII.GetString(hex, 0, hex.Length); keyCerts[name] = pkcs12Cert; object temp = keys["unmarked"]; keys.Remove("unmarked"); keys[name] = temp; } } else { if (localId != null) { byte[] hex = Hex.Encode(localId.GetOctets()); string name = Encoding.ASCII.GetString(hex, 0, hex.Length); keyCerts[name] = pkcs12Cert; } if (alias != null) { // TODO There may have been more than one alias certs[alias] = pkcs12Cert; } } } }
protected bool Equals( DHValidationParameters other) { return(counter == other.counter && Arrays.AreEqual(this.seed, other.seed)); }
public virtual bool Match( object obj) { X509Crl c = obj as X509Crl; if (c == null) { return(false); } if (dateAndTime != null) { DateTime dt = dateAndTime.Value; DateTime tu = c.ThisUpdate; DateTimeObject nu = c.NextUpdate; if (dt.CompareTo(tu) < 0 || nu == null || dt.CompareTo(nu.Value) >= 0) { return(false); } } if (issuers != null) { X509Name i = c.IssuerDN; bool found = false; foreach (X509Name issuer in issuers) { if (issuer.Equivalent(i, true)) { found = true; break; } } if (!found) { return(false); } } if (maxCrlNumber != null || minCrlNumber != null) { Asn1OctetString extVal = c.GetExtensionValue(X509Extensions.CrlNumber); if (extVal == null) { return(false); } BigInteger cn = CrlNumber.GetInstance( X509ExtensionUtilities.FromExtensionValue(extVal)).PositiveValue; if (maxCrlNumber != null && cn.CompareTo(maxCrlNumber) > 0) { return(false); } if (minCrlNumber != null && cn.CompareTo(minCrlNumber) < 0) { return(false); } } DerInteger dci = null; try { Asn1OctetString bytes = c.GetExtensionValue(X509Extensions.DeltaCrlIndicator); if (bytes != null) { dci = DerInteger.GetInstance(X509ExtensionUtilities.FromExtensionValue(bytes)); } } catch (Exception) { return(false); } if (dci == null) { if (DeltaCrlIndicatorEnabled) { return(false); } } else { if (CompleteCrlEnabled) { return(false); } if (maxBaseCrlNumber != null && dci.PositiveValue.CompareTo(maxBaseCrlNumber) > 0) { return(false); } } if (issuingDistributionPointEnabled) { Asn1OctetString idp = c.GetExtensionValue(X509Extensions.IssuingDistributionPoint); if (issuingDistributionPoint == null) { if (idp != null) { return(false); } } else { if (!Arrays.AreEqual(idp.GetOctets(), issuingDistributionPoint)) { return(false); } } } return(true); }
public void TestGetPartitionId() { Parameters p = Parameters.GetKnnDefaultParameters(); p.SetParameterByKey(Parameters.KEY.DISTANCE_METHOD, DistanceMethod.RawOverlap); KNNClassifier classifier = InitClassifier(p); int dimensionality = 40; var a = new double[] { 1, 3, 7, 11, 13, 17, 19, 23, 29 }; var b = new double[] { 2, 4, 8, 12, 14, 18, 20, 28, 30 }; var c = new double[] { 1, 2, 3, 14, 16, 19, 22, 24, 33 }; var d = new double[] { 2, 4, 8, 12, 14, 19, 22, 24, 33 }; var e = new double[] { 1, 3, 7, 12, 14, 19, 22, 24, 33 }; var denseA = new double[dimensionality]; foreach (int index in a) { denseA[index] = 1; } classifier.Learn(a, 0, isSparse: dimensionality, partitionId: 433); classifier.Learn(b, 1, isSparse: dimensionality, partitionId: 213); classifier.Learn(c, 1, isSparse: dimensionality, partitionId: null); classifier.Learn(d, 1, isSparse: dimensionality, partitionId: 433); Assert.AreEqual(433, classifier.GetPartitionId(0)); Assert.AreEqual(213, classifier.GetPartitionId(1)); Assert.AreEqual(null, classifier.GetPartitionId(2)); Assert.AreEqual(433, classifier.GetPartitionId(3)); var result = classifier.Infer(denseA, partitionId: 213); var category = result.Get(0); Assert.AreEqual(0, category); // Test with patternId not in classifier result = classifier.Infer(denseA, partitionId: 666); category = result.Get(0); Assert.AreEqual(0, category); // Partition Ids should be maintained after inference Assert.AreEqual(433, classifier.GetPartitionId(0)); Assert.AreEqual(213, classifier.GetPartitionId(1)); Assert.AreEqual(null, classifier.GetPartitionId(2)); Assert.AreEqual(433, classifier.GetPartitionId(3)); // Should return exceptions if we go out of bounds try { classifier.GetPartitionId(4); Assert.Fail(); } catch (IndexOutOfRangeException) { } catch { Assert.Fail(); } try { classifier.GetPartitionId(-1); Assert.Fail(); } catch (IndexOutOfRangeException) { } catch { Assert.Fail(); } // Learn again classifier.Learn(e, 4, isSparse: dimensionality, partitionId: 413); Assert.AreEqual(413, classifier.GetPartitionId(4)); // Test getPatternIndicesWithPartitionId Assert.IsTrue(Arrays.AreEqual(new[] { 0, 3 }, classifier.GetPatternIndicesWithPartitionId(433))); Assert.IsTrue(Arrays.AreEqual(new int[0], classifier.GetPatternIndicesWithPartitionId(666))); Assert.IsTrue(Arrays.AreEqual(new[] { 4 }, classifier.GetPatternIndicesWithPartitionId(413))); Assert.AreEqual(3, classifier.GetNumPartitionIds()); // Check that the full set of partition ids is what we expect Assert.IsTrue(Arrays.AreEqual(new[] { 433, 213, int.MaxValue, 433, 413 }, classifier.GetPartitionIdPerPattern())); Assert.IsTrue(Arrays.AreEqual(new[] { 433, 213, 413 }, classifier.GetPartitionIdList())); // Remove two rows - all indices shift down Assert.AreEqual(2, classifier.RemoveRows(new[] { 0, 2 })); Assert.IsTrue(Arrays.AreEqual(new[] { 1 }, classifier.GetPatternIndicesWithPartitionId(433))); Assert.IsTrue(Arrays.AreEqual(new[] { 2 }, classifier.GetPatternIndicesWithPartitionId(413))); // Remove another row and check number of partitions have decreased Assert.AreEqual(1, classifier.RemoveRows(new[] { 0 })); Assert.AreEqual(2, classifier.GetNumPartitionIds()); // Check that the full set of partition ids is what we expect Assert.IsTrue(Arrays.AreEqual(new[] { 433, 413 }, classifier.GetPartitionIdPerPattern())); Assert.IsTrue(Arrays.AreEqual(new[] { 433, 413 }, classifier.GetPartitionIdList())); }
public ITestResult Perform() { IDigest digest = new TigerDigest(); byte[] resBuf = new byte[digest.GetDigestSize()]; for (int i = 0; i < messages.Length; i++) { byte[] m = Encoding.ASCII.GetBytes(messages[i]); digest.BlockUpdate(m, 0, m.Length); digest.DoFinal(resBuf, 0); if (!Arrays.AreEqual(resBuf, Hex.Decode(digests[i]))) { return(new SimpleTestResult(false, Name + ": Vector " + i + " failed got " + Hex.ToHexString(resBuf))); } } // // test 2 // byte[] mm = Encoding.ASCII.GetBytes(messages[messages.Length - 1]); digest.BlockUpdate(mm, 0, mm.Length / 2); // clone the IDigest IDigest d = new TigerDigest((TigerDigest)digest); digest.BlockUpdate(mm, mm.Length / 2, mm.Length - mm.Length / 2); digest.DoFinal(resBuf, 0); if (!Arrays.AreEqual(resBuf, Hex.Decode(digests[digests.Length - 1]))) { return(new SimpleTestResult(false, "Tiger failing clone test" + SimpleTest.NewLine + " expected: " + digests[digests.Length - 1] + SimpleTest.NewLine + " got : " + Hex.ToHexString(resBuf))); } d.BlockUpdate(mm, mm.Length / 2, mm.Length - mm.Length / 2); d.DoFinal(resBuf, 0); if (!Arrays.AreEqual(resBuf, Hex.Decode(digests[digests.Length - 1]))) { return(new SimpleTestResult(false, "Tiger failing clone test - part 2" + SimpleTest.NewLine + " expected: " + digests[digests.Length - 1] + SimpleTest.NewLine + " got : " + Hex.ToHexString(resBuf))); } for (int i = 0; i < 65536; i++) { digest.Update((byte)(i & 0xff)); } digest.DoFinal(resBuf, 0); if (!Arrays.AreEqual(resBuf, Hex.Decode(hash64k))) { return(new SimpleTestResult(false, Name + ": Million a's failed")); } return(new SimpleTestResult(true, Name + ": Okay")); }
protected bool Equals(ECDomainParameters other) { return(curve.Equals(other.curve) && g.Equals(other.g) && n.Equals(other.n) && h.Equals(other.h) && Arrays.AreEqual(seed, other.seed)); }
public override void PerformTest() { TupleHash tHash = new TupleHash(128, new byte[0]); tHash.BlockUpdate(Hex.Decode("000102"), 0, 3); tHash.BlockUpdate(Hex.Decode("101112131415"), 0, 6); byte[] res = new byte[tHash.GetDigestSize()]; tHash.DoFinal(res, 0); IsTrue("oops!", Arrays.AreEqual(Hex.Decode("C5 D8 78 6C 1A FB 9B 82 11 1A B3 4B 65 B2 C0 04 8F A6 4E 6D 48 E2 63 26 4C E1 70 7D 3F FC 8E D1"), res)); tHash = new TupleHash(128, Strings.ToByteArray("My Tuple App")); tHash.BlockUpdate(Hex.Decode("000102"), 0, 3); tHash.BlockUpdate(Hex.Decode("101112131415"), 0, 6); tHash.DoFinal(res, 0); IsTrue("oops!", Arrays.AreEqual(Hex.Decode("75 CD B2 0F F4 DB 11 54 E8 41 D7 58 E2 41 60 C5 4B AE 86 EB 8C 13 E7 F5 F4 0E B3 55 88 E9 6D FB"), res)); tHash.BlockUpdate(Hex.Decode("000102"), 0, 3); tHash.BlockUpdate(Hex.Decode("101112131415"), 0, 6); tHash.BlockUpdate(Hex.Decode("202122232425262728"), 0, 9); tHash.DoFinal(res, 0); IsTrue("oops!", Arrays.AreEqual(Hex.Decode("E6 0F 20 2C 89 A2 63 1E DA 8D 4C 58 8C A5 FD 07 F3 9E 51 51 99 8D EC CF 97 3A DB 38 04 BB 6E 84"), res)); tHash = new TupleHash(256, new byte[0]); tHash.BlockUpdate(Hex.Decode("000102"), 0, 3); tHash.BlockUpdate(Hex.Decode("101112131415"), 0, 6); res = new byte[tHash.GetDigestSize()]; tHash.DoFinal(res, 0); IsTrue("oops!", Arrays.AreEqual(Hex.Decode("CF B7 05 8C AC A5 E6 68 F8 1A 12 A2 0A 21 95 CE 97 A9 25 F1 DB A3 E7 44 9A 56 F8 22 01 EC 60 73 11 AC 26 96 B1 AB 5E A2 35 2D F1 42 3B DE 7B D4 BB 78 C9 AE D1 A8 53 C7 86 72 F9 EB 23 BB E1 94"), res)); tHash = new TupleHash(256, Strings.ToByteArray("My Tuple App")); tHash.BlockUpdate(Hex.Decode("000102"), 0, 3); tHash.BlockUpdate(Hex.Decode("101112131415"), 0, 6); tHash.DoFinal(res, 0); IsTrue("oops!", Arrays.AreEqual(Hex.Decode("14 7C 21 91 D5 ED 7E FD 98 DB D9 6D 7A B5 A1 16 92 57 6F 5F E2 A5 06 5F 3E 33 DE 6B BA 9F 3A A1 C4 E9 A0 68 A2 89 C6 1C 95 AA B3 0A EE 1E 41 0B 0B 60 7D E3 62 0E 24 A4 E3 BF 98 52 A1 D4 36 7E"), res)); tHash.BlockUpdate(Hex.Decode("000102"), 0, 3); tHash.BlockUpdate(Hex.Decode("101112131415"), 0, 6); tHash.BlockUpdate(Hex.Decode("202122232425262728"), 0, 9); tHash.DoFinal(res, 0); IsTrue("oops!", Arrays.AreEqual(Hex.Decode("45 00 0B E6 3F 9B 6B FD 89 F5 47 17 67 0F 69 A9 BC 76 35 91 A4 F0 5C 50 D6 88 91 A7 44 BC C6 E7 D6 D5 B5 E8 2C 01 8D A9 99 ED 35 B0 BB 49 C9 67 8E 52 6A BD 8E 85 C1 3E D2 54 02 1D B9 E7 90 CE"), res)); tHash = new TupleHash(128, Strings.ToByteArray("My Tuple App")); tHash.BlockUpdate(Hex.Decode("000102"), 0, 3); tHash.BlockUpdate(Hex.Decode("101112131415"), 0, 6); tHash.BlockUpdate(Hex.Decode("202122232425262728"), 0, 9); res = new byte[32]; tHash.DoOutput(res, 0, res.Length); IsTrue("oops!", !Arrays.AreEqual(Hex.Decode("E6 0F 20 2C 89 A2 63 1E DA 8D 4C 58 8C A5 FD 07 F3 9E 51 51 99 8D EC CF 97 3A DB 38 04 BB 6E 84"), res)); IsTrue("oops!", Arrays.AreEqual(Hex.Decode("900fe16cad098d28e74d632ed852f99daab7f7df4d99e775657885b4bf76d6f8"), res)); tHash = new TupleHash(256, Strings.ToByteArray("My Tuple App")); tHash.BlockUpdate(Hex.Decode("000102"), 0, 3); tHash.BlockUpdate(Hex.Decode("101112131415"), 0, 6); tHash.BlockUpdate(Hex.Decode("202122232425262728"), 0, 9); res = new byte[64]; tHash.DoOutput(res, 0, res.Length); IsTrue("oops!", !Arrays.AreEqual(Hex.Decode("45 00 0B E6 3F 9B 6B FD 89 F5 47 17 67 0F 69 A9 BC 76 35 91 A4 F0 5C 50 D6 88 91 A7 44 BC C6 E7 D6 D5 B5 E8 2C 01 8D A9 99 ED 35 B0 BB 49 C9 67 8E 52 6A BD 8E 85 C1 3E D2 54 02 1D B9 E7 90 CE"), res)); IsTrue("oops!", Arrays.AreEqual(Hex.Decode("0c59b11464f2336c34663ed51b2b950bec743610856f36c28d1d088d8a2446284dd09830a6a178dc752376199fae935d86cfdee5913d4922dfd369b66a53c897"), res)); }
private bool DoVerify( AsymmetricKeyParameter key) { string digestName = Helper.GetDigestAlgName(this.DigestAlgOid); IDigest digest = Helper.GetDigestInstance(digestName); DerObjectIdentifier sigAlgOid = this.encryptionAlgorithm.Algorithm; Asn1Encodable sigParams = this.encryptionAlgorithm.Parameters; ISigner sig; if (sigAlgOid.Equals(Asn1.Pkcs.PkcsObjectIdentifiers.IdRsassaPss)) { // RFC 4056 2.2 // When the id-RSASSA-PSS algorithm identifier is used for a signature, // the AlgorithmIdentifier parameters field MUST contain RSASSA-PSS-params. if (sigParams == null) { throw new CmsException("RSASSA-PSS signature must specify algorithm parameters"); } try { // TODO Provide abstract configuration mechanism // (via alternate SignerUtilities.GetSigner method taking ASN.1 params) Asn1.Pkcs.RsassaPssParameters pss = Asn1.Pkcs.RsassaPssParameters.GetInstance( sigParams.ToAsn1Object()); if (!pss.HashAlgorithm.Algorithm.Equals(this.digestAlgorithm.Algorithm)) { throw new CmsException("RSASSA-PSS signature parameters specified incorrect hash algorithm"); } if (!pss.MaskGenAlgorithm.Algorithm.Equals(Asn1.Pkcs.PkcsObjectIdentifiers.IdMgf1)) { throw new CmsException("RSASSA-PSS signature parameters specified unknown MGF"); } IDigest pssDigest = DigestUtilities.GetDigest(pss.HashAlgorithm.Algorithm); int saltLength = pss.SaltLength.Value.IntValue; byte trailerField = (byte)pss.TrailerField.Value.IntValue; // RFC 4055 3.1 // The value MUST be 1, which represents the trailer field with hexadecimal value 0xBC if (trailerField != 1) { throw new CmsException("RSASSA-PSS signature parameters must have trailerField of 1"); } sig = new PssSigner(new RsaBlindedEngine(), pssDigest, saltLength); } catch (Exception e) { throw new CmsException("failed to set RSASSA-PSS signature parameters", e); } } else { // TODO Probably too strong a check at the moment // if (sigParams != null) // throw new CmsException("unrecognised signature parameters provided"); string signatureName = digestName + "with" + Helper.GetEncryptionAlgName(this.EncryptionAlgOid); sig = Helper.GetSignatureInstance(signatureName); //sig = Helper.GetSignatureInstance(this.EncryptionAlgOid); //sig = SignerUtilities.GetSigner(sigAlgOid); } try { if (digestCalculator != null) { resultDigest = digestCalculator.GetDigest(); } else { if (content != null) { content.Write(new DigOutputStream(digest)); } else if (signedAttributeSet == null) { // TODO Get rid of this exception and just treat content==null as empty not missing? throw new CmsException("data not encapsulated in signature - use detached constructor."); } resultDigest = DigestUtilities.DoFinal(digest); } } catch (IOException e) { throw new CmsException("can't process mime object to create signature.", e); } // RFC 3852 11.1 Check the content-type attribute is correct { Asn1Object validContentType = GetSingleValuedSignedAttribute( CmsAttributes.ContentType, "content-type"); if (validContentType == null) { if (!isCounterSignature && signedAttributeSet != null) { throw new CmsException("The content-type attribute type MUST be present whenever signed attributes are present in signed-data"); } } else { if (isCounterSignature) { throw new CmsException("[For counter signatures,] the signedAttributes field MUST NOT contain a content-type attribute"); } if (!(validContentType is DerObjectIdentifier)) { throw new CmsException("content-type attribute value not of ASN.1 type 'OBJECT IDENTIFIER'"); } DerObjectIdentifier signedContentType = (DerObjectIdentifier)validContentType; if (!signedContentType.Equals(contentType)) { throw new CmsException("content-type attribute value does not match eContentType"); } } } // RFC 3852 11.2 Check the message-digest attribute is correct { Asn1Object validMessageDigest = GetSingleValuedSignedAttribute( CmsAttributes.MessageDigest, "message-digest"); if (validMessageDigest == null) { if (signedAttributeSet != null) { throw new CmsException("the message-digest signed attribute type MUST be present when there are any signed attributes present"); } } else { if (!(validMessageDigest is Asn1OctetString)) { throw new CmsException("message-digest attribute value not of ASN.1 type 'OCTET STRING'"); } Asn1OctetString signedMessageDigest = (Asn1OctetString)validMessageDigest; if (!Arrays.AreEqual(resultDigest, signedMessageDigest.GetOctets())) { throw new CmsException("message-digest attribute value does not match calculated value"); } } } // RFC 3852 11.4 Validate countersignature attribute(s) { Asn1.Cms.AttributeTable signedAttrTable = this.SignedAttributes; if (signedAttrTable != null && signedAttrTable.GetAll(CmsAttributes.CounterSignature).Count > 0) { throw new CmsException("A countersignature attribute MUST NOT be a signed attribute"); } Asn1.Cms.AttributeTable unsignedAttrTable = this.UnsignedAttributes; if (unsignedAttrTable != null) { foreach (Asn1.Cms.Attribute csAttr in unsignedAttrTable.GetAll(CmsAttributes.CounterSignature)) { if (csAttr.AttrValues.Count < 1) { throw new CmsException("A countersignature attribute MUST contain at least one AttributeValue"); } // Note: We don't recursively validate the countersignature value } } } try { sig.Init(false, key); if (signedAttributeSet == null) { if (digestCalculator != null) { // need to decrypt signature and check message bytes return(VerifyDigest(resultDigest, key, this.GetSignature())); } else if (content != null) { // TODO Use raw signature of the hash value instead content.Write(new SigOutputStream(sig)); } } else { byte[] tmp = this.GetEncodedSignedAttributes(); sig.BlockUpdate(tmp, 0, tmp.Length); } return(sig.VerifySignature(this.GetSignature())); } catch (InvalidKeyException e) { throw new CmsException("key not appropriate to signature in message.", e); } catch (IOException e) { throw new CmsException("can't process mime object to create signature.", e); } catch (SignatureException e) { throw new CmsException("invalid signature format in message: " + e.Message, e); } }
/// <summary> return true if the signature represents a ISO9796-2 signature /// for the passed in message. /// </summary> public virtual bool VerifySignature( byte[] signature) { // // calculate H(m2) // byte[] m2Hash = new byte[hLen]; digest.DoFinal(m2Hash, 0); byte[] block; int tLength; int mStart = 0; if (preSig == null) { try { UpdateWithRecoveredMessage(signature); } catch (Exception) { return(false); } } else { if (!Arrays.AreEqual(preSig, signature)) { throw new InvalidOperationException("UpdateWithRecoveredMessage called on different signature"); } } block = preBlock; mStart = preMStart; tLength = preTLength; preSig = null; preBlock = null; // // check the hashes // byte[] C = new byte[8]; LtoOSP(recoveredMessage.Length * 8, C); digest.BlockUpdate(C, 0, C.Length); if (recoveredMessage.Length != 0) { digest.BlockUpdate(recoveredMessage, 0, recoveredMessage.Length); } digest.BlockUpdate(m2Hash, 0, m2Hash.Length); // Update for the salt if (standardSalt != null) { digest.BlockUpdate(standardSalt, 0, standardSalt.Length); } else { digest.BlockUpdate(block, mStart + recoveredMessage.Length, saltLength); } byte[] hash = new byte[digest.GetDigestSize()]; digest.DoFinal(hash, 0); int off = block.Length - tLength - hash.Length; bool isOkay = true; for (int i = 0; i != hash.Length; i++) { if (hash[i] != block[off + i]) { isOkay = false; } } ClearBlock(block); ClearBlock(hash); if (!isOkay) { fullMessage = false; messageLength = 0; ClearBlock(recoveredMessage); return(false); } // // if they've input a message check what we've recovered against // what was input. // if (messageLength != 0) { if (!IsSameAs(mBuf, recoveredMessage)) { messageLength = 0; ClearBlock(mBuf); return(false); } } messageLength = 0; ClearBlock(mBuf); return(true); }
public virtual ITestResult Perform() { KeyParameter key = new KeyParameter(keyBytes); IBlockCipher cipher = new DesEngine(); IMac mac = new CbcBlockCipherMac(cipher); // // standard DAC - zero IV // mac.Init(key); mac.BlockUpdate(input1, 0, input1.Length); byte[] outBytes = new byte[4]; mac.DoFinal(outBytes, 0); if (!Arrays.AreEqual(outBytes, output1)) { return(new SimpleTestResult(false, Name + ": Failed - expected " + Hex.ToHexString(output1) + " got " + Hex.ToHexString(outBytes))); } // // mac with IV. // ParametersWithIV param = new ParametersWithIV(key, ivBytes); mac.Init(param); mac.BlockUpdate(input1, 0, input1.Length); outBytes = new byte[4]; mac.DoFinal(outBytes, 0); if (!Arrays.AreEqual(outBytes, output2)) { return(new SimpleTestResult(false, Name + ": Failed - expected " + Hex.ToHexString(output2) + " got " + Hex.ToHexString(outBytes))); } // // CFB mac with IV - 8 bit CFB mode // param = new ParametersWithIV(key, ivBytes); mac = new CfbBlockCipherMac(cipher); mac.Init(param); mac.BlockUpdate(input1, 0, input1.Length); outBytes = new byte[4]; mac.DoFinal(outBytes, 0); if (!Arrays.AreEqual(outBytes, output3)) { return(new SimpleTestResult(false, Name + ": Failed - expected " + Hex.ToHexString(output3) + " got " + Hex.ToHexString(outBytes))); } // // word aligned data - zero IV // mac.Init(key); mac.BlockUpdate(input2, 0, input2.Length); outBytes = new byte[4]; mac.DoFinal(outBytes, 0); if (!Arrays.AreEqual(outBytes, output4)) { return(new SimpleTestResult(false, Name + ": Failed - expected " + Hex.ToHexString(output4) + " got " + Hex.ToHexString(outBytes))); } // // word aligned data - zero IV - CBC padding // mac = new CbcBlockCipherMac(cipher, new Pkcs7Padding()); mac.Init(key); mac.BlockUpdate(input2, 0, input2.Length); outBytes = new byte[4]; mac.DoFinal(outBytes, 0); if (!Arrays.AreEqual(outBytes, output5)) { return(new SimpleTestResult(false, Name + ": Failed - expected " + Hex.ToHexString(output5) + " got " + Hex.ToHexString(outBytes))); } // // non-word aligned data - zero IV - CBC padding // mac.Reset(); mac.BlockUpdate(input1, 0, input1.Length); outBytes = new byte[4]; mac.DoFinal(outBytes, 0); if (!Arrays.AreEqual(outBytes, output6)) { return(new SimpleTestResult(false, Name + ": Failed - expected " + Hex.ToHexString(output6) + " got " + Hex.ToHexString(outBytes))); } // // non-word aligned data - zero IV - CBC padding // mac.Init(key); mac.BlockUpdate(input1, 0, input1.Length); outBytes = new byte[4]; mac.DoFinal(outBytes, 0); if (!Arrays.AreEqual(outBytes, output6)) { return(new SimpleTestResult(false, Name + ": Failed - expected " + Hex.ToHexString(output6) + " got " + Hex.ToHexString(outBytes))); } return(new SimpleTestResult(true, Name + ": Okay")); }
public virtual bool Equals(F2mFieldElement other) => ((((this.m == other.m) && (this.representation == other.representation)) && Arrays.AreEqual(this.ks, other.ks)) && this.x.Equals(other.x));
protected virtual void ReceiveServerHelloMessage(MemoryStream buf) { { ProtocolVersion server_version = TlsUtilities.ReadVersion(buf); if (server_version.IsDtls) { throw new TlsFatalAlert(AlertDescription.illegal_parameter); } // Check that this matches what the server is Sending in the record layer if (!server_version.Equals(this.mRecordStream.ReadVersion)) { throw new TlsFatalAlert(AlertDescription.illegal_parameter); } ProtocolVersion client_version = Context.ClientVersion; if (!server_version.IsEqualOrEarlierVersionOf(client_version)) { throw new TlsFatalAlert(AlertDescription.illegal_parameter); } this.mRecordStream.SetWriteVersion(server_version); ContextAdmin.SetServerVersion(server_version); this.mTlsClient.NotifyServerVersion(server_version); } /* * Read the server random */ this.mSecurityParameters.serverRandom = TlsUtilities.ReadFully(32, buf); this.mSelectedSessionID = TlsUtilities.ReadOpaque8(buf); if (this.mSelectedSessionID.Length > 32) { throw new TlsFatalAlert(AlertDescription.illegal_parameter); } this.mTlsClient.NotifySessionID(this.mSelectedSessionID); this.mResumedSession = this.mSelectedSessionID.Length > 0 && this.mTlsSession != null && Arrays.AreEqual(this.mSelectedSessionID, this.mTlsSession.SessionID); /* * Find out which CipherSuite the server has chosen and check that it was one of the offered * ones, and is a valid selection for the negotiated version. */ int selectedCipherSuite = TlsUtilities.ReadUint16(buf); if (!Arrays.Contains(this.mOfferedCipherSuites, selectedCipherSuite) || selectedCipherSuite == CipherSuite.TLS_NULL_WITH_NULL_NULL || CipherSuite.IsScsv(selectedCipherSuite) || !TlsUtilities.IsValidCipherSuiteForVersion(selectedCipherSuite, Context.ServerVersion)) { throw new TlsFatalAlert(AlertDescription.illegal_parameter); } this.mTlsClient.NotifySelectedCipherSuite(selectedCipherSuite); /* * Find out which CompressionMethod the server has chosen and check that it was one of the * offered ones. */ byte selectedCompressionMethod = TlsUtilities.ReadUint8(buf); if (!Arrays.Contains(this.mOfferedCompressionMethods, selectedCompressionMethod)) { throw new TlsFatalAlert(AlertDescription.illegal_parameter); } this.mTlsClient.NotifySelectedCompressionMethod(selectedCompressionMethod); /* * RFC 3546 2.2 The extended server hello message format MAY be sent in place of the server * hello message when the client has requested extended functionality via the extended * client hello message specified in Section 2.1. ... Note that the extended server hello * message is only sent in response to an extended client hello message. This prevents the * possibility that the extended server hello message could "break" existing TLS 1.0 * clients. */ this.mServerExtensions = ReadExtensions(buf); /* * RFC 7627 4. Clients and servers SHOULD NOT accept handshakes that do not use the extended * master secret [..]. (and see 5.2, 5.3) */ this.mSecurityParameters.extendedMasterSecret = !TlsUtilities.IsSsl(mTlsClientContext) && TlsExtensionsUtilities.HasExtendedMasterSecretExtension(mServerExtensions); if (!mSecurityParameters.IsExtendedMasterSecret && (mResumedSession || mTlsClient.RequiresExtendedMasterSecret())) { throw new TlsFatalAlert(AlertDescription.handshake_failure); } /* * RFC 3546 2.2 Note that the extended server hello message is only sent in response to an * extended client hello message. * * However, see RFC 5746 exception below. We always include the SCSV, so an Extended Server * Hello is always allowed. */ if (this.mServerExtensions != null) { foreach (int extType in this.mServerExtensions.Keys) { /* * RFC 5746 3.6. Note that Sending a "renegotiation_info" extension in response to a * ClientHello containing only the SCSV is an explicit exception to the prohibition * in RFC 5246, Section 7.4.1.4, on the server Sending unsolicited extensions and is * only allowed because the client is signaling its willingness to receive the * extension via the TLS_EMPTY_RENEGOTIATION_INFO_SCSV SCSV. */ if (extType == ExtensionType.renegotiation_info) { continue; } /* * RFC 5246 7.4.1.4 An extension type MUST NOT appear in the ServerHello unless the * same extension type appeared in the corresponding ClientHello. If a client * receives an extension type in ServerHello that it did not request in the * associated ClientHello, it MUST abort the handshake with an unsupported_extension * fatal alert. */ if (null == TlsUtilities.GetExtensionData(this.mClientExtensions, extType)) { throw new TlsFatalAlert(AlertDescription.unsupported_extension); } /* * RFC 3546 2.3. If [...] the older session is resumed, then the server MUST ignore * extensions appearing in the client hello, and Send a server hello containing no * extensions[.] */ if (this.mResumedSession) { // TODO[compat-gnutls] GnuTLS test server Sends server extensions e.g. ec_point_formats // TODO[compat-openssl] OpenSSL test server Sends server extensions e.g. ec_point_formats // TODO[compat-polarssl] PolarSSL test server Sends server extensions e.g. ec_point_formats // throw new TlsFatalAlert(AlertDescription.illegal_parameter); } } } /* * RFC 5746 3.4. Client Behavior: Initial Handshake */ { /* * When a ServerHello is received, the client MUST check if it includes the * "renegotiation_info" extension: */ byte[] renegExtData = TlsUtilities.GetExtensionData(this.mServerExtensions, ExtensionType.renegotiation_info); if (renegExtData != null) { /* * If the extension is present, set the secure_renegotiation flag to TRUE. The * client MUST then verify that the length of the "renegotiated_connection" * field is zero, and if it is not, MUST abort the handshake (by Sending a fatal * handshake_failure alert). */ this.mSecureRenegotiation = true; if (!Arrays.ConstantTimeAreEqual(renegExtData, CreateRenegotiationInfo(TlsUtilities.EmptyBytes))) { throw new TlsFatalAlert(AlertDescription.handshake_failure); } } } // TODO[compat-gnutls] GnuTLS test server fails to Send renegotiation_info extension when resuming this.mTlsClient.NotifySecureRenegotiation(this.mSecureRenegotiation); IDictionary sessionClientExtensions = mClientExtensions, sessionServerExtensions = mServerExtensions; if (this.mResumedSession) { if (selectedCipherSuite != this.mSessionParameters.CipherSuite || selectedCompressionMethod != this.mSessionParameters.CompressionAlgorithm) { throw new TlsFatalAlert(AlertDescription.illegal_parameter); } sessionClientExtensions = null; sessionServerExtensions = this.mSessionParameters.ReadServerExtensions(); } this.mSecurityParameters.cipherSuite = selectedCipherSuite; this.mSecurityParameters.compressionAlgorithm = selectedCompressionMethod; if (sessionServerExtensions != null && sessionServerExtensions.Count > 0) { { /* * RFC 7366 3. If a server receives an encrypt-then-MAC request extension from a client * and then selects a stream or Authenticated Encryption with Associated Data (AEAD) * ciphersuite, it MUST NOT send an encrypt-then-MAC response extension back to the * client. */ bool serverSentEncryptThenMAC = TlsExtensionsUtilities.HasEncryptThenMacExtension(sessionServerExtensions); if (serverSentEncryptThenMAC && !TlsUtilities.IsBlockCipherSuite(selectedCipherSuite)) { throw new TlsFatalAlert(AlertDescription.illegal_parameter); } this.mSecurityParameters.encryptThenMac = serverSentEncryptThenMAC; } this.mSecurityParameters.maxFragmentLength = ProcessMaxFragmentLengthExtension(sessionClientExtensions, sessionServerExtensions, AlertDescription.illegal_parameter); this.mSecurityParameters.truncatedHMac = TlsExtensionsUtilities.HasTruncatedHMacExtension(sessionServerExtensions); /* * TODO It's surprising that there's no provision to allow a 'fresh' CertificateStatus to be sent in * a session resumption handshake. */ this.mAllowCertificateStatus = !this.mResumedSession && TlsUtilities.HasExpectedEmptyExtensionData(sessionServerExtensions, ExtensionType.status_request, AlertDescription.illegal_parameter); this.mExpectSessionTicket = !this.mResumedSession && TlsUtilities.HasExpectedEmptyExtensionData(sessionServerExtensions, ExtensionType.session_ticket, AlertDescription.illegal_parameter); } if (sessionClientExtensions != null) { this.mTlsClient.ProcessServerExtensions(sessionServerExtensions); } this.mSecurityParameters.prfAlgorithm = GetPrfAlgorithm(Context, this.mSecurityParameters.CipherSuite); /* * RFC 5246 7.4.9. Any cipher suite which does not explicitly specify * verify_data_length has a verify_data_length equal to 12. This includes all * existing cipher suites. */ this.mSecurityParameters.verifyDataLength = 12; }
/** * Add verification for a particular signature * @param signatureName the signature to validate (it may be a timestamp) * @param ocsp the interface to get the OCSP * @param crl the interface to get the CRL * @param certOption * @param level the validation options to include * @param certInclude * @return true if a validation was generated, false otherwise * @throws Exception */ virtual public bool AddVerification(String signatureName, IOcspClient ocsp, ICrlClient crl, CertificateOption certOption, Level level, CertificateInclusion certInclude) { if (used) { throw new InvalidOperationException(MessageLocalization.GetComposedMessage("verification.already.output")); } PdfPKCS7 pk = acroFields.VerifySignature(signatureName); LOGGER.Info("Adding verification for " + signatureName); X509Certificate[] xc = pk.Certificates; X509Certificate cert; X509Certificate signingCert = pk.SigningCertificate; ValidationData vd = new ValidationData(); for (int k = 0; k < xc.Length; ++k) { cert = xc[k]; LOGGER.Info("Certificate: " + cert.SubjectDN); if (certOption == CertificateOption.SIGNING_CERTIFICATE && !cert.Equals(signingCert)) { continue; } byte[] ocspEnc = null; if (ocsp != null && level != Level.CRL) { ocspEnc = ocsp.GetEncoded(cert, GetParent(cert, xc), null); if (ocspEnc != null) { vd.ocsps.Add(BuildOCSPResponse(ocspEnc)); LOGGER.Info("OCSP added"); } } if (crl != null && (level == Level.CRL || level == Level.OCSP_CRL || (level == Level.OCSP_OPTIONAL_CRL && ocspEnc == null))) { ICollection <byte[]> cims = crl.GetEncoded(xc[k], null); if (cims != null) { foreach (byte[] cim in cims) { bool dup = false; foreach (byte[] b in vd.crls) { if (Arrays.AreEqual(b, cim)) { dup = true; break; } } if (!dup) { vd.crls.Add(cim); LOGGER.Info("CRL added"); } } } } if (certInclude == CertificateInclusion.YES) { vd.certs.Add(xc[k].GetEncoded()); } } if (vd.crls.Count == 0 && vd.ocsps.Count == 0) { return(false); } validated[GetSignatureHashKey(signatureName)] = vd; return(true); }
protected virtual bool Equals( DsaValidationParameters other) { return(counter == other.counter && Arrays.AreEqual(seed, other.seed)); }
/// <summary> return true if the signature represents a ISO9796-2 signature /// for the passed in message. /// </summary> public virtual bool VerifySignature(byte[] signature) { byte[] block; if (preSig == null) { try { block = cipher.ProcessBlock(signature, 0, signature.Length); } catch (Exception) { return(false); } } else { if (!Arrays.AreEqual(preSig, signature)) { throw new InvalidOperationException("updateWithRecoveredMessage called on different signature"); } block = preBlock; preSig = null; preBlock = null; } if (((block[0] & 0xC0) ^ 0x40) != 0) { return(ReturnFalse(block)); } if (((block[block.Length - 1] & 0xF) ^ 0xC) != 0) { return(ReturnFalse(block)); } int delta = 0; if (((block[block.Length - 1] & 0xFF) ^ 0xBC) == 0) { delta = 1; } else { int sigTrail = ((block[block.Length - 2] & 0xFF) << 8) | (block[block.Length - 1] & 0xFF); if (IsoTrailers.NoTrailerAvailable(digest)) { throw new ArgumentException("unrecognised hash in signature"); } if (sigTrail != IsoTrailers.GetTrailer(digest)) { throw new InvalidOperationException("signer initialised with wrong digest for trailer " + sigTrail); } delta = 2; } // // find out how much padding we've got // int mStart = 0; for (; mStart != block.Length; mStart++) { if (((block[mStart] & 0x0f) ^ 0x0a) == 0) { break; } } mStart++; // // check the hashes // byte[] hash = new byte[digest.GetDigestSize()]; int off = block.Length - delta - hash.Length; // // there must be at least one byte of message string // if ((off - mStart) <= 0) { return(ReturnFalse(block)); } // // if we contain the whole message as well, check the hash of that. // if ((block[0] & 0x20) == 0) { fullMessage = true; // check right number of bytes passed in. if (messageLength > off - mStart) { return(ReturnFalse(block)); } digest.Reset(); digest.BlockUpdate(block, mStart, off - mStart); digest.DoFinal(hash, 0); bool isOkay = true; for (int i = 0; i != hash.Length; i++) { block[off + i] ^= hash[i]; if (block[off + i] != 0) { isOkay = false; } } if (!isOkay) { return(ReturnFalse(block)); } recoveredMessage = new byte[off - mStart]; Array.Copy(block, mStart, recoveredMessage, 0, recoveredMessage.Length); } else { fullMessage = false; digest.DoFinal(hash, 0); bool isOkay = true; for (int i = 0; i != hash.Length; i++) { block[off + i] ^= hash[i]; if (block[off + i] != 0) { isOkay = false; } } if (!isOkay) { return(ReturnFalse(block)); } recoveredMessage = new byte[off - mStart]; Array.Copy(block, mStart, recoveredMessage, 0, recoveredMessage.Length); } // // if they've input a message check what we've recovered against // what was input. // if (messageLength != 0) { if (!IsSameAs(mBuf, recoveredMessage)) { return(ReturnFalse(block)); } } ClearBlock(mBuf); ClearBlock(block); return(true); }
private void overrideAttrsTest(AsymmetricKeyParameter privateKey, X509Certificate cert, IX509Store certs) { SignerInfoGeneratorBuilder signerInfoGenBuilder = new SignerInfoGeneratorBuilder(); IssuerSerial issuerSerial = new IssuerSerial( new GeneralNames( new GeneralName( X509CertificateStructure.GetInstance(cert.GetEncoded()).Issuer)), new DerInteger(cert.SerialNumber)); byte[] certHash256; byte[] certHash; { Asn1DigestFactory digCalc = Asn1DigestFactory.Get(OiwObjectIdentifiers.IdSha1); IStreamCalculator calc = digCalc.CreateCalculator(); using (Stream s = calc.Stream) { byte[] crt = cert.GetEncoded(); s.Write(crt, 0, crt.Length); } certHash = ((SimpleBlockResult)calc.GetResult()).Collect(); } { Asn1DigestFactory digCalc = Asn1DigestFactory.Get(NistObjectIdentifiers.IdSha256); IStreamCalculator calc = digCalc.CreateCalculator(); using (Stream s = calc.Stream) { byte[] crt = cert.GetEncoded(); s.Write(crt, 0, crt.Length); } certHash256 = ((SimpleBlockResult)calc.GetResult()).Collect(); } EssCertID essCertid = new EssCertID(certHash, issuerSerial); EssCertIDv2 essCertidV2 = new EssCertIDv2(certHash256, issuerSerial); signerInfoGenBuilder.WithSignedAttributeGenerator(new TestAttrGen() { EssCertID = essCertid, EssCertIDv2 = essCertidV2 }); Asn1SignatureFactory sigfact = new Asn1SignatureFactory("SHA1WithRSA", privateKey); SignerInfoGenerator signerInfoGenerator = signerInfoGenBuilder.Build(sigfact, cert); TimeStampTokenGenerator tsTokenGen = new TimeStampTokenGenerator( signerInfoGenerator, Asn1DigestFactory.Get(OiwObjectIdentifiers.IdSha1), new DerObjectIdentifier("1.2"), true); tsTokenGen.SetCertificates(certs); TimeStampRequestGenerator reqGen = new TimeStampRequestGenerator(); TimeStampRequest request = reqGen.Generate(TspAlgorithms.Sha1, new byte[20], BigInteger.ValueOf(100)); TimeStampResponseGenerator tsRespGen = new TimeStampResponseGenerator(tsTokenGen, TspAlgorithms.Allowed); TimeStampResponse tsResp = tsRespGen.Generate(request, BigInteger.ValueOf(23), DateTime.UtcNow); tsResp = new TimeStampResponse(tsResp.GetEncoded()); TimeStampToken tsToken = tsResp.TimeStampToken; tsToken.Validate(cert); Asn1.Cms.AttributeTable table = tsToken.SignedAttributes; Assert.NotNull(table[PkcsObjectIdentifiers.IdAASigningCertificate], "no signingCertificate attribute found"); Assert.NotNull(table[PkcsObjectIdentifiers.IdAASigningCertificateV2], "no signingCertificateV2 attribute found"); SigningCertificate sigCert = SigningCertificate.GetInstance(table[PkcsObjectIdentifiers.IdAASigningCertificate].AttrValues[0]); Assert.IsTrue(cert.CertificateStructure.Issuer.Equals(sigCert.GetCerts()[0].IssuerSerial.Issuer.GetNames()[0].Name)); Assert.IsTrue(cert.CertificateStructure.SerialNumber.Value.Equals(sigCert.GetCerts()[0].IssuerSerial.Serial.Value)); Assert.IsTrue(Arrays.AreEqual(certHash, sigCert.GetCerts()[0].GetCertHash())); SigningCertificate sigCertV2 = SigningCertificate.GetInstance(table[PkcsObjectIdentifiers.IdAASigningCertificateV2].AttrValues[0]); Assert.IsTrue(cert.CertificateStructure.Issuer.Equals(sigCertV2.GetCerts()[0].IssuerSerial.Issuer.GetNames()[0].Name)); Assert.IsTrue(cert.CertificateStructure.SerialNumber.Value.Equals(sigCertV2.GetCerts()[0].IssuerSerial.Serial.Value)); Assert.IsTrue(Arrays.AreEqual(certHash256, sigCertV2.GetCerts()[0].GetCertHash())); }
public virtual bool VerifySignature(byte[] signature) { //IL_0037: Unknown result type (might be due to invalid IL or missing references) //IL_00ca: Unknown result type (might be due to invalid IL or missing references) //IL_00ee: Unknown result type (might be due to invalid IL or missing references) byte[] array; if (preSig == null) { try { array = cipher.ProcessBlock(signature, 0, signature.Length); } catch (global::System.Exception) { return(false); } } else { if (!Arrays.AreEqual(preSig, signature)) { throw new InvalidOperationException("updateWithRecoveredMessage called on different signature"); } array = preBlock; preSig = null; preBlock = null; } if (((array[0] & 0xC0u) ^ 0x40u) != 0) { return(ReturnFalse(array)); } if (((array[array.Length - 1] & 0xFu) ^ 0xCu) != 0) { return(ReturnFalse(array)); } int num = 0; if (((array[array.Length - 1] & 0xFF) ^ 0xBC) == 0) { num = 1; } else { int num2 = ((array[array.Length - 2] & 0xFF) << 8) | (array[array.Length - 1] & 0xFF); if (IsoTrailers.NoTrailerAvailable(digest)) { throw new ArgumentException("unrecognised hash in signature"); } if (num2 != IsoTrailers.GetTrailer(digest)) { throw new InvalidOperationException(string.Concat((object)"signer initialised with wrong digest for trailer ", (object)num2)); } num = 2; } int i; for (i = 0; i != array.Length && ((array[i] & 0xFu) ^ 0xAu) != 0; i++) { } i++; byte[] array2 = new byte[digest.GetDigestSize()]; int num3 = array.Length - num - array2.Length; if (num3 - i <= 0) { return(ReturnFalse(array)); } if ((array[0] & 0x20) == 0) { fullMessage = true; if (messageLength > num3 - i) { return(ReturnFalse(array)); } digest.Reset(); digest.BlockUpdate(array, i, num3 - i); digest.DoFinal(array2, 0); bool flag = true; for (int j = 0; j != array2.Length; j++) { byte[] array3; byte[] array4 = (array3 = array); int num4 = num3 + j; global::System.IntPtr intPtr = (global::System.IntPtr)num4; array4[num4] = (byte)(array3[(long)intPtr] ^ array2[j]); if (array[num3 + j] != 0) { flag = false; } } if (!flag) { return(ReturnFalse(array)); } recoveredMessage = new byte[num3 - i]; global::System.Array.Copy((global::System.Array)array, i, (global::System.Array)recoveredMessage, 0, recoveredMessage.Length); } else { fullMessage = false; digest.DoFinal(array2, 0); bool flag2 = true; for (int k = 0; k != array2.Length; k++) { byte[] array3; byte[] array5 = (array3 = array); int num5 = num3 + k; global::System.IntPtr intPtr = (global::System.IntPtr)num5; array5[num5] = (byte)(array3[(long)intPtr] ^ array2[k]); if (array[num3 + k] != 0) { flag2 = false; } } if (!flag2) { return(ReturnFalse(array)); } recoveredMessage = new byte[num3 - i]; global::System.Array.Copy((global::System.Array)array, i, (global::System.Array)recoveredMessage, 0, recoveredMessage.Length); } if (messageLength != 0 && !IsSameAs(mBuf, recoveredMessage)) { return(ReturnFalse(array)); } ClearBlock(mBuf); ClearBlock(array); return(true); }
public void Init(byte[] H) { if (M == null) { M = new uint[32][][]; } else if (Arrays.AreEqual(this.H, H)) { return; } this.H = Arrays.Clone(H); M[0] = new uint[16][]; M[1] = new uint[16][]; M[0][0] = new uint[4]; M[1][0] = new uint[4]; M[1][8] = GcmUtilities.AsUints(H); for (int j = 4; j >= 1; j >>= 1) { uint[] tmp = (uint[])M[1][j + j].Clone(); GcmUtilities.MultiplyP(tmp); M[1][j] = tmp; } { uint[] tmp = (uint[])M[1][1].Clone(); GcmUtilities.MultiplyP(tmp); M[0][8] = tmp; } for (int j = 4; j >= 1; j >>= 1) { uint[] tmp = (uint[])M[0][j + j].Clone(); GcmUtilities.MultiplyP(tmp); M[0][j] = tmp; } for (int i = 0; ;) { for (int j = 2; j < 16; j += j) { for (int k = 1; k < j; ++k) { uint[] tmp = (uint[])M[i][j].Clone(); GcmUtilities.Xor(tmp, M[i][k]); M[i][j + k] = tmp; } } if (++i == 32) { return; } if (i > 1) { M[i] = new uint[16][]; M[i][0] = new uint[4]; for (int j = 8; j > 0; j >>= 1) { uint[] tmp = (uint[])M[i - 2][j].Clone(); GcmUtilities.MultiplyP8(tmp); M[i][j] = tmp; } } } }
private static void AssertArrayEquals(byte[] a, byte[] b) { Assert.IsTrue(Arrays.AreEqual(a, b)); }