Пример #1
0
        public static void GenerateTestIssuanceParameters(string uidp, string spec, int numberOfAttributes, bool useRecommendedParameters, int numberOfTokens, out IssuerKeyAndParameters ikap, out IssuerProtocolParameters ipp, out ProverProtocolParameters ppp)
        {
            IssuerSetupParameters isp = new IssuerSetupParameters(maxNumberOfAttributes);

            isp.UidP = (uidp == null ? null : encoding.GetBytes(uidp));
            isp.E    = IssuerSetupParameters.GetDefaultEValues(numberOfAttributes);
            isp.UseRecommendedParameterSet = useRecommendedParameters;
            isp.S = (spec == null ? null : encoding.GetBytes(spec));
            ikap  = isp.Generate();
            IssuerParameters ip = ikap.IssuerParameters;

            // Issuance
            byte[][] attributes = new byte[numberOfAttributes][];
            for (int i = 0; i < numberOfAttributes; i++)
            {
                attributes[i] = encoding.GetBytes("attribute value " + (i + 1));
            }
            byte[] tokenInformation  = encoding.GetBytes("token information field");
            byte[] proverInformation = encoding.GetBytes("prover information field");

            ipp                  = new IssuerProtocolParameters(ikap);
            ipp.Attributes       = attributes;
            ipp.NumberOfTokens   = numberOfTokens;
            ipp.TokenInformation = tokenInformation;

            ppp                   = new ProverProtocolParameters(ip);
            ppp.Attributes        = attributes;
            ppp.NumberOfTokens    = numberOfTokens;
            ppp.TokenInformation  = tokenInformation;
            ppp.ProverInformation = proverInformation;
        }
Пример #2
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);
        }
        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];
        }
Пример #4
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) { }
        }
Пример #5
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)));
        }
Пример #6
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);
            }
        }
Пример #7
0
        public void TestIssuer()
        {
            byte[][] A  = new byte[][] {};
            byte[]   TI = null;
            IssuerSetupParameters isp = new IssuerSetupParameters();

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

            try { ipp = new IssuerProtocolParameters(null); Assert.Fail(); } catch (ArgumentNullException) { }
            try
            {
                ipp                  = new IssuerProtocolParameters(ikap);
                ipp.Attributes       = A;
                ipp.NumberOfTokens   = -1;
                ipp.TokenInformation = TI;
                ipp.Validate();
                Assert.Fail();
            } catch (ArgumentException) { }
            try
            {
                ipp                  = new IssuerProtocolParameters(ikap);
                ipp.Attributes       = A;
                ipp.NumberOfTokens   = 0;
                ipp.TokenInformation = TI;
                ipp.Validate();
                Assert.Fail();
            } catch (ArgumentException) { }
            ipp                  = new IssuerProtocolParameters(ikap);
            ipp.Attributes       = A;
            ipp.NumberOfTokens   = 1;
            ipp.TokenInformation = TI;
            ipp.Validate();
            Issuer issuer = ipp.CreateIssuer();

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

            try { msg3 = issuer.GenerateThirdMessage(msg2); Assert.Fail(); } catch (InvalidOperationException) { }
            msg1 = issuer.GenerateFirstMessage();
            try { msg1 = issuer.GenerateFirstMessage(); Assert.Fail(); } catch (InvalidOperationException) { }
            msg2 = new ProverProtocolParameters(ikap.IssuerParameters).CreateProver().GenerateSecondMessage(msg1);
            msg3 = issuer.GenerateThirdMessage(msg2);
            try { msg3 = issuer.GenerateThirdMessage(msg2); Assert.Fail(); } catch (InvalidOperationException) { }
        }
Пример #8
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);
 }
Пример #9
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 SetupIssuerParameters()
        {
            // Generate issuer parameters (need the group params)
            byte[][] A  = new byte[][] { };
            byte[]   TI = null;
            //byte[] PI = null;
            IssuerSetupParameters isp = new IssuerSetupParameters(maxNumberOfAttributes);

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

            ipp.Attributes       = A;
            ipp.NumberOfTokens   = 1;
            ipp.TokenInformation = TI;
            ip = ikap.IssuerParameters;
        }
        public FirstIssuanceMessageInfo FirstMessage(FirstIssuanceMessageSpec spec)
        {
            if (!issuerStore.HasValue(spec.IssuerID))
            {
                ApiArgumentFault fault = new ApiArgumentFault();
                fault.Details       = "Issuer with unique ID was found";
                fault.Argument      = "FirstIssuanceMessageSpec.IssuerID";
                fault.ArgumentValue = spec.IssuerID;
                throw new FaultException <ApiArgumentFault>(fault);
            }
            IssuerKeyAndParameters ikp = issuerStore.GetValue(spec.IssuerID);

            IssuerProtocolParameters ipp = new IssuerProtocolParameters(ikp);

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

            if (!String.IsNullOrWhiteSpace(spec.Gamma))
            {
                ipp.Gamma = ExtensionMethods.ToGroupElement(spec.Gamma, ikp.IssuerParameters);
            }

            if (!String.IsNullOrWhiteSpace(spec.DevicePublicKey))
            {
                ipp.DevicePublicKey = ExtensionMethods.ToGroupElement(spec.DevicePublicKey, ikp.IssuerParameters);
            }

            ipp.Validate();
            Issuer issuer = ipp.CreateIssuer();
            FirstIssuanceMessage     firstMessage = issuer.GenerateFirstMessage();
            FirstIssuanceMessageInfo ret          = new FirstIssuanceMessageInfo();

            ret.FirstMessage = firstMessage;
            Guid issuerInstance = Guid.NewGuid();

            ret.IssuerInstanceID  = issuerInstance;
            ret.FirstMessageState = issuer.ExportPostFirstMessageState();
            issuerInstanceDB.TryAdd(issuerInstance, new IssuerInstanceData(issuer));
            return(ret);
        }
        /// <summary>
        /// creates the first message for the given number of tokens
        /// </summary>
        /// <param name="numberOfTokens">number of token to issue</param>
        /// <param name="ti">token information field</param>
        /// <param name="devicePublicKey">public key from the provers device</param>
        /// <returns>first message as json string or if there was a failure, an empty string</returns>
        public string GenerateFirstMessage(int numberOfTokens, byte[] ti = null, GroupElement devicePublicKey = null)
        {
            try
            {
                LogService.Log(LogService.LogType.Info, "IssuingIssuer - GenerateFirstMessage called");

                IssuerProtocolParameters ipp = new IssuerProtocolParameters(ikap);
                ipp.Attributes       = ci.ConvertAttributeListToBase64ByteArray(attributes);
                ipp.NumberOfTokens   = numberOfTokens;
                ipp.TokenInformation = ti;

                // if it is device protected, device public key is needed here
                if (isDeviceProtected && devicePublicKey == null)
                {
                    throw new Exception("DevicePublicKey is null. First message creation abort.");
                }

                if (ipp.IssuerKeyAndParameters.IssuerParameters.IsDeviceSupported && devicePublicKey != null)
                {
                    ipp.DevicePublicKey = devicePublicKey;
                }

                issuer = ipp.CreateIssuer();
                // firstmessage for prover
                string firstMessageJson = ikap.IssuerParameters.Serialize <FirstIssuanceMessage>(
                    issuer.GenerateFirstMessage());

                LogService.Log(LogService.LogType.Info, "FirstMessage created: " + firstMessageJson);
                return(firstMessageJson);
            }
            catch (Exception e)
            {
                LogService.Log(LogService.LogType.FatalError, "IssuingIssuer - Error during first message generation.", e);
                throw new CommunicationException("IssuingIssuer - Error during first message generation.", e);
            }
        }
