Beispiel #1
0
        public void CollaborativeIssuanceTrustedGamma()
        {
            // Issuance
            byte[][] attributes = new byte[][] { encoding.GetBytes("Attribute 1"), encoding.GetBytes("Attribute 2"), encoding.GetBytes("Attribute 3") };
            ProverProtocolParameters ppp = new ProverProtocolParameters(ip);
            ppp.Attributes = attributes;
            Prover prover = ppp.CreateProver();

            IssuerProtocolParameters ipp = new IssuerProtocolParameters(ikap);
            ipp.Gamma = ProtocolHelper.ComputeIssuanceInput(ip, attributes, null, null); // computed by some other party. 
            Issuer issuer = ipp.CreateIssuer();

            FirstIssuanceMessage msg1 = issuer.GenerateFirstMessage();
            SecondIssuanceMessage msg2 = prover.GenerateSecondMessage(msg1);
            ThirdIssuanceMessage msg3 = issuer.GenerateThirdMessage(msg2);
            UProveKeyAndToken[] upkt = prover.GenerateTokens(msg3);

            // use the token to make sure everything is ok
            int[] disclosed = new int[0];
            byte[] message = encoding.GetBytes("this is the presentation message, this can be a very long message");
            UProveCrypto.Math.FieldZqElement[] unused;
            byte[] scope = null;
            PresentationProof proof = PresentationProof.Generate(ip, disclosed, null, 1, scope, message, null, null, upkt[0], attributes, out unused);
            proof.Verify(ip, disclosed, null, 1, scope, message, null, upkt[0].Token);
        }
        /// <summary>
        /// creates the second message to the received first message from the issuer
        /// </summary>
        /// <param name="devicePublicKey">if the tokens are hard token protected, this is
        /// the public key of that device</param>
        /// <returns>SecondMessage as json string or if there was a failure, an empty string</returns>
        public string GenerateSecondMessage(GroupElement devicePublicKey = null)
        {
            try
            {
                LogService.Log(LogService.LogType.Info, "IssuingProver - GenerateSecondMessage called");

                // initialize prover protocol
                ProverProtocolParameters ppp = new ProverProtocolParameters(IP);
                ppp.Attributes     = ByteAttributes = ci.ConvertAttributeListToBase64ByteArray(Attributes);
                ppp.NumberOfTokens = numberOfTokens;

                ppp.TokenInformation  = ti != null ? ti : null;
                ppp.ProverInformation = pi;

                if (devicePublicKey != null)
                {
                    ppp.DevicePublicKey = devicePublicKey;
                }

                prover = ppp.CreateProver();

                string secondMessageJson = IP.Serialize <SecondIssuanceMessage>(
                    prover.GenerateSecondMessage(IP.Deserialize <FirstIssuanceMessage>(firstMessageJson)));

                LogService.Log(LogService.LogType.Info, "IssuingProver - SecondMessage created: " + secondMessageJson);

                return(secondMessageJson);
            }
            catch (Exception e)
            {
                LogService.Log(LogService.LogType.Error, "IssuingProver - Error during second message generation.", e);
                throw new CommunicationException("IssuingProver - Error during second message generation.", e);
            }
        }
Beispiel #3
0
        private GenerateTokensInfo HandleGenerateTokens(Prover prover, ThirdIssuanceMessage thirdIssuanceMessage)
        {
            GenerateTokensInfo gInfo = new GenerateTokensInfo();

            gInfo.Tokens = prover.GenerateTokens(thirdIssuanceMessage, true);
            return(gInfo);
        }
        public static void MyClassInitialize(TestContext testContext)
        {
            //
            // generate issuer parameters
            //
            IssuerSetupParameters isp = new IssuerSetupParameters(maxNumberOfAttributes);

            isp.UidP = new byte[] { (byte)0 };
            //isp.NumberOfAttributes = 1;
            isp.E = new byte[] { (byte)0 };  // encode xid directly has an
            IssuerKeyAndParameters ikap = isp.Generate();

            ip = ikap.IssuerParameters;

            //
            // issue a token
            //
            xid = ip.Gq.FieldZq.GetRandomElement(false);
            IssuerProtocolParameters ipp = new IssuerProtocolParameters(ikap);
            ProverProtocolParameters ppp = new ProverProtocolParameters(ip);

            attributes         = new byte[][] { xid.ToByteArray() };
            ipp.Attributes     = ppp.Attributes = attributes;
            ipp.NumberOfTokens = ppp.NumberOfTokens = 1;
            Issuer issuer = ipp.CreateIssuer();
            Prover prover = ppp.CreateProver();

            upkt = prover.GenerateTokens(issuer.GenerateThirdMessage(prover.GenerateSecondMessage(issuer.GenerateFirstMessage())))[0];
        }
Beispiel #5
0
        public bool Move(Direction dir)
        {
            if (Pbattery != null && Pbattery.TakePower(PpowerAmount))
            {
                switch (dir)
                {
                case Direction.Down:
                    Prover.UpdatePos(Prover.Location.X, Prover.Location.Y + 1f);
                    break;

                case Direction.Up:
                    Prover.UpdatePos(Prover.Location.X, Prover.Location.Y - 1f);
                    break;

                case Direction.Left:
                    Prover.UpdatePos(Prover.Location.X - 1f, Prover.Location.Y);
                    break;

                case Direction.Right:
                    Prover.UpdatePos(Prover.Location.X + 1f, Prover.Location.Y);
                    break;
                }
                return(true);
            }
            else
            {
                return(false);
            }
        }
