예제 #1
0
 public UserInfo(ICryptoSuite suite, string mspid, string name, string enrollSecret)
 {
     Name         = name;
     EnrollSecret = enrollSecret;
     MspId        = mspid;
     Suite        = suite;
 }
예제 #2
0
        /**
         * used asn1 and get hash
         *
         * @param blockNumber
         * @param previousHash
         * @param dataHash
         * @return byte[]
         * @throws IOException
         * @throws InvalidIllegalArgumentException
         */
        public static byte[] CalculateBlockHash(HFClient client, long blockNumber, byte[] previousHash, byte[] dataHash)
        {
            if (previousHash == null)
            {
                throw new ArgumentException("previousHash parameter is null.");
            }

            if (dataHash == null)
            {
                throw new ArgumentException("dataHash parameter is null.");
            }

            if (null == client)
            {
                throw new ArgumentException("client parameter is null.");
            }

            ICryptoSuite cryptoSuite = client.CryptoSuite;

            if (null == cryptoSuite)
            {
                throw new ArgumentException("Client crypto suite has not  been set.");
            }

            MemoryStream         s   = new MemoryStream();
            DerSequenceGenerator seq = new DerSequenceGenerator(s);

            seq.AddObject(new DerInteger((int)blockNumber));
            seq.AddObject(new DerOctetString(previousHash));
            seq.AddObject(new DerOctetString(dataHash));
            seq.Close();
            s.Flush();
            return(cryptoSuite.Hash(s.ToArray()));
        }
        public void TestValidationOfCertWithFabicCAattributes()
        {
            ICryptoSuite     cryptoSuite      = Factory.Instance.GetCryptoSuite();
            Certificate      onceFailingPem   = Certificate.Create(File.ReadAllText("Fixture/testPems/peerCert.pem".Locate()));
            CryptoPrimitives cryptoPrimitives = (CryptoPrimitives)cryptoSuite;

            cryptoPrimitives.Store.AddCertificateFromFile("fixture/testPems/caBundled.pems".Locate());
            Assert.IsTrue(cryptoPrimitives.Store.Validate(onceFailingPem));
        }
예제 #4
0
        // ==========================================================================================
        // Helper methods
        // ==========================================================================================

        private TransactionContext CreateTestContext()
        {
            Channel channel = CreateTestChannel("channel1");

            IUser        user        = hfclient.UserContext;
            ICryptoSuite cryptoSuite = hfclient.CryptoSuite;

            return(new TransactionContext(channel, user, cryptoSuite));
        }
        public void TestDefaultCrypto()
        {
            ICryptoSuite     cryptoSuite = Factory.Instance.GetCryptoSuite();
            CryptoPrimitives primitives  = (CryptoPrimitives)cryptoSuite;

            Assert.AreEqual("secp256r1", primitives.curveName);
            Assert.AreEqual(256, primitives.securityLevel);
            Assert.AreEqual("SHA2", primitives.hashAlgorithm);
            // Should be exactly same instance as it has the same properties.
            Assert.AreEqual(cryptoSuite, Factory.Instance.GetCryptoSuite());
        }
예제 #6
0
        public void TestEnrollmentNoServerResponse()
        {
            ICryptoSuite cryptoSuite = Factory.Instance.GetCryptoSuite();

            EnrollmentRequest req    = new EnrollmentRequest("profile 1", "label 1", null);
            HFCAClient        client = HFCAClient.Create("client", "http://localhost:99", null);

            client.CryptoSuite = cryptoSuite;

            client.Enroll(TEST_ADMIN_NAME, TEST_ADMIN_NAME, req);
        }
        public ICryptoSuite GetCryptoSuite(Properties properties)
        {
            ICryptoSuite ret = null;

            foreach (Properties st in cache.Keys)
            {
                bool found = true;
                foreach (string key in properties.Keys)
                {
                    if (!st.Contains(key))
                    {
                        found = false;
                    }
                    else
                    {
                        if (st[key] != properties[key])
                        {
                            found = false;
                        }
                    }

                    if (!found)
                    {
                        break;
                    }
                }

                if (found)
                {
                    ret = cache[st];
                    break;
                }
            }

            if (ret == null)
            {
                try
                {
                    CryptoPrimitives cp = new CryptoPrimitives();
                    cp.SetProperties(properties);
                    cp.Init();
                    ret = cp;
                }
                catch (Exception e)
                {
                    throw new CryptoException(e.Message, e);
                }

                cache[properties] = ret;
            }

            return(ret);
        }
예제 #8
0
        public void TestGetters()
        {
            Channel channel = CreateTestChannel("channel1");

            IUser        user        = hfclient.UserContext;
            ICryptoSuite cryptoSuite = hfclient.CryptoSuite;

            TransactionContext context = new TransactionContext(channel, user, cryptoSuite);

            // ensure getCryptoPrimitives returns what we passed in to the constructor
            ICryptoSuite cryptoPrimitives = context.CryptoPrimitives;

            Assert.AreEqual(cryptoSuite, cryptoPrimitives);
        }