Пример #13
0
        public void TestSerialization()
        {
            // Create IssuerSetupParameters
            System.Text.UTF8Encoding encoding = new System.Text.UTF8Encoding();

            for (int i = 0; i <= 1; i++)
            {
                for (int j = 0; j <= 1; j++)
                {
                    bool useCustomGroup          = (i == 0);
                    bool useSubgroupConstruction = (j == 0);

                    IssuerSetupParameters isp = new IssuerSetupParameters();
                    if (useSubgroupConstruction)
                    {
                        isp.GroupConstruction = GroupType.Subgroup;
                        if (useCustomGroup)
                        {
                            byte[] p = HexToBytes("d21ae8d66e6c6b3ced0eb3df1a26c91bdeed013c17d849d30ec309813e4d3799f26db0d494e82ec61ea9fdc70bb5cbcaf2e5f18a836494f58e67c6d616480c37a7f2306101fc9f0f4768f9c9793c2be176b0b7c979b4065d3e835686a3f0b8420c6834cb17930386dedab2b07dd473449a48baab316286b421052475d134cd3b");
                            byte[] q = HexToBytes("fff80ae19daebc61f46356af0935dc0e81148eb1");
                            byte[] g = HexToBytes("abcec972e9a9dd8d133270cfeac26f726e567d964757630d6bd43460d0923a46aec0ace255ebf3ddd4b1c4264f53e68b361afb777a13cf0067dae364a34d55a0965a6cccf78852782923813cf8708834d91f6557d783ec75b5f37cd9185f027b042c1c72e121b1266a408be0bb7270d65917b69083633e1f3cd60624612fc8c1");
                            isp.Gq = SubgroupGroup.CreateSubgroupGroup(
                                p,
                                q,
                                g,
                                null,
                                null);
                            isp.UidH = "SHA1";
                        }
                    }
                    else
                    {
                        isp.GroupConstruction = GroupType.ECC;
                        if (useCustomGroup)
                        {
                            continue;
                        }
                    }

                    isp.UidP = encoding.GetBytes("http://issuer/uprove/issuerparams/software");
                    isp.E    = IssuerSetupParameters.GetDefaultEValues(3);
                    isp.S    = encoding.GetBytes("application-specific specification");

                    // Generate IssuerKeyAndParameters
                    IssuerKeyAndParameters ikap = isp.Generate();

                    // Create an IssuerParameters
                    IssuerParameters ip = ikap.IssuerParameters;

                    VerifySerialization(useCustomGroup, useSubgroupConstruction, ip, ikap);
                    VerifySerialization(useCustomGroup, useSubgroupConstruction, ip, ikap.IssuerParameters);

                    // specify the attribute values
                    byte[][] attributes = new byte[][] {
                        encoding.GetBytes("first attribute value"),
                        encoding.GetBytes("second attribute value"),
                        encoding.GetBytes("third attribute value")
                    };

                    // specify the special field values
                    byte[] tokenInformation  = encoding.GetBytes("token information value");
                    byte[] proverInformation = encoding.GetBytes("prover information value");

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

                    // setup the issuer and generate the first issuance message
                    IssuerProtocolParameters ipp = new IssuerProtocolParameters(ikap);
                    ipp.Attributes       = attributes;
                    ipp.NumberOfTokens   = numberOfTokens;
                    ipp.TokenInformation = tokenInformation;
                    Issuer issuer = ipp.CreateIssuer();
                    FirstIssuanceMessage firstMessage = issuer.GenerateFirstMessage();
                    VerifySerialization(useCustomGroup, useSubgroupConstruction, ip, firstMessage);

                    // setup the prover and generate the second issuance message
                    Prover prover = new Prover(ip, numberOfTokens, attributes, tokenInformation, proverInformation, null);
                    SecondIssuanceMessage secondMessage = prover.GenerateSecondMessage(firstMessage);
                    VerifySerialization(useCustomGroup, useSubgroupConstruction, ip, secondMessage);

                    // generate the third issuance message
                    ThirdIssuanceMessage thirdMessage = issuer.GenerateThirdMessage(secondMessage);
                    VerifySerialization(useCustomGroup, useSubgroupConstruction, ip, thirdMessage);

                    // generate the tokens
                    UProveKeyAndToken[] upkt = prover.GenerateTokens(thirdMessage);

                    for (int k = 0; k < upkt.Length; k++)
                    {
                        string            json          = ip.Serialize(upkt[k]);
                        UProveKeyAndToken upkt_fromJson = ip.Deserialize <UProveKeyAndToken>(json);
                        Assert.IsTrue(Verify(upkt[k], upkt_fromJson));
                    }

                    VerifySerialization(useCustomGroup, useSubgroupConstruction, ip, upkt[0].Token);

                    /*
                     *  token presentation
                     */
                    // the indices of disclosed attributes
                    int[] disclosed = new int[] { 2 };
                    // the indices of committed attributes
                    int[] committed = new int[] { 3 };
                    // the returned commitment randomizers, to be used by an external proof module
                    FieldZqElement[] tildeO;
                    // the application-specific message that the prover will sign. Typically this is a nonce combined
                    // with any application-specific transaction data to be signed.
                    byte[] message = encoding.GetBytes("message");
                    // the application-specific verifier scope from which a scope-exclusive pseudonym will be created
                    // (if null, then a pseudonym will not be presented)
                    byte[] scope = encoding.GetBytes("verifier scope");
                    // generate the presentation proof
                    PresentationProof proof = PresentationProof.Generate(ip, disclosed, committed, 1, scope, message, null, null, upkt[0], attributes, out tildeO);
                    VerifySerialization(useCustomGroup, useSubgroupConstruction, ip, proof);

                    // verify the presentation proof
                    proof.Verify(ip, disclosed, committed, 1, scope, message, null, upkt[0].Token);
                }
            }
        }
        public static void GetUProveParameters(
            bool hashAttributes,
            out ProverPresentationProtocolParameters proverParams,
            out VerifierPresentationProtocolParameters verifierParams,
            byte [] customTokenInformation   = null,
            byte [][] customAttributes       = null,
            GroupElement [] customGenerators = null,
            byte [] customUidP = null
            )
        {
            // Issuer setup
            IssuerSetupParameters isp = new IssuerSetupParameters(maxNumberOfAttributes);

            if (customUidP == null)
            {
                isp.UidP = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
            }
            else
            {
                isp.UidP = customUidP;
            }

            if (hashAttributes)
            {
                isp.E = _e1;
            }
            else
            {
                isp.E = _e0;
            }


            isp.S = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9 };

            if (customGenerators != null)
            {
                isp.ParameterSet = IssuerSetupParameters.GetDefaultParameterSet();
                PrivateObject customParams = new PrivateObject(isp.ParameterSet);
                customParams.SetField("G", customGenerators);
            }
            else
            {
                isp.UseRecommendedParameterSet = true;
            }

            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")
            };
            if (customAttributes != null)
            {
                attributes = customAttributes;
            }

            byte[] tokenInformation = new byte[] { };
            if (customTokenInformation != null)
            {
                tokenInformation = customTokenInformation;
            }
            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;
//            ppp.BatchValidationSecurityLevel = -1;
            Prover prover = ppp.CreateProver();
            SecondIssuanceMessage msg2 = prover.GenerateSecondMessage(msg1);
            ThirdIssuanceMessage  msg3 = issuer.GenerateThirdMessage(msg2);

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

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

            //Generate prover
            proverParams           = new ProverPresentationProtocolParameters(ip, disclosed, message, upkt[0], attributes);
            proverParams.Committed = committed;

            //Generate verifier
            verifierParams           = new VerifierPresentationProtocolParameters(ip, disclosed, message, upkt[0].Token);
            verifierParams.Committed = committed;
        }
Пример #15
0
        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));
        }