Beispiel #6
0
        public void TestProver()
        {
            byte[][] A  = new byte[][] { };
            byte[]   TI = null;
            byte[]   PI = null;
            IssuerSetupParameters isp = new IssuerSetupParameters(maxNumberOfAttributes);

            isp.UidP = new byte[] { 0 };
            isp.E    = new byte[] { 0 };
            IssuerKeyAndParameters   ikap = isp.Generate();
            IssuerProtocolParameters ipp  = new IssuerProtocolParameters(ikap);

            ipp.Attributes       = A;
            ipp.NumberOfTokens   = 1;
            ipp.TokenInformation = TI;
            Issuer issuer = ipp.CreateIssuer();

            FirstIssuanceMessage  msg1 = null;
            SecondIssuanceMessage msg2 = null;
            ThirdIssuanceMessage  msg3 = null;

            msg1 = issuer.GenerateFirstMessage();
            try { new Prover(null, 1, A, TI, PI, null); Assert.Fail(); } catch (ArgumentNullException) { }
            try { new Prover(ikap.IssuerParameters, -1, A, TI, PI, null); Assert.Fail(); } catch (ArgumentException) { }
            try { new Prover(ikap.IssuerParameters, 0, A, TI, PI, null); Assert.Fail(); } catch (ArgumentException) { }
            Prover prover = new Prover(ikap.IssuerParameters, 1, A, TI, PI, null);

            try { prover.GenerateTokens(msg3); Assert.Fail(); } catch (InvalidOperationException) { }
            msg2 = prover.GenerateSecondMessage(msg1);
            try { msg2 = prover.GenerateSecondMessage(msg1); Assert.Fail(); } catch (InvalidOperationException) { }
            msg3 = issuer.GenerateThirdMessage(msg2);
            prover.GenerateTokens(msg3);
            try { prover.GenerateTokens(msg3); Assert.Fail(); } catch (InvalidOperationException) { }
        }
Beispiel #7
0
        private static UProveKeyAndToken[] IssueUProveTokens(IssuerKeyAndParameters ikap, IssuerParameters ip, byte[][] attributes, int numOfTokens, byte[] ti = null, byte[] pi = null)
        {
            WriteLine("Issuing " + numOfTokens + " tokens");
            // setup the issuer and generate the first issuance message
            IssuerProtocolParameters ipp = new IssuerProtocolParameters(ikap);

            ipp.Attributes       = attributes;
            ipp.NumberOfTokens   = numOfTokens;
            ipp.TokenInformation = ti;
            Issuer issuer       = ipp.CreateIssuer();
            string firstMessage = ip.Serialize <FirstIssuanceMessage>(issuer.GenerateFirstMessage());

            // setup the prover and generate the second issuance message
            ProverProtocolParameters ppp = new ProverProtocolParameters(ip);

            ppp.Attributes        = attributes;
            ppp.NumberOfTokens    = numOfTokens;
            ppp.TokenInformation  = ti;
            ppp.ProverInformation = pi;
            Prover prover        = ppp.CreateProver();
            string secondMessage = ip.Serialize <SecondIssuanceMessage>(prover.GenerateSecondMessage(ip.Deserialize <FirstIssuanceMessage>(firstMessage)));

            // generate the third issuance message
            string thirdMessage = ip.Serialize <ThirdIssuanceMessage>(issuer.GenerateThirdMessage(ip.Deserialize <SecondIssuanceMessage>(secondMessage)));

            // generate the tokens
            return(prover.GenerateTokens(ip.Deserialize <ThirdIssuanceMessage>(thirdMessage)));
        }
Beispiel #8
0
        public SecondIssuanceMessageInfo SecondMessage(SecondIssuanceMessageSpec spec)
        {
            if (spec.IssuerParameter == null)
            {
                ApiArgumentFault fault = new ApiArgumentFault();
                fault.Details       = "Issuer with unique ID was found";
                fault.Argument      = "IssuerSetupParametersSpec.ID";
                fault.ArgumentValue = spec.IssuerParameter.Serialize();
                throw new FaultException <ApiArgumentFault>(fault);
            }
            ProverProtocolParameters pProtoParam = new ProverProtocolParameters(spec.IssuerParameter);

            pProtoParam.NumberOfTokens = spec.NumberOfTokens;
            if (!String.IsNullOrWhiteSpace(spec.TokenInfomation))
            {
                pProtoParam.TokenInformation = ExtensionMethods.ToByteArray(spec.TokenInfomation);
            }

            if (!String.IsNullOrWhiteSpace(spec.Gamma))
            {
                pProtoParam.Gamma = ExtensionMethods.ToGroupElement(spec.Gamma, spec.IssuerParameter);
            }

            if (!String.IsNullOrWhiteSpace(spec.DevicePublicKey))
            {
                pProtoParam.DevicePublicKey = ExtensionMethods.ToGroupElement(spec.DevicePublicKey, spec.IssuerParameter);
            }

            if (!String.IsNullOrWhiteSpace(spec.ProverInfomation))
            {
                pProtoParam.ProverInformation = ExtensionMethods.ToByteArray(spec.ProverInfomation);
            }

            if (spec.RandomData != null)
            {
                pProtoParam.ProverRandomData = spec.RandomData;
            }
            if (spec.BatchSecurityLevel > 0)
            {
                pProtoParam.BatchValidationSecurityLevel = spec.BatchSecurityLevel;
            }
            pProtoParam.Validate();
            Prover prover = pProtoParam.CreateProver();

            SecondIssuanceMessage  secondMessage          = prover.GenerateSecondMessage(spec.FirstMessage);
            PostSecondMessageState postSecondMessageState = prover.ExportPostSecondMessageState();

            SecondIssuanceMessageInfo simInfo = new SecondIssuanceMessageInfo();

            simInfo.PostSecondMessageState = postSecondMessageState;
            simInfo.SecondMessage          = secondMessage;

            Guid issuerInstance = Guid.NewGuid();

            simInfo.ProverInstanceID = issuerInstance;
            proverInstanceDB.TryAdd(issuerInstance, new ProverInstanceData(prover));

            return(simInfo);
        }