예제 #9
0
        public static ISigningIdentity GetSigningIdentity(ICryptoSuite cryptoSuite, IUser user)
        {
            IEnrollment enrollment = user.Enrollment;

            if (enrollment is IdemixEnrollment)
            {
                // Need Idemix signer for this.
                return(new IdemixSigningIdentity((IdemixEnrollment)enrollment));
            }
            else
            {
                // for now all others are x509
                return(new X509SigningIdentity(cryptoSuite, user));
            }
        }
예제 #10
0
        public SampleUser(string name, string org, /*SampleStore fs,*/ ICryptoSuite cryptoSuite)
        {
            this.Name        = name;
            this.cryptoSuite = cryptoSuite;

            //keyValStore = fs;
            //Organization = org;
            KeyValStoreName = ToKeyValStoreName(Name, org);
            //string memberStr = keyValStore.GetValue(KeyValStoreName);
            //if (null == memberStr)
            //{
            //    SaveState();
            //}
            //else
            //{
            //    RestoreState();
            //}
        }
예제 #11
0
        public SampleUser(string name, string org, SampleStore fs, ICryptoSuite cryptoSuite)
        {
            this.Name        = name;
            this.cryptoSuite = cryptoSuite;

            keyValStore     = fs;
            Organization    = org;
            KeyValStoreName = ToKeyValStoreName(Name, org);
            string memberStr = keyValStore.GetValue(KeyValStoreName);

            if (null == memberStr)
            {
                SaveState();
            }
            else
            {
                RestoreState();
            }
        }
        public void TestGetSetProperties()
        {
            Properties propsIn = new Properties();

            try
            {
                string expectHash = "SHA3"; // use something different than default!
                propsIn.Set(Config.SECURITY_LEVEL, "384");
                propsIn.Set(Config.HASH_ALGORITHM, expectHash);
                //    testCrypto.setProperties(propsIn);
                //   testCrypto.init();
                ICryptoSuite testCrypto = Factory.Instance.GetCryptoSuite(propsIn);

                //          Assert.AreEqual(BouncyCastleProvider.class, getField(testCrypto, "SECURITY_PROVIDER").getClass());

                string           expectedCurve = config.GetSecurityCurveMapping()[384];
                CryptoPrimitives original      = (CryptoPrimitives)testCrypto;
                Assert.AreEqual("secp384r1", expectedCurve);
                Assert.AreEqual(expectedCurve, original.curveName);
                Assert.AreEqual(384, original.securityLevel);
                Properties cryptoProps = original.GetProperties();
                Assert.AreEqual(cryptoProps[Config.SECURITY_LEVEL], "384");
                cryptoProps = testCrypto.GetProperties();
                Assert.AreEqual(cryptoProps[Config.HASH_ALGORITHM], expectHash);
                Assert.AreEqual(expectHash, original.hashAlgorithm);
                Assert.AreEqual(cryptoProps[Config.SECURITY_LEVEL], "384");

                // Should be exactly same instance as it has the same properties.
                Assert.AreEqual(testCrypto, Factory.Instance.GetCryptoSuite(propsIn));
            }
            catch (CryptoException e)
            {
                Assert.Fail($"TestGetSetProperties should not throw exception. Error: {e.Message}");
            }
            catch (ArgumentException e)
            {
                Assert.Fail($"TestGetSetProperties should not throw exception. Error: {e.Message}");
            }
        }
예제 #13
0
        public static void SetupClient(HFClient hfclient)
        {
            ICryptoSuite cryptoSuite = Factory.GetCryptoSuite();

            string props = Path.Combine(GetHomePath(), "test.properties");

            if (File.Exists(props))
            {
                File.Delete(props);
            }
            SampleStore sampleStore = new SampleStore(props);

            //src/test/fixture/sdkintegration/e2e-2Orgs/channel/crypto-config/peerOrganizations/org1.example.com/users/[email protected]/msp/keystore/

            //SampleUser someTestUSER = sampleStore.getMember("someTestUSER", "someTestORG");
            SampleUser someTestUSER = sampleStore.GetMember("someTestUSER", "someTestORG", "mspid", FindFileSk("fixture/sdkintegration/e2e-2Orgs/" + TestConfig.Instance.FAB_CONFIG_GEN_VERS + "/crypto-config/peerOrganizations/org1.example.com/users/[email protected]/msp/keystore"), ("fixture/sdkintegration/e2e-2Orgs/" + TestConfig.Instance.FAB_CONFIG_GEN_VERS + "/crypto-config/peerOrganizations/org1.example.com/users/[email protected]/msp/signcerts/[email protected]").Locate());

            someTestUSER.MspId = "testMSPID?";

            hfclient.CryptoSuite = Factory.Instance.GetCryptoSuite();
            hfclient.UserContext = someTestUSER;
        }