Пример #16
0
        public void CollaborativeIssuanceTestFull()
        {
            byte[][] attributes = new byte[][] { encoding.GetBytes("A1"), encoding.GetBytes("A2") };
            UProveKeyAndToken[] upkt = IssueSourceToken(attributes);

            // carry over one attribute to various positions
            for (int sourceIndex = 0; sourceIndex < attributes.Length; sourceIndex++)
            {
                for (int destinationIndex = 0; destinationIndex < 3; destinationIndex++)
                {
                    // Collaborative Issuance 
                    // First the Prover creates a PreIssuanceProof
                    int[] sourceIndices = new int[] { sourceIndex + 1 };
                    int[] destinationIndices = new int[] { destinationIndex + 1 };
                    ProverPreIssuanceParameters ppip = new ProverPreIssuanceParameters(ip);
                    ppip.Attributes = new byte[3][];
                    ppip.CarryOverAttribute(sourceIndices, destinationIndices, sourceIp, upkt[0], attributes); 
                    ppip.U = new int[] { ((destinationIndex + 1) % 3) + 1 };
                    ppip.K = new int[] { ((destinationIndex + 2) % 3) + 1 };
                    ppip.Attributes[destinationIndex] = attributes[sourceIndex];
                    ppip.Attributes[ppip.U[0] - 1] = encoding.GetBytes("unknown");
                    ppip.Attributes[ppip.K[0] - 1] = encoding.GetBytes("known");
                    byte[] message = encoding.GetBytes("Optional Message");

                    // The verifier will only have the token, not the keyAndToken 
                    IssuerPreIssuanceParameters ipip = new IssuerPreIssuanceParameters(ip);
                    ipip.Attributes = new byte[3][];
                    ipip.CarryOverAttribute(sourceIndices, destinationIndices, sourceIp, upkt[0].Token);
                    ipip.U = ppip.U;
                    ipip.K = ppip.K;
                    ipip.Attributes[destinationIndex] = null; // carried-over
                    ipip.Attributes[ppip.U[0] - 1] = null;
                    ipip.Attributes[ppip.K[0] - 1] = encoding.GetBytes("known");

                    PreIssuanceData pid = PreIssuance(ppip, ipip); 

                    // Issuance (collaborative, using blindedGamma)
                    IssuerProtocolParameters ipp2 = new IssuerProtocolParameters(ikap);
                    ipp2.Gamma = pid.Gamma;
                    Issuer issuer2 = ipp2.CreateIssuer();
                    FirstIssuanceMessage msg1_2 = issuer2.GenerateFirstMessage();

                    ProverProtocolParameters ppp2 = new ProverProtocolParameters(ip);
                    ppp2.SetBlindedGamma(pid.Gamma, pid.Beta0);
                    Prover prover2 = ppp2.CreateProver();
                    SecondIssuanceMessage msg2_2 = prover2.GenerateSecondMessage(msg1_2);
                    ThirdIssuanceMessage msg3_2 = issuer2.GenerateThirdMessage(msg2_2);
                    UProveKeyAndToken[] upkt_2 = prover2.GenerateTokens(msg3_2);

                    // Create a presentation proof for each token, disclosing everything, to make sure the new token works
                    for (int i = 0; i < upkt_2.Length; i++)
                    {
                        int[] disclosed = { 1, 2, 3 };
                        int[] committed = { };
                        PresentationProof P = PresentationProof.Generate(ip, disclosed, message, null, null, upkt_2[i], ppip.Attributes);
                        P.Verify(ip, disclosed, message, null, upkt_2[i].Token);
                        // verify that carried-over attribute was properly set
                        Assert.IsTrue(P.DisclosedAttributes[destinationIndex].SequenceEqual<byte>(attributes[sourceIndex]));
                        Assert.IsTrue(P.DisclosedAttributes[ppip.U[0] - 1].SequenceEqual<byte>(encoding.GetBytes("unknown")));
                        Assert.IsTrue(P.DisclosedAttributes[ppip.K[0] - 1].SequenceEqual<byte>(encoding.GetBytes("known")));
                    }
                }
            }
        }