Beispiel #9
0
        public SecondIssuanceMessageComposite getSecondMessage(string[] attributesParam, IssuerParametersComposite ipc, int numberOfTokensParam, FirstIssuanceMessageComposite firstMessage, string sessionID)
        {
            /*
             *  token issuance - generate second message
             */

            cOut.write("Issuing U-Prove tokens - generate second message, prover side");
            VerifySessionId(sessionID);

            try
            {
                string tokenInformationParam  = null;
                string proverInformationParam = null;

                // specify the attribute values agreed to by the Issuer and Prover
                int      numberOfAttributes = attributesParam.Length;
                byte[][] attributes         = new byte[numberOfAttributes][];
                for (int i = 0; i < numberOfAttributes; i++)
                {
                    attributes[i] = encoding.GetBytes(attributesParam[i]);
                }

                // specify the special field values
                byte[] tokenInformation  = (tokenInformationParam == null) ? new byte[] { } : encoding.GetBytes(tokenInformationParam);
                byte[] proverInformation = (proverInformationParam == null) ? new byte[] { } : encoding.GetBytes(proverInformationParam);

                // specify the number of tokens to issue
                int numberOfTokens = numberOfTokensParam;

                IssuerParameters ip = ConvertUtils.convertIssuerParametersComposite(ipc, sessionDB[sessionID]);

                // Convert serializable FirstIssuanceMessageComposite members to FirstIssuanceMessage
                FirstIssuanceMessage fi = ConvertUtils.convertFirstIssuanceMessageComposite(firstMessage, ip);

                // setup the prover and generate the second issuance message
                Prover prover = new Prover(ip, numberOfTokens, attributes, tokenInformation, proverInformation, sessionDB[sessionID].deviceManager.GetDevice());

                // Store the prover in proversDictionary using the sessionKey as key
                sessionDB[sessionID].prover = prover;

                SecondIssuanceMessage sm = prover.GenerateSecondMessage(fi);

                // Convert SecondIssuanceMessage members to serializable SecondIssuanceMessageComposite
                SecondIssuanceMessageComposite smc = ConvertUtils.convertSecondIssuanceMessage(sm);

                // Add the sessionKey to SecondIssuanceMessageComposite
                smc.SessionKey = sessionID;

                return(smc);
            }
            catch (Exception e)
            {
                cOut.write(e.ToString());
                DebugUtils.DebugPrint(e.StackTrace.ToString());
            }

            return(null);
        }
Beispiel #10
0
        public void RandomZero()
        {
            var mockRandom = new MockRandom();

            mockRandom.GetScalarResults.Add(Scalar.Zero);

            // Don't tolerate if the second zero scalar random is received.
            mockRandom.GetScalarResults.Add(Scalar.Zero);

            Assert.ThrowsAny <InvalidOperationException>(() => Prover.CreateProof(new KnowledgeOfDlogParams(Scalar.One, new Statement(Scalar.One * Generators.G, Generators.G)), mockRandom));
        }
Beispiel #11
0
        public void RandomOverflow()
        {
            var mockRandom = new MockRandom();

            foreach (var scalar in CryptoHelpers.GetScalars(x => x.IsOverflow))
            {
                mockRandom.GetScalarResults.Add(scalar);

                Assert.ThrowsAny <InvalidOperationException>(() => Prover.CreateProof(new KnowledgeOfDlogParams(Scalar.One, new Statement(Scalar.One * Generators.G, Generators.G)), mockRandom));
            }
        }
Beispiel #12
0
        public void CollaborativeIssuanceTest()
        {
            // Issuer setup
            IssuerSetupParameters isp = new IssuerSetupParameters();

            isp.UidP = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
            isp.E    = new byte[] { (byte)1, (byte)1, (byte)1, (byte)1 };
            isp.UseRecommendedParameterSet = true;
            isp.S = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
            IssuerKeyAndParameters ikap = isp.Generate();
            IssuerParameters       ip   = ikap.IssuerParameters;

            // Issuance

            byte[][] attributes        = new byte[][] { encoding.GetBytes("Attribute 1"), encoding.GetBytes("Attribute 2"), encoding.GetBytes("Attribute 3"), encoding.GetBytes("Attribute 4") };
            byte[]   tokenInformation  = new byte[] { };
            byte[]   proverInformation = new byte[] { };
            int      numberOfTokens    = 2;

            // Test cases
            // 1: CA-RA split (a party trusted by the issuer provides the gamma value)
            int numTestCases = 1;

            for (int testCase = 1; testCase <= numTestCases; testCase++)
            {
                ProverProtocolParameters ppp = new ProverProtocolParameters(ip);
                ppp.Attributes        = attributes;
                ppp.NumberOfTokens    = numberOfTokens;
                ppp.TokenInformation  = tokenInformation;
                ppp.ProverInformation = proverInformation;
                Prover prover = ppp.CreateProver();

                IssuerProtocolParameters ipp = new IssuerProtocolParameters(ikap);
                if (testCase == 1)
                {
                    ipp.Gamma = ProtocolHelper.ComputeIssuanceInput(ip, attributes, tokenInformation, null);
                }
                ipp.NumberOfTokens = numberOfTokens;
                Issuer issuer = ipp.CreateIssuer();

                FirstIssuanceMessage  msg1 = issuer.GenerateFirstMessage();
                SecondIssuanceMessage msg2 = prover.GenerateSecondMessage(msg1);
                ThirdIssuanceMessage  msg3 = issuer.GenerateThirdMessage(msg2);
                UProveKeyAndToken[]   upkt = prover.GenerateTokens(msg3);

                // use the token to make sure everything is ok
                int[]             disclosed = new int[0];
                byte[]            message   = encoding.GetBytes("this is the presentation message, this can be a very long message");
                FieldZqElement[]  unused;
                byte[]            scope = null;
                PresentationProof proof = PresentationProof.Generate(ip, disclosed, null, 1, scope, message, null, null, upkt[0], attributes, out unused);
                proof.Verify(ip, disclosed, null, 1, scope, message, null, upkt[0].Token);
            }
        }
Beispiel #13
0
        /// <summary>
        /// Returns provers password.
        /// </summary>
        /// <returns>The password.</returns>
        /// <param name="password">Password.</param>
        /// <param name="version">Version.</param>
        public string ProverPassword(SecureString password, int version)
        {
            Guard.Argument(password, nameof(password)).NotNull();
            Guard.Argument(version, nameof(version)).NotNegative();

            using (var insecurePassword = password.Insecure())
            {
                var hash = Cryptography.GenericHashNoKey($"{version} {insecurePassword.Value}");
                return(Prover.GetHashStringNumber(hash).ToByteArray().ToHex());
            }
        }
        public void End2EndVerificationSimple(uint scalarSeed)
        {
            var secret          = new Scalar(scalarSeed);
            var generator       = Generators.G;
            var publicPoint     = secret * generator;
            var statement       = new Statement(publicPoint, generator);
            var knowledgeParams = new KnowledgeOfDlogParams(secret, statement);
            var proof           = Prover.CreateProof(knowledgeParams);

            Assert.True(Verifier.Verify(proof, statement));
        }
 public void End2EndVerification()
 {
     foreach (var secret in CryptoHelpers.GetScalars(x => !x.IsOverflow && !x.IsZero))
     {
         var generator       = Generators.G;
         var publicPoint     = secret * generator;
         var statement       = new Statement(publicPoint, generator);
         var knowledgeParams = new KnowledgeOfDlogParams(secret, statement);
         var proof           = Prover.CreateProof(knowledgeParams);
         Assert.True(Verifier.Verify(proof, statement));
     }
 }