예제 #14
0
        //private List<String> attrs;


        public TransactionContext(Channel channel, IUser user, ICryptoSuite cryptoPrimitives)
        {
            User    = user;
            Channel = channel;
            //TODO clean up when public classes are interfaces.
            Verify = !"".Equals(channel.Name); //if name is not blank not system channel and need verify.
            //  this.txID = transactionID;
            CryptoPrimitives = cryptoPrimitives;

            // Get the signing identity from the user
            signingIdentity = IdentityFactory.GetSigningIdentity(cryptoPrimitives, user);

            // Serialize signingIdentity
            Identity = signingIdentity.CreateSerializedIdentity();

            ByteString no = Nonce;

            byte[] comp = no.Concat(Identity.ToByteArray()).ToArray();
            byte[] txh  = cryptoPrimitives.Hash(comp);
            //    txID = Hex.encodeHexString(txh);
            TxID     = txh.ToHexString();
            toString = $"TransactionContext {{ txID: {TxID} mspid: {user.MspId}, user: {user.Name} }}";
        }
예제 #15
0
 public X509SigningIdentity(ICryptoSuite cryptoSuite, IUser user) : base(user)
 {
     this.cryptoSuite = cryptoSuite ?? throw new ArgumentException("CryptoSuite is null");
 }
예제 #16
0
        /*
         * Verifies that a Proposal response is properly signed. The payload is the
         * concatenation of the response payload byte string and the endorsement The
         * certificate (public key) is gotten from the Endorsement.Endorser.IdBytes
         * field
         *
         * @param crypto the CryptoPrimitives instance to be used for signing and
         * verification
         *
         * @return true/false depending on result of signature verification
         */
        public bool Verify(ICryptoSuite crypto)
        {
            logger.Trace($"{Peer} verifying transaction: {TransactionID} endorsement.");
            if (HasBeenVerified)
            {
                // check if this proposalResponse was already verified   by client code
                logger.Trace($"{Peer} transaction: {TransactionID} was already verified returned {IsVerified}");
                return(IsVerified);
            }

            try
            {
                if (IsInvalid)
                {
                    IsVerified = false;
                    logger.Debug($"{Peer} for transaction {TransactionID} returned invalid. Setting verify to false");
                    return(false);
                }

                Endorsement endorsement        = ProtoProposalResponse.Endorsement;
                ByteString  sig                = endorsement.Signature;
                byte[]      endorserCertifcate = null;
                byte[]      signature          = null;
                byte[]      data               = null;

                try
                {
                    SerializedIdentity endorser  = SerializedIdentity.Parser.ParseFrom(endorsement.Endorser);
                    ByteString         plainText = ByteString.CopyFrom(ProtoProposalResponse.Payload.Concat(endorsement.Endorser).ToArray());

                    if (Config.Instance.ExtraLogLevel(10))
                    {
                        if (null != diagnosticFileDumper)
                        {
                            StringBuilder sb = new StringBuilder(10000);
                            sb.AppendLine("payload TransactionBuilder bytes in hex: " + ProtoProposalResponse.Payload.ToByteArray().ToHexString());
                            sb.AppendLine("endorser bytes in hex: " + endorsement.ToByteArray().ToHexString());
                            sb.Append("plainText bytes in hex: " + plainText.ToByteArray().ToHexString());
                            logger.Trace("payload TransactionBuilder bytes:  " + diagnosticFileDumper.CreateDiagnosticFile(sb.ToString()));
                        }
                    }

                    if (sig == null || sig.IsEmpty)
                    {
                        // we shouldn't get here ...
                        logger.Warn($"{Peer} {TransactionID} returned signature is empty verify set to false.");
                        IsVerified = false;
                    }
                    else
                    {
                        endorserCertifcate = endorser.IdBytes.ToByteArray();
                        signature          = sig.ToByteArray();
                        data = plainText.ToByteArray();

                        IsVerified = crypto.Verify(endorserCertifcate, Config.Instance.GetSignatureAlgorithm(), signature, data);
                        if (!IsVerified)
                        {
                            logger.Warn($"{Peer} transaction: {TransactionID} verify: Failed to verify. Endorsers certificate: {endorserCertifcate.ToHexString()}, signature: {signature.ToHexString()}, signing algorithm: {Config.Instance.GetSignatureAlgorithm()}, signed data: {data.ToHexString()}.");
                        }
                    }
                }
                catch (Exception e)
                {
                    logger.ErrorException($"{Peer} transaction: {TransactionID} verify: Failed to verify. Endorsers certificate: {endorserCertifcate.ToHexString()}, signature: {signature.ToHexString()}, signing algorithm: {Config.Instance.GetSignatureAlgorithm()}, signed data: {data.ToHexString()}.", e);
                    logger.Error($"{Peer} transaction: {TransactionID} verify: Cannot retrieve peer identity from ProposalResponse. Error is: {e.Message}");


                    logger.ErrorException("verify: Cannot retrieve peer identity from ProposalResponse. Error is: " + e.Message, e);
                    IsVerified = false;
                }

                logger.Debug($"{Peer} finished verify for transaction {TransactionID} returning {IsVerified}");
                return(IsVerified);
            }
            finally
            {
                HasBeenVerified = true;
            }
        } // verify