Пример #17
0
        public void TestEndToEnd()
        {
            Random random          = new Random();
            int    attributeLength = 10;

            foreach (GroupType groupConstruction in groupConstructions)
            {
                foreach (string hashFunction in supportedHashFunctions)
                {
                    //Console.WriteLine("Hash = " + hashFunction);
                    for (int numberOfAttribs = 0; numberOfAttribs <= 3; numberOfAttribs++)
                    {
                        //Console.WriteLine("NumberOfAttribs = " + numberOfAttribs);
                        for (int e = 0; e <= 1; e++)
                        {
                            foreach (bool supportDevice in new bool[] { false, true })
                            {
                                // Issuer setup
                                IssuerSetupParameters isp = new IssuerSetupParameters(maxNumberOfAttributes);
                                isp.GroupConstruction = groupConstruction;
                                isp.UidP = encoding.GetBytes("unique UID");
                                isp.UidH = hashFunction;
                                isp.E    = new byte[numberOfAttribs];
                                for (int i = 0; i < numberOfAttribs; i++)
                                {
                                    isp.E[i] = (byte)e;
                                }
                                isp.S = encoding.GetBytes("specification");
                                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[numberOfAttribs][];
                                for (int index = 0; index < numberOfAttribs; index++)
                                {
                                    attributes[index] = new byte[attributeLength];
                                    random.NextBytes(attributes[index]);
                                }
                                byte[] tokenInformation  = encoding.GetBytes("token information");
                                byte[] proverInformation = encoding.GetBytes("prover information");
                                int    numberOfTokens    = (int)Math.Pow(2, numberOfAttribs);

                                IssuerProtocolParameters ipp = new IssuerProtocolParameters(ikap);
                                ipp.Attributes       = attributes;
                                ipp.NumberOfTokens   = numberOfTokens;
                                ipp.TokenInformation = tokenInformation;
                                ipp.DevicePublicKey  = hd;
                                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;
                                ppp.DevicePublicKey   = hd;
                                Prover prover = ppp.CreateProver();
                                SecondIssuanceMessage msg2 = prover.GenerateSecondMessage(msg1);
                                ThirdIssuanceMessage  msg3 = issuer.GenerateThirdMessage(msg2);
                                // issue token
                                UProveKeyAndToken[] upkt = prover.GenerateTokens(msg3);

                                // Presentation
                                for (int i = 0; i < numberOfTokens; i++)
                                {
                                    List <int> disclosedList = new List <int>();
                                    //Console.Write("Disclosed list = ");
                                    for (int index = 0; index < numberOfAttribs; index++)
                                    {
                                        if ((((int)Math.Pow(2, index)) & i) != 0)
                                        {
                                            //Console.Write((index + 1) + ", ");
                                            disclosedList.Add(index + 1);
                                        }
                                    }
                                    //Console.WriteLine();

                                    int[]  disclosed     = disclosedList.ToArray();
                                    byte[] message       = encoding.GetBytes("message");
                                    byte[] deviceMessage = null;
                                    IDevicePresentationContext deviceContext = null;
                                    if (supportDevice)
                                    {
                                        deviceMessage = encoding.GetBytes("message");
                                        deviceContext = device.GetPresentationContext();
                                    }

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

                                    // verify the presentation proof
                                    proof.Verify(ip, disclosed, message, deviceMessage, upkt[i].Token);

                                    //
                                    // negative cases
                                    //
                                    if (numberOfAttribs > 0)
                                    {
                                        // modify issuer params (change specification);
                                        IssuerParameters ip2 = new IssuerParameters(ip.UidP, ip.Gq, ip.UidH, ip.G, ip.Gd, ip.E, ip.S, ip.UsesRecommendedParameters, maxNumberOfAttributes);
                                        ip2.S = encoding.GetBytes("wrong issuer params");
                                        try { proof.Verify(ip2, disclosed, message, null, upkt[i].Token); Assert.Fail(); }
                                        catch (InvalidUProveArtifactException) { }

                                        // modify disclosed list
                                        int[] disclosed2;
                                        if (disclosed.Length == 0)
                                        {
                                            disclosed2 = new int[] { 1 };
                                        }
                                        else
                                        {
                                            disclosed2 = new int[] { };
                                        }
                                        try { proof.Verify(ip, disclosed2, message, deviceMessage, upkt[i].Token); Assert.Fail(); }
                                        catch (InvalidUProveArtifactException) { }

                                        // modify message
                                        try { proof.Verify(ip, disclosed, encoding.GetBytes("wrong message"), deviceMessage, upkt[i].Token); Assert.Fail(); }
                                        catch (InvalidUProveArtifactException) { }

                                        // modify token
                                        try { proof.Verify(ip, disclosed, message, deviceMessage, upkt[(i + 1) % numberOfTokens].Token); Assert.Fail(); }
                                        catch (InvalidUProveArtifactException) { }

                                        // modify proof
                                        proof.A = encoding.GetBytes("wrong proof");
                                        try { proof.Verify(ip, disclosed, message, deviceMessage, upkt[i].Token); Assert.Fail(); }
                                        catch (InvalidUProveArtifactException) { }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
Пример #18
0
        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);
        }
Пример #19
0
        public void LongTest()
        {
            int numberOfAttribs = 25;
            // Issuer setup
            IssuerSetupParameters isp = new IssuerSetupParameters(numberOfAttribs);

            isp.UidP = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
            // isp.E = new byte[numberOfAttribs]; // extension by Fablei -> do not change MaxNumberOfAttributes
            isp.UseRecommendedParameterSet = true;
            for (int i = 0; i < numberOfAttribs; i++)
            {
                isp.E[i] = (byte)(i % 2); // alternate between 0 (direct encoding) and 1 (hash)
            }

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

            ip.Verify();

            // Issuance
            byte[][] attributes = new byte[numberOfAttribs][];
            attributes[0] = new byte[] { 0x00 };
            attributes[1] = null;
            attributes[2] = new byte[] { 0x00 };
            attributes[3] = encoding.GetBytes("This is a very long value that doesn't fit in one attribute, but this is ok since we hash this value");
            for (int index = 4; index < numberOfAttribs; index++)
            {
                // for the rest, we just encode random Zq values
                attributes[index] = ip.Zq.GetRandomElement(false).ToByteArray();
            }
            byte[] tokenInformation  = new byte[] { 0x01 };
            byte[] proverInformation = new byte[] { 0x01 };
            int    numberOfTokens    = 10;

            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);

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

            // Presentation
            for (int i = 1; i <= numberOfAttribs; i++)
            {
                // disclose each attribute one by one
                int[]  disclosed = new int[] { i };
                byte[] message   = encoding.GetBytes("this is the presentation message, this can be a very long message");

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

                // verify the presentation proof
                proof.Verify(ip, disclosed, message, null, upkt[0].Token);
            }


            // Pseudonym
            for (int i = 1; i <= numberOfAttribs; i++)
            {
                // present each attribute as a pseudonym
                int[]            disclosed = new int[0];
                byte[]           message   = encoding.GetBytes("this is the presentation message, this can be a very long message");
                byte[]           scope     = encoding.GetBytes("scope" + i);
                FieldZqElement[] unused;

                // generate the presentation proof
                PresentationProof proof = PresentationProof.Generate(ip, disclosed, null, i, scope, message, null, null, upkt[0], attributes, out unused);

                // verify the presentation proof
                proof.Verify(ip, disclosed, null, i, scope, message, null, upkt[0].Token);
            }
        }
Пример #20
0
        public void DevicePseudonymTest()
        {
            // 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(true);
            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;

            IDevice      device = new VirtualDevice(ip);
            GroupElement hd     = device.GetDevicePublicKey();

            IssuerProtocolParameters ipp = new IssuerProtocolParameters(ikap);

            ipp.Attributes       = attributes;
            ipp.NumberOfTokens   = numberOfTokens;
            ipp.TokenInformation = tokenInformation;
            ipp.DevicePublicKey  = hd;
            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;
            ppp.DevicePublicKey   = hd;
            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];
            byte[]            message          = encoding.GetBytes("this is the presentation message, this can be a very long message");
            byte[]            messageForDevice = encoding.GetBytes("message for Device");
            byte[]            scope            = encoding.GetBytes("scope");
            PresentationProof proof;

            FieldZqElement[] tildeO;

            // Valid presentation
            IDevicePresentationContext deviceCtx = device.GetPresentationContext();

            proof = PresentationProof.Generate(ip, disclosed, null, PresentationProof.DeviceAttributeIndex, scope, message, messageForDevice, deviceCtx, upkt[0], attributes, out tildeO);
            proof.Verify(ip, disclosed, null, PresentationProof.DeviceAttributeIndex, scope, message, messageForDevice, upkt[0].Token);

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

            // Ensure tildeO is correct, in this case it should be empty because there are no comitted attributes
            Assert.IsTrue(tildeO == null || tildeO.Length == 0);
        }
Пример #21
0
        public void ProtocolTest()
        {
            Stopwatch sw = new Stopwatch();

            sw.Start();
            bool[] bools = new bool[] { true, false };
            foreach (bool isSubgroupConstruction in bools)
            {
                foreach (bool supportDevice in bools)
                {
                    foreach (int DSize in new int[] { 0, 2, 5 })
                    {
                        foreach (bool isLite in bools)
                        {
                            string filename = "TestVectorData\\testvectors_";
                            if (isSubgroupConstruction)
                            {
                                filename += "SG";
                            }
                            else
                            {
                                filename += "EC";
                            }
                            if (supportDevice)
                            {
                                filename += "_Device";
                            }
                            filename += ("_D" + DSize);
                            if (isLite)
                            {
                                filename += "_lite";
                            }
                            filename += "_doc.txt";
                            var vectors = GetTestVectors(filename);

                            IssuerKeyAndParameters ikap = LoadIssuerKeyAndParameters(isSubgroupConstruction, vectors["GroupName"], supportDevice, vectors);
                            FieldZq Zq = ikap.IssuerParameters.Zq;
                            // replace random y0/g0 with test vector values
                            ikap.PrivateKey            = Zq.GetElement(HexToBytes(vectors["y0"]));
                            ikap.IssuerParameters.G[0] = CreateGroupElement(ikap.IssuerParameters.Gq, vectors["g0"]);
                            Assert.AreEqual(ikap.IssuerParameters.G[0], ikap.IssuerParameters.Gq.G.Exponentiate(ikap.PrivateKey), "g0 computation");
                            IssuerParameters ip = ikap.IssuerParameters;
                            ip.Verify();

                            /*
                             * issuance
                             */

                            byte[][] A = new byte[][] {
                                HexToBytes(vectors["A1"]),
                                HexToBytes(vectors["A2"]),
                                HexToBytes(vectors["A3"]),
                                HexToBytes(vectors["A4"]),
                                HexToBytes(vectors["A5"])
                            };

                            Assert.AreEqual(Zq.GetElement(HexToBytes(vectors["x1"])), ProtocolHelper.ComputeXi(ip, 0, A[0]), "x1");
                            Assert.AreEqual(Zq.GetElement(HexToBytes(vectors["x2"])), ProtocolHelper.ComputeXi(ip, 1, A[1]), "x2");
                            Assert.AreEqual(Zq.GetElement(HexToBytes(vectors["x3"])), ProtocolHelper.ComputeXi(ip, 2, A[2]), "x3");
                            Assert.AreEqual(Zq.GetElement(HexToBytes(vectors["x4"])), ProtocolHelper.ComputeXi(ip, 3, A[3]), "x4");
                            Assert.AreEqual(Zq.GetElement(HexToBytes(vectors["x5"])), ProtocolHelper.ComputeXi(ip, 4, A[4]), "x5");

                            byte[] TI = HexToBytes(vectors["TI"]);
                            Assert.IsTrue(HexToBytes(vectors["P"]).SequenceEqual(ip.Digest(supportDevice)), "P");
                            Assert.AreEqual(Zq.GetElement(HexToBytes(vectors["xt"])), ProtocolHelper.ComputeXt(ip, TI, supportDevice), "xt");

                            IDevice      device = null;
                            GroupElement hd     = null;
                            if (supportDevice)
                            {
                                device = new VirtualDevice(ip, Zq.GetElement(HexToBytes(vectors["xd"])), Zq.GetElement(HexToBytes(vectors["wdPrime"])));
                                IDevicePresentationContext context = device.GetPresentationContext();
                                // Test device responses
                                Assert.AreEqual(CreateGroupElement(ip.Gq, vectors["hd"]), device.GetDevicePublicKey(), "hd");
                                Assert.AreEqual(CreateGroupElement(ip.Gq, vectors["ad"]), context.GetInitialWitness(), "ad");
                                Assert.AreEqual(Zq.GetElement(HexToBytes(vectors["rdPrime"])), context.GetDeviceResponse(HexToBytes(vectors["md"]), HexToBytes(vectors["cp"]), ip.HashFunctionOID), "rdPrime");
                                hd = CreateGroupElement(ip.Gq, vectors["hd"]);
                            }

                            IssuerProtocolParameters ipp = new IssuerProtocolParameters(ikap);
                            ipp.Attributes       = A;
                            ipp.NumberOfTokens   = 1;
                            ipp.TokenInformation = TI;
                            ipp.DevicePublicKey  = hd;
                            ipp.PreGeneratedW    = new FieldZqElement[] { Zq.GetElement(HexToBytes(vectors["w"])) };
                            Issuer issuer = ipp.CreateIssuer();
                            byte[] PI     = HexToBytes(vectors["PI"]);

                            ProverProtocolParameters ppp = new ProverProtocolParameters(ip);
                            ppp.Attributes        = A;
                            ppp.NumberOfTokens    = 1;
                            ppp.TokenInformation  = TI;
                            ppp.ProverInformation = PI;
                            ppp.DevicePublicKey   = hd;
                            ppp.ProverRandomData  = new ProverRandomData(
                                new FieldZqElement[] { Zq.GetElement(HexToBytes(vectors["alpha"])) },
                                new FieldZqElement[] { Zq.GetElement(HexToBytes(vectors["beta1"])) },
                                new FieldZqElement[] { Zq.GetElement(HexToBytes(vectors["beta2"])) });
                            Prover prover = ppp.CreateProver();

                            FirstIssuanceMessage msg1 = issuer.GenerateFirstMessage();
                            Assert.AreEqual(msg1.sigmaZ, CreateGroupElement(ip.Gq, vectors["sigmaZ"]), "sigmaZ");
                            Assert.AreEqual(msg1.sigmaA[0], CreateGroupElement(ip.Gq, vectors["sigmaA"]), "sigmaA");
                            Assert.AreEqual(msg1.sigmaB[0], CreateGroupElement(ip.Gq, vectors["sigmaB"]), "sigmaB");

                            SecondIssuanceMessage msg2 = prover.GenerateSecondMessage(msg1);
                            Assert.AreEqual(msg2.sigmaC[0], Zq.GetElement(HexToBytes(vectors["sigmaC"])), "sigmaC");

                            ThirdIssuanceMessage msg3 = issuer.GenerateThirdMessage(msg2);
                            Assert.AreEqual(msg3.sigmaR[0], Zq.GetElement(HexToBytes(vectors["sigmaR"])), "sigmaR");

                            UProveKeyAndToken[] upkt = prover.GenerateTokens(msg3);
                            Assert.AreEqual(upkt[0].PrivateKey, Zq.GetElement(HexToBytes(vectors["alphaInverse"])), "alphaInverse");
                            UProveToken token = upkt[0].Token;
                            Assert.AreEqual(token.H, CreateGroupElement(ip.Gq, vectors["h"]), "h");
                            Assert.AreEqual(token.SigmaZPrime, CreateGroupElement(ip.Gq, vectors["sigmaZPrime"]), "sigmaZPrime");
                            Assert.AreEqual(token.SigmaCPrime, Zq.GetElement(HexToBytes(vectors["sigmaCPrime"])), "sigmaCPrime");
                            Assert.AreEqual(token.SigmaRPrime, Zq.GetElement(HexToBytes(vectors["sigmaRPrime"])), "sigmaRPrime");
                            Assert.IsTrue(HexToBytes(vectors["UIDt"]).SequenceEqual(ProtocolHelper.ComputeTokenID(ip, token)), "UIDt");
                            Assert.IsTrue(supportDevice == token.IsDeviceProtected);

                            /*
                             * presentation
                             */


                            int[] disclosed = new int[] { };
                            if (vectors.ContainsKey("D") && vectors["D"].Length > 0)
                            {
                                disclosed = Array.ConvertAll <string, int>(vectors["D"].Split(','), new Converter <string, int>(stringToInt));
                            }
                            int[] undisclosed = new int[5 - disclosed.Length];
                            int   dIndex = 0, uIndex = 0;
                            for (int i = 1; i <= 5; i++)
                            {
                                if (disclosed.Length > 0 && disclosed[dIndex] == i)
                                {
                                    dIndex++;
                                }
                                else
                                {
                                    undisclosed[uIndex++] = i;
                                }
                            }
                            int[] committed = new int[] { };
                            if (vectors.ContainsKey("C") && vectors["C"].Length > 0)
                            {
                                committed = Array.ConvertAll <string, int>(vectors["C"].Split(','), new Converter <string, int>(stringToInt));
                            }
                            byte[] m  = HexToBytes(vectors["m"]);
                            byte[] md = HexToBytes(vectors["md"]);
                            IDevicePresentationContext deviceContext = null;
                            if (supportDevice)
                            {
                                deviceContext = device.GetPresentationContext();
                            }
                            int p = 0;
                            if (vectors.ContainsKey("p") && !int.TryParse(vectors["p"], out p))
                            {
                                p = PresentationProof.DeviceAttributeIndex;
                            }
                            byte[] s = vectors.ContainsKey("s") ? HexToBytes(vectors["s"]) : null;
                            int    commitmentIndex = committed.Length > 0 ? committed[0] : 0;
                            ProverPresentationProtocolParameters pppp = new ProverPresentationProtocolParameters(ip, disclosed, m, upkt[0], A);
                            pppp.Committed = committed;
                            pppp.PseudonymAttributeIndex = p;
                            pppp.PseudonymScope          = s;
                            pppp.DeviceMessage           = md;
                            pppp.DeviceContext           = deviceContext;
                            FieldZqElement[] w = new FieldZqElement[undisclosed.Length];
                            for (int i = 0; i < undisclosed.Length; i++)
                            {
                                w[i] = Zq.GetElement(HexToBytes(vectors["w" + undisclosed[i]]));
                            }
                            FieldZqElement[] tildeO = new FieldZqElement[committed.Length];
                            FieldZqElement[] tildeW = new FieldZqElement[committed.Length];
                            for (int i = 0; i < committed.Length; i++)
                            {
                                tildeO[i] = Zq.GetElement(HexToBytes(vectors["tildeO" + committed[i]]));
                                tildeW[i] = Zq.GetElement(HexToBytes(vectors["tildeW" + committed[i]]));
                            }
                            pppp.RandomData = new ProofGenerationRandomData(
                                Zq.GetElement(HexToBytes(vectors["w0"])),
                                w,
                                supportDevice ? Zq.GetElement(HexToBytes(vectors["wd"])) : null,
                                tildeO,
                                tildeW);
                            CommitmentPrivateValues cpv;
                            PresentationProof       proof = PresentationProof.Generate(pppp, out cpv);
                            Assert.IsTrue(HexToBytes(vectors["a"]).SequenceEqual(proof.A), "a");
                            if (vectors.ContainsKey("gs"))
                            {
                                Assert.AreEqual(ProtocolHelper.GenerateScopeElement(ip.Gq, s), CreateGroupElement(ip.Gq, vectors["gs"]));
                                Assert.IsTrue(HexToBytes(vectors["ap"]).SequenceEqual(proof.Ap), "ap");
                                Assert.AreEqual(proof.Ps, CreateGroupElement(ip.Gq, vectors["Ps"]), "Ps");
                            }
                            for (int i = 0; i < disclosed.Length; i++)
                            {
                                Assert.IsTrue(HexToBytes(vectors["A" + disclosed[i]]).SequenceEqual(proof.DisclosedAttributes[i]), "A" + disclosed[i]);
                            }
                            Assert.AreEqual(proof.R[0], Zq.GetElement(HexToBytes(vectors["r0"])), "r0");
                            for (int i = 0; i < undisclosed.Length; i++)
                            {
                                Assert.AreEqual(proof.R[i + 1], Zq.GetElement(HexToBytes(vectors["r" + undisclosed[i]])), "r" + undisclosed[i]);
                            }
                            if (supportDevice)
                            {
                                Assert.AreEqual(proof.R[proof.R.Length - 1], Zq.GetElement(HexToBytes(vectors["rd"])), "rd");
                            }
                            for (int i = 0; i < committed.Length; i++)
                            {
                                Assert.AreEqual(proof.Commitments[i].TildeR, Zq.GetElement(HexToBytes(vectors["tildeR" + committed[i]])), "tildeR" + committed[i]);
                                Assert.IsTrue(cpv.TildeO.Length == committed.Length);
                                Assert.AreEqual(cpv.TildeO[i], Zq.GetElement(HexToBytes(vectors["tildeO" + committed[i]])), "tildeO" + committed[i]);
                            }
                            VerifierPresentationProtocolParameters vppp = new VerifierPresentationProtocolParameters(ip, disclosed, m, upkt[0].Token);
                            vppp.Committed = committed;
                            vppp.PseudonymAttributeIndex = p;
                            vppp.PseudonymScope          = s;
                            vppp.DeviceMessage           = md;
                            proof.Verify(vppp);
#if TEST_ID_ESCROW
                            if (committed.Length > 0)
                            {
                                IDEscrowParams     escrowParams     = new IDEscrowParams(ip);
                                IDEscrowPrivateKey escrowPrivateKey = new IDEscrowPrivateKey(Zq.GetElement(HexToBytes(vectors["ie_x"])));
                                IDEscrowPublicKey  escrowPublicKey  = new IDEscrowPublicKey(escrowParams, escrowPrivateKey);
                                Assert.AreEqual(escrowPublicKey.H, CreateGroupElement(ip.Gq, vectors["ie_H"]), "ie_H");
                                byte[] additionalInfo = HexToBytes(vectors["ie_additionalInfo"]);
                                int    ie_bIndex      = int.Parse(vectors["ie_b"]);

                                IDEscrowCiphertext ctext = IDEscrowFunctions.VerifiableEncrypt(
                                    escrowParams,
                                    escrowPublicKey,
                                    HexToBytes(vectors["UIDt"]),
                                    proof.Commitments[0].TildeC,
                                    ProtocolHelper.ComputeXi(ip, ie_bIndex - 1, A[ie_bIndex - 1]),
                                    cpv.TildeO[0],
                                    additionalInfo,
                                    new IDEscrowFunctions.IDEscrowProofGenerationRandomData(
                                        Zq.GetElement(HexToBytes(vectors["ie_r"])),
                                        Zq.GetElement(HexToBytes(vectors["ie_xbPrime"])),
                                        Zq.GetElement(HexToBytes(vectors["ie_rPrime"])),
                                        Zq.GetElement(HexToBytes(vectors["ie_obPrime"]))));
                                Assert.IsTrue(IDEscrowFunctions.UProveVerify(escrowParams, ctext, proof, upkt[0].Token, escrowPublicKey));
                                Assert.AreEqual(ctext.E1, CreateGroupElement(ip.Gq, vectors["ie_E1"]), "ie_E1");
                                Assert.AreEqual(ctext.E2, CreateGroupElement(ip.Gq, vectors["ie_E2"]), "ie_E2");
                                Assert.AreEqual(ctext.proof.c, Zq.GetElement(HexToBytes(vectors["ie_c"])), "ie_c");
                                Assert.AreEqual(ctext.proof.rR, Zq.GetElement(HexToBytes(vectors["ie_rr"])), "ie_rr");
                                Assert.AreEqual(ctext.proof.rXb, Zq.GetElement(HexToBytes(vectors["ie_rxb"])), "ie_rxb");
                                Assert.AreEqual(ctext.proof.rOb, Zq.GetElement(HexToBytes(vectors["ie_rob"])), "ie_rob");
                                GroupElement PE = IDEscrowFunctions.Decrypt(escrowParams, ctext, escrowPrivateKey);
                            }
#endif

#if TEST_DVA_REVOCATION
                            if (committed.Length > 0)
                            {
                                RAParameters             raParams = new RAParameters(ip.Gq.GroupName, CreateGroupElement(ip.Gq, vectors["r_K"]), ip.UidH);
                                FieldZqElement           delta    = Zq.GetElement(HexToBytes(vectors["r_delta"]));
                                RevocationAuthority      RA       = new RevocationAuthority(raParams, delta);
                                HashSet <FieldZqElement> revoked  = new HashSet <FieldZqElement>();
                                for (int i = 1; i <= 4; i++)
                                {
                                    revoked.Add(Zq.GetElement(HexToBytes(vectors["r_R" + i])));
                                }
                                RA.UpdateAccumulator(revoked, null);
                                Assert.AreEqual(RA.Accumulator, CreateGroupElement(ip.Gq, vectors["r_V"]), "r_V");
                                int r_id = 0;
                                int.TryParse(vectors["r_id"], out r_id);
                                RevocationWitness witness = RA.ComputeRevocationWitness(revoked, Zq.GetElement(HexToBytes(vectors["x" + r_id])));
                                Assert.AreEqual(witness.d, Zq.GetElement(HexToBytes(vectors["r_d"])), "r_d");
                                Assert.AreEqual(witness.W, CreateGroupElement(ip.Gq, vectors["r_W"]), "r_W");
                                Assert.AreEqual(witness.Q, CreateGroupElement(ip.Gq, vectors["r_Q"]), "r_Q");

                                NonRevocationProof nrProof = RevocationUser.GenerateNonRevocationProof(
                                    raParams,
                                    witness,
                                    proof.Commitments[0].TildeC, ProtocolHelper.ComputeXi(ip, r_id - 1, A[r_id - 1]),
                                    cpv.TildeO[0],
                                    new NonRevocationProofGenerationRandomData(new FieldZqElement[] {
                                    Zq.GetElement(HexToBytes(vectors["r_t1"])),
                                    Zq.GetElement(HexToBytes(vectors["r_t2"])),
                                    Zq.GetElement(HexToBytes(vectors["r_k1"])),
                                    Zq.GetElement(HexToBytes(vectors["r_k2"])),
                                    Zq.GetElement(HexToBytes(vectors["r_k3"])),
                                    Zq.GetElement(HexToBytes(vectors["r_k4"])),
                                    Zq.GetElement(HexToBytes(vectors["r_k5"])),
                                    Zq.GetElement(HexToBytes(vectors["r_k6"]))
                                }));
                                Assert.AreEqual(nrProof.X, CreateGroupElement(ip.Gq, vectors["r_X"]), "r_X");
                                Assert.AreEqual(nrProof.Y, CreateGroupElement(ip.Gq, vectors["r_Y"]), "r_Y");
                                Assert.AreEqual(nrProof.Cd, CreateGroupElement(ip.Gq, vectors["r_Cd"]), "r_Cd");
                                Assert.AreEqual(nrProof.cPrime, Zq.GetElement(HexToBytes(vectors["r_cPrime"])), "r_cPrime");
                                Assert.AreEqual(nrProof.s[0], Zq.GetElement(HexToBytes(vectors["r_s1"])), "r_s1");
                                Assert.AreEqual(nrProof.s[1], Zq.GetElement(HexToBytes(vectors["r_s2"])), "r_s2");
                                Assert.AreEqual(nrProof.s[2], Zq.GetElement(HexToBytes(vectors["r_s3"])), "r_s3");
                                Assert.AreEqual(nrProof.s[3], Zq.GetElement(HexToBytes(vectors["r_s4"])), "r_s4");
                                Assert.AreEqual(nrProof.s[4], Zq.GetElement(HexToBytes(vectors["r_s5"])), "r_s5");
                                Assert.AreEqual(nrProof.s[5], Zq.GetElement(HexToBytes(vectors["r_s6"])), "r_s6");

                                // validate proof
                                RA.VerifyNonRevocationProof(ip, 0, proof, nrProof);
                            }
#endif

#if TEST_SET_MEMBERSHIP
                            if (committed.Length > 0)
                            {
                                int sm_x_index = 0;
                                int.TryParse(vectors["sm_x_index"], out sm_x_index);
                                int sm_n = 0;
                                int.TryParse(vectors["sm_n"], out sm_n);
                                int sm_i = 0;
                                int.TryParse(vectors["sm_i"], out sm_i);
                                byte[][]         setValues = new byte[sm_n][];
                                FieldZqElement[] sm_c      = new FieldZqElement[sm_n - 1];
                                FieldZqElement[] sm_r      = new FieldZqElement[sm_n - 1];
                                int randomIndex            = 0;
                                for (int i = 1; i <= sm_n; i++)
                                {
                                    if (i == sm_i)
                                    {
                                        setValues[i - 1] = HexToBytes(vectors["A" + sm_x_index]);
                                    }
                                    else
                                    {
                                        setValues[i - 1]  = HexToBytes(vectors["sm_s" + i]);
                                        sm_c[randomIndex] = Zq.GetElement(HexToBytes(vectors["sm_c" + i]));
                                        sm_r[randomIndex] = Zq.GetElement(HexToBytes(vectors["sm_r" + i]));
                                        randomIndex++;
                                    }
                                }
                                SetMembershipProofGenerationRandomData smRandom = new SetMembershipProofGenerationRandomData(sm_c, sm_r, Zq.GetElement(HexToBytes(vectors["sm_w"])));
                                SetMembershipProof setMembershipProof           = SetMembershipProof.Generate(pppp, proof, cpv, sm_x_index, setValues, smRandom);
                                for (int i = 1; i <= sm_n; i++)
                                {
                                    Assert.AreEqual(setMembershipProof.a[i - 1], CreateGroupElement(ip.Gq, vectors["sm_a" + i]), "sm_a" + i);
                                    if (i < sm_n) // no c_n in the proof
                                    {
                                        Assert.AreEqual(setMembershipProof.c[i - 1], Zq.GetElement(HexToBytes(vectors["sm_c" + i])), "sm_c" + i);
                                    }
                                    Assert.AreEqual(setMembershipProof.r[i - 1], Zq.GetElement(HexToBytes(vectors["sm_r" + i])), "sm_r" + i);
                                }

                                if (!SetMembershipProof.Verify(vppp, proof, setMembershipProof, sm_x_index, setValues))
                                {
                                    throw new InvalidUProveArtifactException("Invalid set membership proof");
                                }
                            }
#endif
                        }
                    }
                }
            }
            sw.Stop();
            Debug.WriteLine("Protocol Test Elapsed Time: " + sw.ElapsedMilliseconds + "ms");
        }
Пример #22
0
        public void ProtocolTest()
        {
            Stopwatch sw = new Stopwatch();

            sw.Start();
            bool[] bools = new bool[] { true, false };
            foreach (bool isSubgroupConstruction in bools)
            {
                foreach (bool supportDevice in bools)
                {
                    var vectors =
                        supportDevice ?
                        (isSubgroupConstruction ?
                         GetTestVectors("testvectorssubgroup_Device_doc.txt")
                            :
                         GetTestVectors("testvectorsEC_Device_doc.txt"))
                        :
                        (isSubgroupConstruction ?
                         GetTestVectors("testvectorssubgroup_doc.txt")
                            :
                         GetTestVectors("testvectorsEC_doc.txt"));

                    IssuerKeyAndParameters ikap = LoadIssuerKeyAndParameters(isSubgroupConstruction, vectors["GroupName"], supportDevice, vectors);
                    FieldZq Zq = ikap.IssuerParameters.Zq;
                    // replace random y0/g0 with test vector values
                    ikap.PrivateKey            = Zq.GetElement(HexToBytes(vectors["y0"]));
                    ikap.IssuerParameters.G[0] = CreateGroupElement(ikap.IssuerParameters.Gq, vectors["g0"]);
                    Assert.AreEqual(ikap.IssuerParameters.G[0], ikap.IssuerParameters.Gq.G.Exponentiate(ikap.PrivateKey), "g0 computation");
                    IssuerParameters ip = ikap.IssuerParameters;
                    ip.Verify();

                    /*
                     * issuance
                     */

                    byte[][] A = new byte[][] {
                        HexToBytes(vectors["A1"]),
                        HexToBytes(vectors["A2"]),
                        HexToBytes(vectors["A3"]),
                        HexToBytes(vectors["A4"]),
                        HexToBytes(vectors["A5"])
                    };

                    Assert.AreEqual(Zq.GetElement(HexToBytes(vectors["x1"])), ProtocolHelper.ComputeXi(ip, 0, A[0]), "x1");
                    Assert.AreEqual(Zq.GetElement(HexToBytes(vectors["x2"])), ProtocolHelper.ComputeXi(ip, 1, A[1]), "x2");
                    Assert.AreEqual(Zq.GetElement(HexToBytes(vectors["x3"])), ProtocolHelper.ComputeXi(ip, 2, A[2]), "x3");
                    Assert.AreEqual(Zq.GetElement(HexToBytes(vectors["x4"])), ProtocolHelper.ComputeXi(ip, 3, A[3]), "x4");
                    Assert.AreEqual(Zq.GetElement(HexToBytes(vectors["x5"])), ProtocolHelper.ComputeXi(ip, 4, A[4]), "x5");

                    byte[] TI = HexToBytes(vectors["TI"]);
                    Assert.IsTrue(HexToBytes(vectors["P"]).SequenceEqual(ip.Digest(supportDevice)), "P");
                    Assert.AreEqual(Zq.GetElement(HexToBytes(vectors["xt"])), ProtocolHelper.ComputeXt(ip, TI, supportDevice), "xt");

                    IDevice      device = null;
                    GroupElement hd     = null;
                    if (supportDevice)
                    {
                        device = new VirtualDevice(ip, Zq.GetElement(HexToBytes(vectors["xd"])), Zq.GetElement(HexToBytes(vectors["wdPrime"])));
                        IDevicePresentationContext context = device.GetPresentationContext();
                        // Test device responses
                        Assert.AreEqual(CreateGroupElement(ip.Gq, vectors["hd"]), device.GetDevicePublicKey(), "hd");
                        Assert.AreEqual(CreateGroupElement(ip.Gq, vectors["ad"]), context.GetInitialWitness(), "ad");
                        Assert.AreEqual(Zq.GetElement(HexToBytes(vectors["rdPrime"])), context.GetDeviceResponse(HexToBytes(vectors["md"]), HexToBytes(vectors["mdPrime"]), ip.HashFunctionOID), "rdPrime");
                        hd = CreateGroupElement(ip.Gq, vectors["hd"]);
                    }

                    IssuerProtocolParameters ipp = new IssuerProtocolParameters(ikap);
                    ipp.Attributes       = A;
                    ipp.NumberOfTokens   = 1;
                    ipp.TokenInformation = TI;
                    ipp.DevicePublicKey  = hd;
                    ipp.PreGeneratedW    = new FieldZqElement[] { Zq.GetElement(HexToBytes(vectors["w"])) };
                    Issuer issuer = ipp.CreateIssuer();
                    byte[] PI     = HexToBytes(vectors["PI"]);

                    ProverProtocolParameters ppp = new ProverProtocolParameters(ip);
                    ppp.Attributes        = A;
                    ppp.NumberOfTokens    = 1;
                    ppp.TokenInformation  = TI;
                    ppp.ProverInformation = PI;
                    ppp.DevicePublicKey   = hd;
                    ppp.ProverRandomData  = new ProverRandomData(
                        new FieldZqElement[] { Zq.GetElement(HexToBytes(vectors["alpha"])) },
                        new FieldZqElement[] { Zq.GetElement(HexToBytes(vectors["beta1"])) },
                        new FieldZqElement[] { Zq.GetElement(HexToBytes(vectors["beta2"])) });
                    Prover prover = ppp.CreateProver();

                    FirstIssuanceMessage msg1 = issuer.GenerateFirstMessage();
                    Assert.AreEqual(msg1.sigmaZ, CreateGroupElement(ip.Gq, vectors["sigmaZ"]), "sigmaZ");
                    Assert.AreEqual(msg1.sigmaA[0], CreateGroupElement(ip.Gq, vectors["sigmaA"]), "sigmaA");
                    Assert.AreEqual(msg1.sigmaB[0], CreateGroupElement(ip.Gq, vectors["sigmaB"]), "sigmaB");

                    SecondIssuanceMessage msg2 = prover.GenerateSecondMessage(msg1);
                    Assert.AreEqual(msg2.sigmaC[0], Zq.GetElement(HexToBytes(vectors["sigmaC"])), "sigmaC");

                    ThirdIssuanceMessage msg3 = issuer.GenerateThirdMessage(msg2);
                    Assert.AreEqual(msg3.sigmaR[0], Zq.GetElement(HexToBytes(vectors["sigmaR"])), "sigmaR");

                    UProveKeyAndToken[] upkt = prover.GenerateTokens(msg3);
                    Assert.AreEqual(upkt[0].PrivateKey, Zq.GetElement(HexToBytes(vectors["alphaInverse"])), "alphaInverse");
                    UProveToken token = upkt[0].Token;
                    Assert.AreEqual(token.H, CreateGroupElement(ip.Gq, vectors["h"]), "h");
                    Assert.AreEqual(token.SigmaZPrime, CreateGroupElement(ip.Gq, vectors["sigmaZPrime"]), "sigmaZPrime");
                    Assert.AreEqual(token.SigmaCPrime, Zq.GetElement(HexToBytes(vectors["sigmaCPrime"])), "sigmaCPrime");
                    Assert.AreEqual(token.SigmaRPrime, Zq.GetElement(HexToBytes(vectors["sigmaRPrime"])), "sigmaRPrime");
                    Assert.IsTrue(HexToBytes(vectors["UIDt"]).SequenceEqual(ProtocolHelper.ComputeTokenID(ip, token)), "UIDt");
                    Assert.IsTrue(supportDevice == token.IsDeviceProtected);

                    /*
                     * presentation
                     */

                    int[]  disclosed = Array.ConvertAll <string, int>(vectors["D"].Split(','), new Converter <string, int>(stringToInt));
                    int[]  committed = Array.ConvertAll <string, int>(vectors["C"].Split(','), new Converter <string, int>(stringToInt));
                    byte[] m         = HexToBytes(vectors["m"]);
                    byte[] md        = null;
                    IDevicePresentationContext deviceContext = null;
                    if (supportDevice)
                    {
                        md            = HexToBytes(vectors["md"]);
                        deviceContext = device.GetPresentationContext();
                    }
                    int p;
                    if (!int.TryParse(vectors["p"], out p))
                    {
                        p = PresentationProof.DeviceAttributeIndex;
                    }
                    byte[] s = HexToBytes(vectors["s"]);
                    int    commitmentIndex = committed[0];
                    ProverPresentationProtocolParameters pppp = new ProverPresentationProtocolParameters(ip, disclosed, m, upkt[0], A);
                    pppp.Committed = committed;
                    pppp.PseudonymAttributeIndex = p;
                    pppp.PseudonymScope          = s;
                    pppp.DeviceMessage           = md;
                    pppp.DeviceContext           = deviceContext;
                    pppp.RandomData = new ProofGenerationRandomData(
                        Zq.GetElement(HexToBytes(vectors["w0"])),
                        new FieldZqElement[] {
                        Zq.GetElement(HexToBytes(vectors["w1"])),
                        Zq.GetElement(HexToBytes(vectors["w3"])),
                        Zq.GetElement(HexToBytes(vectors["w4"]))
                    },
                        supportDevice ? Zq.GetElement(HexToBytes(vectors["wd"])) : null,
                        new FieldZqElement[] {
                        Zq.GetElement(HexToBytes(vectors["tildeO" + commitmentIndex])),
                    },
                        new FieldZqElement[] {
                        Zq.GetElement(HexToBytes(vectors["tildeW" + commitmentIndex]))
                    });
                    CommitmentPrivateValues cpv;
                    PresentationProof       proof = PresentationProof.Generate(pppp, out cpv);
                    Assert.IsTrue(HexToBytes(vectors["a"]).SequenceEqual(proof.A), "a");
                    Assert.AreEqual(ProtocolHelper.GenerateScopeElement(ip.Gq, s), CreateGroupElement(ip.Gq, vectors["gs"]));
                    Assert.IsTrue(HexToBytes(vectors["ap"]).SequenceEqual(proof.Ap), "ap");
                    Assert.AreEqual(proof.Ps, CreateGroupElement(ip.Gq, vectors["Ps"]), "Ps");
                    Assert.IsTrue(HexToBytes(vectors["A2"]).SequenceEqual(proof.DisclosedAttributes[0]), "A2");
                    Assert.IsTrue(HexToBytes(vectors["A5"]).SequenceEqual(proof.DisclosedAttributes[1]), "A5");
                    Assert.AreEqual(proof.R[0], Zq.GetElement(HexToBytes(vectors["r0"])), "r0");
                    Assert.AreEqual(proof.R[1], Zq.GetElement(HexToBytes(vectors["r1"])), "r1");
                    Assert.AreEqual(proof.R[2], Zq.GetElement(HexToBytes(vectors["r3"])), "r3");
                    Assert.AreEqual(proof.R[3], Zq.GetElement(HexToBytes(vectors["r4"])), "r4");
                    if (supportDevice)
                    {
                        Assert.AreEqual(proof.R[4], Zq.GetElement(HexToBytes(vectors["rd"])), "rd");
                    }
                    Assert.AreEqual(proof.Commitments[0].TildeR, Zq.GetElement(HexToBytes(vectors["tildeR" + commitmentIndex])), "tildeR" + commitmentIndex);
                    Assert.IsTrue(cpv.TildeO.Length == 1);
                    Assert.AreEqual(cpv.TildeO[0], Zq.GetElement(HexToBytes(vectors["tildeO" + commitmentIndex])), "tildeO" + commitmentIndex);
                    VerifierPresentationProtocolParameters vppp = new VerifierPresentationProtocolParameters(ip, disclosed, m, upkt[0].Token);
                    vppp.Committed = committed;
                    vppp.PseudonymAttributeIndex = p;
                    vppp.PseudonymScope          = s;
                    vppp.DeviceMessage           = md;
                    proof.Verify(vppp);
                }
            }

            sw.Stop();
            Debug.WriteLine("Protocol Test Elapsed Time: " + sw.ElapsedMilliseconds + "ms");
        }
        public void TestIEWithRealToken()
        {
            /********** begin: this section of code taken from EndToEndTest.cs, TestMethod PseudonymAndCommitmentsTest *****/
            System.Text.UTF8Encoding encoding = new System.Text.UTF8Encoding();

            // 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       ip2  = 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(ip2);

            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(ip2, disclosed, committed, 1, scope, message, null, null, upkt[0], attributes, out tildeO);
            try { proof.Verify(ip2, disclosed, committed, 1, scope, message, null, upkt[0].Token); }
            catch { Assert.Fail("Proof failed to verify"); }
            /******** end code from EndToEndTest.cs ***********/

            // Use the commitment to attribute x_2 for ID escrow
            GroupElement   Cx2     = proof.Commitments[0].TildeC;                     // x2 is the first committed attribute
            FieldZqElement x2      = ProtocolHelper.ComputeXi(ip2, 1, attributes[1]); // attributes[] is zero indexed.
            FieldZqElement tildeO2 = tildeO[0];

            // double check that Cx2 is computed as we expect.
            GroupElement Cx2Prime = ip2.Gq.G.Exponentiate(x2);

            Cx2Prime = Cx2Prime.Multiply(ip2.G[1].Exponentiate(tildeO2));
            Assert.IsTrue(Cx2Prime.Equals(Cx2));

            // Setup
            IDEscrowParams     ieParam3 = new IDEscrowParams(ip2);
            IDEscrowPrivateKey priv     = new IDEscrowPrivateKey(ieParam3);                  // we can't re-use the keypair above, it was created with different issuer params
            IDEscrowPublicKey  pub      = new IDEscrowPublicKey(ieParam3, priv);

            byte[] tokenID = ProtocolHelper.ComputeTokenID(ip2, upkt[0].Token);
            // additionalInfo is defined above.

            // Encrypt
            IDEscrowCiphertext ctext = IDEscrowFunctions.VerifiableEncrypt(ieParam3, pub, tokenID, Cx2, x2, tildeO2, additionalInfo);

            // Verify
            Assert.IsTrue(IDEscrowFunctions.Verify(ieParam3, ctext, tokenID, pub, Cx2));
            // Decrypt
            GroupElement PE = IDEscrowFunctions.Decrypt(ieParam3, ctext, priv);

            Assert.IsTrue(PE.Equals(ieParam3.Ge.Exponentiate(x2)));   // Ensure PE == (ge)^x2
        }