Beispiel #16
0
        /// <summary>
        /// Returns provers password.
        /// </summary>
        /// <returns>The password.</returns>
        /// <param name="password">Password.</param>
        /// <param name="version">Version.</param>
        public string ProverPassword(SecureString password, int version)
        {
            if (password == null)
            {
                throw new ArgumentNullException(nameof(password));
            }

            using (var insecurePassword = password.Insecure())
            {
                var hash = Cryptography.GenericHashNoKey(string.Format("{0} {1}", version, insecurePassword.Value));

                return(Prover.GetHashStringNumber(hash).ToByteArray().ToHex());
            }
        }
Beispiel #17
0
 UProveKeyAndToken[] IssueSourceToken(byte[][] attributes)
 {
     byte[] tokenInformation = new byte[] { };
     IssuerProtocolParameters ipp = new IssuerProtocolParameters(sourceIkap);
     ipp.Attributes = attributes;
     ipp.TokenInformation = tokenInformation;
     Issuer issuer = ipp.CreateIssuer();
     FirstIssuanceMessage msg1 = issuer.GenerateFirstMessage();
     ProverProtocolParameters ppp = new ProverProtocolParameters(sourceIp);
     ppp.Attributes = attributes;
     ppp.TokenInformation = tokenInformation;
     Prover prover = ppp.CreateProver();
     SecondIssuanceMessage msg2 = prover.GenerateSecondMessage(msg1);
     ThirdIssuanceMessage msg3 = issuer.GenerateThirdMessage(msg2);
     return prover.GenerateTokens(msg3);
 }
Beispiel #18
0
        public List <UProveKeyAndTokenComposite> generateTokens(ThirdIssuanceMessageComposite thirdMessage, string sessionID)
        {
            /*
             *  token issuance - generate tokens.
             */

            cOut.write("Issuing U-Prove tokens - generate tokens, prover side");
            VerifySessionId(sessionID);

            try
            {
                // Convert serializable ThirdIssuanceMessageComposite members to ThirdIssuanceMessage.
                ThirdIssuanceMessage tm = ConvertUtils.convertThirdIssuanceMessageComposite(thirdMessage);

                // Retrieve correct Prover instance from proversDictionary for the given sessionKey.
                if (sessionDB.ContainsKey(sessionID))
                {
                    Prover prover = sessionDB[sessionID].prover;
                    // generate the tokens.
                    UProveKeyAndToken[] upkt = prover.GenerateTokens(tm);

                    // Serialize them.
                    cOut.write("Generating tokens...");

                    List <UProveKeyAndTokenComposite> tokens = new List <UProveKeyAndTokenComposite>();

                    foreach (UProveKeyAndToken t in upkt)
                    {
                        byte[] bigInt = t.PrivateKey.ToByteArray();
                        UProveKeyAndTokenComposite keyAndTokenComposite = new UProveKeyAndTokenComposite();
                        keyAndTokenComposite.PrivateKey = bigInt;
                        keyAndTokenComposite.Token      = ConvertUtils.convertUProveToken(t.Token);
                        tokens.Add(keyAndTokenComposite);
                    }

                    return(tokens);
                }
            }
            catch (Exception e)
            {
                cOut.write(e.ToString());
                DebugUtils.DebugPrint(e.StackTrace.ToString());
            }

            return(null);
        }
Beispiel #19
0
        private void RunProtocol(IssuerKeyAndParameters ikap, IssuerParameters ip)
        {
            ip.Verify(); // sanity check

            // Issuance
            int numberOfAttribs = ip.G.Length - 2; // minus g_0 and g_t

            byte[][] attributes = new byte[numberOfAttribs][];
            for (int i = 0; i < numberOfAttribs; i++)
            {
                attributes[i] = new byte[] { (byte)i };
            }
            byte[] tokenInformation  = new byte[] { 0x01 };
            byte[] proverInformation = new byte[] { 0x01 };
            int    numberOfTokens    = 1;

            IssuerProtocolParameters ipp = new IssuerProtocolParameters(ikap);

            ipp.Attributes       = attributes;
            ipp.NumberOfTokens   = numberOfTokens;
            ipp.TokenInformation = tokenInformation;
            Issuer issuer = ipp.CreateIssuer();
            FirstIssuanceMessage     msg1 = issuer.GenerateFirstMessage();
            ProverProtocolParameters ppp  = new ProverProtocolParameters(ip);

            ppp.NumberOfTokens    = numberOfTokens;
            ppp.Attributes        = attributes;
            ppp.TokenInformation  = tokenInformation;
            ppp.ProverInformation = proverInformation;
            Prover prover = ppp.CreateProver();
            SecondIssuanceMessage msg2 = prover.GenerateSecondMessage(msg1);
            ThirdIssuanceMessage  msg3 = issuer.GenerateThirdMessage(msg2);

            // issue token
            UProveKeyAndToken[] upkt = prover.GenerateTokens(msg3);

            // Presentation
            int[]  disclosed = new int[] { 1 };
            byte[] message   = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9 };

            // generate the presentation proof
            PresentationProof proof = PresentationProof.Generate(new ProverPresentationProtocolParameters(ip, disclosed, message, upkt[0], attributes));

            // verify the presentation proof
            proof.Verify(new VerifierPresentationProtocolParameters(ip, disclosed, message, upkt[0].Token));
        }
        public void End2EndVerificationSimple(uint scalarSeed1, uint scalarSeed2)
        {
            var secrets     = new[] { new Scalar(scalarSeed1), new Scalar(scalarSeed2) };
            var generators  = new[] { Generators.G, Generators.Ga };
            var publicPoint = GroupElement.Infinity;

            foreach (var(secret, generator) in secrets.ZipForceEqualLength(generators))
            {
                publicPoint += secret * generator;
            }

            var statement = new Statement(publicPoint, generators);
            var knowledge = new KnowledgeOfRepParams(secrets, statement);
            var proof     = Prover.CreateProof(knowledge);

            Assert.True(Verifier.Verify(proof, statement));
        }
Beispiel #21
0
        public void TestIssuerStateExport()
        {
            IssuerKeyAndParameters   ikap;
            IssuerProtocolParameters ipp;
            ProverProtocolParameters ppp;

            StaticTestHelpers.GenerateTestIssuanceParameters("test issuer params", "test spec", 3, true, 6, out ikap, out ipp, out ppp);

            // generate test issuer parameters
            Issuer           issuer = ipp.CreateIssuer();
            IssuerParameters ip     = ikap.IssuerParameters;
            Prover           prover = ppp.CreateProver();

            FirstIssuanceMessage  msg1 = null;
            SecondIssuanceMessage msg2 = null;
            ThirdIssuanceMessage  msg3 = null;

            msg1 = issuer.GenerateFirstMessage();
            PostFirstMessageState state = issuer.ExportPostFirstMessageState();
            string serializedState      = ikap.IssuerParameters.Serialize(state);

            msg2 = prover.GenerateSecondMessage(msg1);

            // make sure the original issuer is unusable
            try
            {
                issuer.GenerateThirdMessage(msg2);
                Assert.Fail();
            }
            catch (Exception)
            {
                // expected
            }

            // complete the issuance with a new issuer instance
            Issuer issuer2 = new Issuer(ikap, ikap.IssuerParameters.Deserialize <PostFirstMessageState>(serializedState));

            msg3 = issuer2.GenerateThirdMessage(msg2);
            // make sure tokens are valid by completing the issuance
            prover.GenerateTokens(msg3);
        }
        public void End2EndVerification()
        {
            var goodScalars = CryptoHelpers.GetScalars(x => !x.IsOverflow && !x.IsZero);

            foreach (var secret1 in goodScalars)
            {
                foreach (var secret2 in goodScalars.Where(x => x != secret1))
                {
                    var secrets     = new[] { secret1, secret2 };
                    var generators  = new[] { Generators.G, Generators.Ga };
                    var publicPoint = GroupElement.Infinity;
                    foreach (var(secret, generator) in secrets.ZipForceEqualLength(generators))
                    {
                        publicPoint += secret * generator;
                    }
                    Statement statement = new Statement(publicPoint, generators);
                    var       knowledge = new KnowledgeOfRepParams(secrets, statement);
                    var       proof     = Prover.CreateProof(knowledge);
                    Assert.True(Verifier.Verify(proof, statement));
                }
            }
        }
Beispiel #23
0
        public void DrillDown()
        {
            if (_wear > 100)
            {
                Random rnd = new Random();
                if (rnd.Next(1, 5) == 1)
                {
                    return;
                }
            }
            Speciman search = PGC.TakeSpecimanAt(GameMain.newPoint2D(Prover.Location.X, Prover.Location.Y));

            if (search != null)
            {
                Prover.AddSpeciman(search);
                _wear += 5;
            }
            else
            {
                _wear += 10;
            }
        }
Beispiel #24
0
        public GenerateTokensInfo GenerateTokens(GenerateTokensSpec spec)
        {
            // first we will try to lookup the cache value of the prover object.
            Prover prover = null;

            if (spec.ProverInstanceID != null)
            {
                ProverInstanceData proverInstance;
                bool ok = proverInstanceDB.TryGetValue(spec.ProverInstanceID, out proverInstance);
                if (ok)
                {
                    prover = proverInstance.Prover;
                }
                else
                {
                    //XXX add log about Prover not found in cache.
                }
            }

            if (prover != null)
            {
                return(HandleGenerateTokens(prover, spec.ThirdMessage));
            }

            if (spec.SecondMessageState != null && spec.IssuerParameter != null)
            {
                prover = new Prover(spec.IssuerParameter, spec.SecondMessageState);
                proverInstanceDB.TryAdd(spec.ProverInstanceID, new ProverInstanceData(prover));
                return(HandleGenerateTokens(prover, spec.ThirdMessage));
            }

            ApiArgumentFault fault = new ApiArgumentFault();

            fault.Details       = "Prover with unique ID was found or SecondMessageState and IssuerParameter not provided.";
            fault.Argument      = "GenerateTokensSpec.ProverInstanceID/GenerateTokensSpec.SecondMessageState/GenerateTokensSpec.IssuerParameter";
            fault.ArgumentValue = spec.ProverInstanceID.ToString();
            throw new FaultException <ApiArgumentFault>(fault);
        }
        public void End2EndVerificationLargeScalar()
        {
            uint val             = int.MaxValue;
            var  gen             = new Scalar(4) * Generators.G;
            var  secret          = new Scalar(val, val, val, val, val, val, val, val);
            var  p               = secret * gen;
            var  statement       = new Statement(p, gen);
            var  knowledgeParams = new KnowledgeOfDlogParams(secret, statement);
            var  proof           = Prover.CreateProof(knowledgeParams);

            Assert.True(Verifier.Verify(proof, statement));

            secret          = EC.N + (new Scalar(1)).Negate();
            p               = secret * gen;
            statement       = new Statement(p, gen);
            knowledgeParams = new KnowledgeOfDlogParams(secret, statement);
            proof           = Prover.CreateProof(knowledgeParams);
            Assert.True(Verifier.Verify(proof, statement));

            secret          = EC.NC;
            p               = secret * gen;
            statement       = new Statement(p, gen);
            knowledgeParams = new KnowledgeOfDlogParams(secret, statement);
            proof           = Prover.CreateProof(knowledgeParams);
            Assert.True(Verifier.Verify(proof, statement));
            secret          = EC.NC + new Scalar(1);
            p               = secret * gen;
            statement       = new Statement(p, gen);
            knowledgeParams = new KnowledgeOfDlogParams(secret, statement);
            proof           = Prover.CreateProof(knowledgeParams);
            Assert.True(Verifier.Verify(proof, statement));
            secret          = EC.NC + (new Scalar(1)).Negate();
            p               = secret * gen;
            statement       = new Statement(p, gen);
            knowledgeParams = new KnowledgeOfDlogParams(secret, statement);
            proof           = Prover.CreateProof(knowledgeParams);
            Assert.True(Verifier.Verify(proof, statement));
        }
        private void RunFuzzedTest(bool useSubgroupConstruction, string hashFunction, int numberOfAttributes, bool supportDevice, int numberOfTokens, int[] dArray, int[] cArray, int pseudonymIndex)
        {
            // Issuer setup
            IssuerSetupParameters isp = new IssuerSetupParameters(numberOfAttributes);

            isp.GroupConstruction = useSubgroupConstruction ? GroupType.Subgroup : GroupType.ECC;
            isp.UidP = GetRandomBytes(MaxByteArrayLength);
            isp.UidH = hashFunction;
            //isp.E = IssuerSetupParameters.GetDefaultEValues(numberOfAttributes);  // extension by Fablei -> do not change MaxNumberOfAttributes
            isp.S = GetRandomBytes(MaxByteArrayLength);
            IssuerKeyAndParameters ikap = isp.Generate(supportDevice);
            IssuerParameters       ip   = ikap.IssuerParameters;

            ip.Verify();

            IDevice      device = null;
            GroupElement hd     = null;

            if (supportDevice)
            {
                device = new VirtualDevice(ip);
                hd     = device.GetDevicePublicKey();
            }

            // Issuance
            byte[][] attributes = new byte[numberOfAttributes][];
            for (int index = 0; index < numberOfAttributes; index++)
            {
                attributes[index] = GetRandomBytes(MaxByteArrayLength);
            }
            byte[] tokenInformation  = GetRandomBytes(MaxByteArrayLength);
            byte[] proverInformation = GetRandomBytes(MaxByteArrayLength);

            IssuerProtocolParameters ipp = new IssuerProtocolParameters(ikap);

            ipp.Attributes       = attributes;
            ipp.NumberOfTokens   = numberOfTokens;
            ipp.TokenInformation = tokenInformation;
            ipp.DevicePublicKey  = hd;
            Issuer issuer = ipp.CreateIssuer();

            string msg1 = ip.Serialize(issuer.GenerateFirstMessage());

            ProverProtocolParameters ppp = new ProverProtocolParameters(ip);

            ppp.Attributes        = attributes;
            ppp.NumberOfTokens    = numberOfTokens;
            ppp.TokenInformation  = tokenInformation;
            ppp.ProverInformation = proverInformation;
            ppp.DevicePublicKey   = hd;
            Prover prover = ppp.CreateProver();
            string msg2   = ip.Serialize(prover.GenerateSecondMessage(ip.Deserialize <FirstIssuanceMessage>(msg1)));
            string msg3   = ip.Serialize(issuer.GenerateThirdMessage(ip.Deserialize <SecondIssuanceMessage>(msg2)));

            // issue token
            UProveKeyAndToken[] upkt = prover.GenerateTokens(ip.Deserialize <ThirdIssuanceMessage>(msg3));

            // Presentation
            byte[] message       = GetRandomBytes(MaxByteArrayLength);
            byte[] deviceMessage = null;
            IDevicePresentationContext deviceContext = null;

            if (supportDevice)
            {
                deviceMessage = GetRandomBytes(MaxByteArrayLength);
                deviceContext = device.GetPresentationContext();
            }
            int tokenIndex = random.Next(upkt.Length);

            // generate the presentation proof
            PresentationProof proof = PresentationProof.Generate(ip, dArray, message, deviceMessage, deviceContext, upkt[tokenIndex], attributes);

            // verify the presentation proof
            proof.Verify(ip, dArray, message, deviceMessage, upkt[tokenIndex].Token);
        }
        public void PseudonymAndCommitmentsTest()
        {
            // Issuer setup
            IssuerSetupParameters isp = new IssuerSetupParameters(maxNumberOfAttributes);

            isp.UidP = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
            isp.E    = new byte[] { (byte)1, (byte)1, (byte)1, (byte)1 };
            isp.UseRecommendedParameterSet = true;
            isp.S = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
            IssuerKeyAndParameters ikap = isp.Generate();
            IssuerParameters       ip   = ikap.IssuerParameters;

            // Issuance
            byte[][] attributes        = new byte[][] { encoding.GetBytes("Attribute 1"), encoding.GetBytes("Attribute 2"), encoding.GetBytes("Attribute 3"), encoding.GetBytes("Attribute 4") };
            byte[]   tokenInformation  = new byte[] { };
            byte[]   proverInformation = new byte[] { };
            int      numberOfTokens    = 1;

            IssuerProtocolParameters ipp = new IssuerProtocolParameters(ikap);

            ipp.Attributes       = attributes;
            ipp.NumberOfTokens   = numberOfTokens;
            ipp.TokenInformation = tokenInformation;
            Issuer issuer = ipp.CreateIssuer();
            FirstIssuanceMessage     msg1 = issuer.GenerateFirstMessage();
            ProverProtocolParameters ppp  = new ProverProtocolParameters(ip);

            ppp.Attributes        = attributes;
            ppp.NumberOfTokens    = numberOfTokens;
            ppp.TokenInformation  = tokenInformation;
            ppp.ProverInformation = proverInformation;
            Prover prover = ppp.CreateProver();
            SecondIssuanceMessage msg2 = prover.GenerateSecondMessage(msg1);
            ThirdIssuanceMessage  msg3 = issuer.GenerateThirdMessage(msg2);

            UProveKeyAndToken[] upkt = prover.GenerateTokens(msg3);

            // Pseudonym
            int[]             disclosed = new int[0];
            int[]             committed = new int[] { 2, 4 };
            byte[]            message   = encoding.GetBytes("this is the presentation message, this can be a very long message");
            byte[]            scope     = encoding.GetBytes("scope");
            PresentationProof proof;

            FieldZqElement[] tildeO;

            // Valid presentation
            proof = PresentationProof.Generate(ip, disclosed, committed, 1, scope, message, null, null, upkt[0], attributes, out tildeO);
            proof.Verify(ip, disclosed, committed, 1, scope, message, null, upkt[0].Token);

            // Invalid pseudonym (wrong scope)
            proof = PresentationProof.Generate(ip, disclosed, committed, 1, scope, message, null, null, upkt[0], attributes, out tildeO);
            try { proof.Verify(ip, disclosed, committed, 1, encoding.GetBytes("bad scope"), message, null, upkt[0].Token); Assert.Fail(); }
            catch (InvalidUProveArtifactException) { }

            // Invalid pseudonym (wrong attribute)
            try { proof.Verify(ip, disclosed, committed, 2, scope, message, null, upkt[0].Token); Assert.Fail(); }
            catch (InvalidUProveArtifactException) { }

            // Invalid commitment (null list)
            try { proof.Verify(ip, disclosed, null, 2, scope, message, null, upkt[0].Token); Assert.Fail(); }
            catch (InvalidUProveArtifactException) { }

            // Invalid commitment (wrong committed values)
            try { proof.Verify(ip, disclosed, new int[] { 1, 4 }, 2, scope, message, null, upkt[0].Token); Assert.Fail(); }
            catch (InvalidUProveArtifactException) { }

            // Invalid commitment (wront number of committed values)
            try { proof.Verify(ip, disclosed, new int[] { 1 }, 2, scope, message, null, upkt[0].Token); Assert.Fail(); }
            catch (InvalidUProveArtifactException) { }

            // Invalid commitment (value)
            proof.Commitments[0].TildeA[0]++;
            try { proof.Verify(ip, disclosed, committed, 2, scope, message, null, upkt[0].Token); Assert.Fail(); }
            catch (InvalidUProveArtifactException) { }

            // Ensure tildeO is correct
            GroupElement   Cx2     = proof.Commitments[0].TildeC;                    // x2 is the first committed attribute
            FieldZqElement x2      = ProtocolHelper.ComputeXi(ip, 1, attributes[1]); // attributes[] is zero indexed.
            FieldZqElement tildeO2 = tildeO[0];
            // double check that Cx2 is computed correctly.
            GroupElement Cx2Prime = ip.Gq.MultiExponentiate(new GroupElement[] { ip.Gq.G, ip.G[1] }, new FieldZqElement[] { x2, tildeO2 });

            Assert.IsTrue(Cx2Prime.Equals(Cx2));
        }
        public void FiatShamirComposition()
        {
            var rnd = new MockRandom();

            rnd.GetBytesResults.Add(new byte[32]);
            rnd.GetBytesResults.Add(new byte[32]);

            var witness1 = new ScalarVector(Scalar.One);
            var witness2 = new ScalarVector(Scalar.One + Scalar.One);

            var g = new GroupElementVector(Generators.G);

            var publicPoint1 = witness1 * g;
            var publicPoint2 = witness2 * g;

            var statement1 = new Statement(new Equation(publicPoint1, g));
            var statement2 = new Statement(new Equation(publicPoint2, g));

            var prover1 = new Prover(new Knowledge(statement1, witness1));
            var prover2 = new Prover(new Knowledge(statement2, witness2));

            var proverTranscript   = new WalletWasabi.Crypto.ZeroKnowledge.Transcript(new byte[0]);
            var verifierTranscript = proverTranscript.MakeCopy();

            var prover1Nonces = prover1.CommitToStatements(proverTranscript);
            var prover2Nonces = prover2.CommitToStatements(proverTranscript);

            var prover1Respond = prover1Nonces(rnd);
            var prover2Respond = prover2Nonces(rnd);

            var proof1 = prover1Respond();
            var proof2 = prover2Respond();

            var verifier1 = new Verifier(statement1);
            var verifier2 = new Verifier(statement2);

            // First, verify as a compound proof
            var correctVerifierTranscript = verifierTranscript.MakeCopy();
            var correctVerifier1Nonces    = verifier1.CommitToStatements(correctVerifierTranscript);
            var correctVerifier2Nonces    = verifier2.CommitToStatements(correctVerifierTranscript);
            var correctVerifier1Verify    = correctVerifier1Nonces(proof1);
            var correctVerifier2Verify    = correctVerifier2Nonces(proof2);

            Assert.True(correctVerifier1Verify());
            Assert.True(correctVerifier2Verify());

            // If the verifiers are not run interleaved, they should reject.
            var notInterleavedVerifierTranscript = verifierTranscript.MakeCopy();
            var notInterleavedVerifier1Nonces    = verifier1.CommitToStatements(correctVerifierTranscript);
            var notInterleavedVerifier1Verify    = notInterleavedVerifier1Nonces(proof1);

            Assert.False(notInterleavedVerifier1Verify());
            var notInterleavedVerifier2Nonces = verifier2.CommitToStatements(correctVerifierTranscript);
            var notInterleavedVerifier2Verify = notInterleavedVerifier2Nonces(proof2);

            Assert.False(notInterleavedVerifier2Verify());

            // If the verifiers are run independently (without sharing a transcript),
            // they should reject.
            var incompleteTranscript1 = verifierTranscript.MakeCopy();
            var incompleteTranscript2 = verifierTranscript.MakeCopy();
            var incompleteTranscriptVerifier1Nonces = verifier1.CommitToStatements(incompleteTranscript1);
            var incompleteTranscriptVerifier2Nonces = verifier2.CommitToStatements(incompleteTranscript2);
            var incompleteTranscriptVerifier1Verify = incompleteTranscriptVerifier1Nonces(proof1);
            var incompleteTranscriptVerifier2Verify = incompleteTranscriptVerifier2Nonces(proof2);

            Assert.False(incompleteTranscriptVerifier1Verify());
            Assert.False(incompleteTranscriptVerifier2Verify());

            // If the sub-proofs are swapped between the verifiers, they should reject.
            var incorrectProofVerifierTranscript = verifierTranscript.MakeCopy();
            var incorrectProofVerifier1Nonces    = verifier1.CommitToStatements(correctVerifierTranscript);
            var incorrectProofVerifier2Nonces    = verifier2.CommitToStatements(correctVerifierTranscript);
            var incorrectProofVerifier1Verify    = incorrectProofVerifier1Nonces(proof2);
            var incorrectProofVerifier2Verify    = incorrectProofVerifier2Nonces(proof1);

            Assert.False(incorrectProofVerifier1Verify());
            Assert.False(incorrectProofVerifier2Verify());

            // If the order of the verifiers is changed, they should reject.
            var incorrectOrderVerifierTranscript = verifierTranscript.MakeCopy();
            var incorrectOrderVerifier1Nonces    = verifier1.CommitToStatements(correctVerifierTranscript);
            var incorrectOrderVerifier2Nonces    = verifier2.CommitToStatements(correctVerifierTranscript);
            var incorrectOrderVerifier2Verify    = incorrectOrderVerifier2Nonces(proof2);
            var incorrectOrderVerifier1Verify    = incorrectOrderVerifier1Nonces(proof1);

            Assert.False(incorrectOrderVerifier1Verify());
            Assert.False(incorrectOrderVerifier2Verify());

            // If the proofs are committed to the transcript in the right order but
            // with the wrong verifier (combination of previous two cases) they should
            // reject.
            var incorrectOrderAndProofVerifierTranscript = verifierTranscript.MakeCopy();
            var incorrectOrderAndProofVerifier1Nonces    = verifier1.CommitToStatements(correctVerifierTranscript);
            var incorrectOrderAndProofVerifier2Nonces    = verifier2.CommitToStatements(correctVerifierTranscript);
            var incorrectOrderAndProofVerifier2Verify    = incorrectOrderAndProofVerifier2Nonces(proof1);
            var incorrectOrderAndProofVerifier1Verify    = incorrectOrderAndProofVerifier1Nonces(proof2);

            Assert.False(incorrectOrderAndProofVerifier2Verify());
            Assert.False(incorrectOrderAndProofVerifier1Verify());
        }
Beispiel #29
0
 internal ProverInstanceData(Prover issuer)
 {
     this.LastAccessed = DateTime.Now;
     _prover           = issuer;
 }
        private static string CreateClientToken(SigningCredentials credential, string clientId, string audience,
                                                List <string> rootCertSubject,
                                                UiLambdaSet uiLambda = null)
        {
            // oz
            //// string x5c = "";
            string[]         x5c          = null;
            string           certFileName = certPfx;
            string           password     = certPfxPW;
            X509Certificate2 certificate  = null;

            if (credential == null)
            {
                var res = UiLambdaSet.MesssageBoxShow(uiLambda, "",
                                                      "Select certificate chain from certificate store? \n" +
                                                      "(otherwise use file Andreas_Orzelski_Chain.pfx)",
                                                      "Select certificate chain", MessageBoxButtons.YesNo);

                if (res == DialogResult.No)
                {
                    certFileName = "Andreas_Orzelski_Chain.pfx";
                    password     = "******";
                    credential   = new X509SigningCredentials(new X509Certificate2(certFileName, password));
                }
            }

            if (credential == null)
            {
                X509Store store = new X509Store("MY", StoreLocation.CurrentUser);
                store.Open(OpenFlags.ReadOnly | OpenFlags.OpenExistingOnly);

                X509Certificate2Collection collection  = (X509Certificate2Collection)store.Certificates;
                X509Certificate2Collection fcollection = (X509Certificate2Collection)collection.Find(
                    X509FindType.FindByTimeValid, DateTime.Now, false);

                Boolean rootCertFound = false;
                X509Certificate2Collection fcollection2 = new X509Certificate2Collection();
                foreach (X509Certificate2 fc in fcollection)
                {
                    X509Chain fch = new X509Chain();
                    fch.Build(fc);
                    foreach (X509ChainElement element in fch.ChainElements)
                    {
                        if (rootCertSubject.Contains(element.Certificate.Subject))
                        {
                            rootCertFound = true;
                            fcollection2.Add(fc);
                        }
                    }
                }
                if (rootCertFound)
                {
                    fcollection = fcollection2;
                }

                X509Certificate2Collection scollection = X509Certificate2UI.SelectFromCollection(fcollection,
                                                                                                 "Test Certificate Select",
                                                                                                 "Select a certificate from the following list to get information on that certificate",
                                                                                                 X509SelectionFlag.SingleSelection);
                if (scollection.Count != 0)
                {
                    certificate = scollection[0];
                    X509Chain ch = new X509Chain();
                    ch.Build(certificate);

                    string[] X509Base64 = new string[ch.ChainElements.Count];

                    int j = 0;
                    foreach (X509ChainElement element in ch.ChainElements)
                    {
                        X509Base64[j++] = Convert.ToBase64String(element.Certificate.GetRawCertData());
                    }

                    x5c = X509Base64;
                }
            }
            else
            {
                // use old fixed certificate chain
                X509Certificate2Collection xc = new X509Certificate2Collection();
                xc.Import(certFileName, password, X509KeyStorageFlags.PersistKeySet);

                string[] X509Base64 = new string[xc.Count];

                int j   = xc.Count;
                var xce = xc.GetEnumerator();
                for (int i = 0; i < xc.Count; i++)
                {
                    xce.MoveNext();
                    X509Base64[--j] = Convert.ToBase64String(xce.Current.GetRawCertData());
                }
                x5c = X509Base64;

                certificate = new X509Certificate2(certFileName, password);
            }

            string email   = "";
            string subject = certificate.Subject;
            var    split   = subject.Split(new Char[] { ',' });

            if (split[0] != "")
            {
                var split2 = split[0].Split(new Char[] { '=' });
                if (split2[0] == "E")
                {
                    email = split2[1];
                }
            }
            Console.WriteLine("email: " + email);

            //
            StringBuilder builder = new StringBuilder();

            builder.AppendLine("-----BEGIN CERTIFICATE-----");
            builder.AppendLine(
                Convert.ToBase64String(certificate.RawData, Base64FormattingOptions.InsertLineBreaks));
            builder.AppendLine("-----END CERTIFICATE-----");

            UiLambdaSet.MesssageBoxShow(uiLambda, builder.ToString(), "", "Client Certificate", MessageBoxButtons.OK);

            credential = new X509SigningCredentials(certificate);
            // oz end

            var now = DateTime.UtcNow;

            var token = new JwtSecurityToken(
                clientId,
                audience,
                new List <Claim>()
            {
                new Claim(JwtClaimTypes.JwtId, Guid.NewGuid().ToString()),
                new Claim(JwtClaimTypes.Subject, clientId),
                new Claim(JwtClaimTypes.IssuedAt, now.ToEpochTime().ToString(), ClaimValueTypes.Integer64),
                // OZ
                new Claim(JwtClaimTypes.Email, email)
                // new Claim("x5c", x5c)
            },
                now,
                now.AddMinutes(1),
                credential)
            ;

            token.Header.Add("x5c", x5c);
            if (ssiURL != "")
            {
                //// Prover prover = new Prover("http://192.168.178.33:5001"); //AASX Package Explorer
                Prover prover = new Prover(ssiURL); //AASX Package Explorer

                string invitation = prover.CreateInvitation();

                token.Header.Add("ssiInvitation", invitation);
            }
            // oz

            var tokenHandler = new JwtSecurityTokenHandler();

            return(tokenHandler.WriteToken(token));
        }