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();
            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;
        }
    private IssuerSetupParameters getIssuerSetupParameters(byte[] attributeEncoding, string name, bool forceRecSet = false)
    {
      IssuerSetupParameters isp = new IssuerSetupParameters();
      
      if (attributeEncoding.Length <= 21 || forceRecSet)
      {
        isp.ParameterSet = getRecommendedSet(2048);
        isp.UseRecommendedParameterSet = true;
      }
      else
      {
        isp.UseRecommendedParameterSet = false;
      }

      isp.UidH = "SHA-256";
      isp.UidP = encoding.GetBytes(name);

      // set the encoding parameters for the attributes
      isp.GroupConstruction = GroupConstruction.Subgroup;
      isp.E = attributeEncoding;

      // specification field unused in ABC4Trust
      isp.S = null;

      return isp;
    }
    public IssuerKeyAndParameters CreateIssuerSetupParameters(IssuerSetupParametersSpec spec)
    {
      IssuerSetupParameters isp = new IssuerSetupParameters();
      isp.GroupConstruction = spec.GroupConstruction ?? GroupType.Subgroup;
      isp.UidP = ExtensionMethods.ToByteArray(spec.IssuerID);
      isp.E = spec.AttributeEncoding != null ? spec.AttributeEncoding : IssuerSetupParameters.GetDefaultEValues(spec.NumberOfAttributes);
      isp.UseRecommendedParameterSet = spec.UseRecommendedParameterSet ?? true;

      if (issuerStore.HasValue(spec.IssuerID) && spec.StoreOnServer)
      {
        ApiArgumentFault fault = new ApiArgumentFault();
        fault.Details = "Issuer with unique ID was found";
        fault.Argument = "IssuerSetupParametersSpec.ID";
        fault.ArgumentValue = spec.ParameterSetName;
        throw new FaultException<ApiArgumentFault>(fault);
      }

      // look up ParameterSet.
      if (isp.UseRecommendedParameterSet)
      {
        isp.ParameterSet = IssuerSetupParameters.GetDefaultParameterSet(isp.GroupConstruction);
        // XXX add a check here to see if the name of the default parameterset is that same as
        // specified in spec.ParameterSetName and that match with the sha method specified.
      }
      else
      {
        ParameterSet pSet;
        if (ParameterSet.TryGetNamedParameterSet(spec.ParameterSetName, out pSet))
        {
          isp.ParameterSet = pSet;
        }
        else
        {
          ApiArgumentFault fault = new ApiArgumentFault();
          fault.Details = "Member value vas not found";
          fault.Argument = "IssuerSetupParametersSpec.ParameterSetName";
          fault.ArgumentValue = spec.ParameterSetName;
          throw new FaultException<ApiArgumentFault>(fault);
        }
      }

      // specification field unused in ABC4Trust
      isp.S = null;

      IssuerKeyAndParameters issuerKeyParam = isp.Generate(true);
      if (spec.StoreOnServer) { 
        issuerStore.AddValue(spec.IssuerID, issuerKeyParam);
      }
      return issuerKeyParam;
    }
 public void VerifyIssuerParametersTest()
 {
     IssuerSetupParameters isp = new IssuerSetupParameters();
     isp.UidP = new byte[] { 1, 2, 3, 4, 5 };
     isp.E = IssuerSetupParameters.GetDefaultEValues(7);
     isp.UseRecommendedParameterSet = false;
     isp.GroupConstruction = GroupType.Subgroup;
     IssuerKeyAndParameters ikap = isp.Generate();
     IssuerParameters ip = ikap.IssuerParameters;
     ProtocolHelper.VerifyIssuerParameters(ip, false);
     byte[] g0Bytes = ip.G[0].GetEncoded();
     g0Bytes[g0Bytes.Length - 1]++;
     ip.G[0] = (SubgroupGroupElement)ip.Gq.CreateGroupElement(g0Bytes);
     try { ProtocolHelper.VerifyIssuerParameters(ip, false); Assert.Fail(); } catch (InvalidUProveArtifactException) { }
 }
        private static IssuerKeyAndParameters SetupUProveIssuer(string UIDP, int numberOfAttributes, GroupType groupType = GroupType.Subgroup, bool supportDevice = false)
        {
            WriteLine("Setting up Issuer parameters");
            IssuerSetupParameters isp = new IssuerSetupParameters();
            // pick a unique identifier for the issuer params
            isp.UidP = encoding.GetBytes(UIDP);
            // set the number of attributes in the U-Prove tokens
            isp.NumberOfAttributes = numberOfAttributes;
            // an application profile would define the format of the specification field,
            // we use a dummy value in this sample
            isp.S = encoding.GetBytes("application-specific specification");
            // specify the group type: subgroup (default) or ECC
            isp.GroupConstruction = groupType;

            return isp.Generate(supportDevice);
        }
Beispiel #6
0
        /// <summary>
        /// Generates a fresh Issuer key and parameters.
        /// </summary>
        /// <param name="supportDevice">If true, the parameters will support issuing Device-protected tokens. Defaults to <code>false</code>.</param>
        /// <returns>A Issuer key and parameters instance.</returns>
        public IssuerKeyAndParameters Generate(bool supportDevice = false)
        {
            // first validate the data we have
            Validate();

            GroupElement[] gValues = null;
            if (ip.Gq == null)
            {
                if (this.ParameterSet != null)
                {
                    ip.Gq   = this.ParameterSet.Group;
                    gValues = this.ParameterSet.G;
                    if (supportDevice)
                    {
                        ip.Gd = this.ParameterSet.Gd;
                    }
                    // is that a known parameter set?
                    ip.UsesRecommendedParameters = ParameterSet.ContainsParameterSet(this.ParameterSet.Name);
                }
                else
                {
                    ParameterSet defaultParamSet = IssuerSetupParameters.GetDefaultParameterSet(this.GroupConstruction);
                    ip.Gq = defaultParamSet.Group;
                    if (UseRecommendedParameterSet)
                    {
                        gValues = defaultParamSet.G;
                        // recommended groups always support devices
                        ip.Gd = defaultParamSet.Gd;
                        ip.UsesRecommendedParameters = true;
                    }
                }
            }

            FieldZqElement y0 = ProtocolHelper.GenerateIssuerParametersCryptoData(ip, gValues, supportDevice);

            return(new IssuerKeyAndParameters(y0, ip));
        }
        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();
                                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);
                                        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) { }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
        public void LongTest()
        {
            int numberOfAttribs = 25;
            // Issuer setup
            IssuerSetupParameters isp = new IssuerSetupParameters();
            isp.UidP = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
            isp.E = new byte[numberOfAttribs];
            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);
            }

        }
        public void DevicePseudonymTest()
        {
            // 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(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);
        }
        public void TestIssuerSetupParameters()
        {
            System.Text.UTF8Encoding encoding = new System.Text.UTF8Encoding();

            byte[][] A = new byte[][] { encoding.GetBytes("attribute value") };
            byte[] TI = encoding.GetBytes("TI value");
            IssuerSetupParameters isp = new IssuerSetupParameters();
            isp.GroupConstruction = GroupType.Subgroup;
            isp.UidP = encoding.GetBytes("UIDP value");
            isp.E = new byte[] { 1 };
            IssuerKeyAndParameters ikap = isp.Generate();

            ikap.IssuerParameters.Verify();

            // invalidate the issuer parameters

            IssuerParameters ip = ikap.IssuerParameters;
            SubgroupGroupElement sgG0 = (SubgroupGroupElement) ip.G[0];
            byte[] g0Bytes = ip.G[0].GetEncoded();
            g0Bytes[g0Bytes.Length - 1]++;
            ip.G[0] = (SubgroupGroupElement) ip.Gq.CreateGroupElement(g0Bytes);

            try
            {
                ip.Verify();
                Assert.Fail();
            }
            catch (InvalidUProveArtifactException) { }
            
        }
        public void PseudonymAndCommitmentsTest()
        {
            // 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 = 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.G.Exponentiate(x2);
            Cx2Prime = Cx2Prime.Multiply(ip.G[1].Exponentiate(tildeO2));
            Assert.IsTrue(Cx2Prime.Equals(Cx2));

        }
        public void TestProver()
        {
            byte[][] A = new byte[][] { };
            byte[] TI = null;
            byte[] PI = null;
            IssuerSetupParameters isp = new IssuerSetupParameters();
            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) { }
        }
        public void TestRecommendedParameters()
        {
            ParameterSet set;
            const string ECCNamePrefix = "U-Prove Recommended Parameters Profile";
            var encoder = System.Text.UnicodeEncoding.UTF8;
            Dictionary<string, byte[]> oidContextDictionary = new Dictionary<string, byte[]>();
            // Subgroup (OID, NIST domain params seed)

            oidContextDictionary.Add("1.3.6.1.4.1.311.75.1.1.0", 
                            new byte[] {
                             0x42, 0xf3, 0x05, 0xc4, 0x7a, 0xfa, 0xa3, 0x3b,
                             0x97, 0xd7, 0x25, 0x77, 0x5c, 0xc2, 0xfe, 0x61,
                             0xa8, 0xa1, 0xae, 0xe7
                            });

            oidContextDictionary.Add("1.3.6.1.4.1.311.75.1.1.1",
                            new byte[] {
                             0x22, 0x7c, 0xc8, 0x30, 0x35, 0xac, 0x2c, 0x68,
                             0xe6, 0xb4, 0xe5, 0xfe, 0x4b, 0x59, 0xc0, 0xa8,
                             0x4a, 0xe8, 0x03, 0x30, 0xf3, 0x80, 0xde, 0x03,
                             0x22, 0x3e, 0x37, 0x81, 0x36, 0xd7, 0x6f, 0xc0                                                         
                            });

            oidContextDictionary.Add("1.3.6.1.4.1.311.75.1.1.2",
                           new byte[] {
                            0x31, 0xf2, 0xd6, 0xcf, 0xcd, 0x65, 0x2b, 0x7d,
                            0xb8, 0x18, 0x6e, 0x84, 0x9d, 0xf1, 0x4b, 0x75,
                            0x60, 0x40, 0x7b, 0xca, 0x0f, 0x03, 0x04, 0xe0,
                            0x9e, 0x0d, 0x9d, 0x2c, 0x03, 0xd4, 0xfa, 0x4c
                           });


            // Elliptic Curve (OID, ECC Prefix + curve name)
            oidContextDictionary.Add("1.3.6.1.4.1.311.75.1.2.1", encoder.GetBytes(ECCNamePrefix + "P-256"));  // NIST P-256
            oidContextDictionary.Add("1.3.6.1.4.1.311.75.1.2.2", encoder.GetBytes(ECCNamePrefix + "P-384"));  // NIST P-384
            oidContextDictionary.Add("1.3.6.1.4.1.311.75.1.2.3", encoder.GetBytes(ECCNamePrefix + "P-521"));  // NIST P-521

            foreach (string oid in oidContextDictionary.Keys)
            {
                ParameterSet.TryGetNamedParameterSet(oid, out set);
                Assert.AreEqual<string>(oid, set.Name);
                Assert.AreEqual<int>(ParameterSet.NumberOfIssuerGenerators + 1, set.G.Length); // g_t is also in the list
                Group Gq = set.Group;
                Gq.Verify();
                int counter;
                byte[] context = oidContextDictionary[oid];
                if (Gq.Type == GroupType.Subgroup)
                {
                    // g is only generated for the subgroup construction
                    Assert.AreEqual<GroupElement>(Gq.G, Gq.DeriveElement(context, (byte)0, out counter));
                }

                // tests gi
                for (int i = 1; i < set.G.Length; i++ )
                {
                    GroupElement gi = set.G[i - 1];
                    Gq.ValidateGroupElement(gi);
                    GroupElement derived = Gq.DeriveElement(context, (byte)i, out counter);
                    Gq.ValidateGroupElement(derived);
                    if (!gi.Equals(derived))
                    {
                        Debugger.Break();
                    }

                    Assert.AreEqual<GroupElement>(gi, derived);
                }
                // gt uses index = 255
                Assert.AreEqual<GroupElement>(set.G[set.G.Length - 1], Gq.DeriveElement(context, (byte)255, out counter));
                Gq.ValidateGroupElement(set.Gd);

                // gd uses index = 254
                Assert.AreEqual<GroupElement>(set.Gd, Gq.DeriveElement(context, (byte)254, out counter));
                Gq.ValidateGroupElement(set.Gd);

                // Issuer setup
                IssuerSetupParameters isp = new IssuerSetupParameters();
                isp.UidP = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
                if (oid == "1.3.6.1.4.1.311.75.1.2.3") // P-521
                {
                    isp.UidH = "SHA-512";
                }
                isp.E = new byte[ParameterSet.NumberOfIssuerGenerators];
                isp.ParameterSet = set;
                for (int i = 0; i < ParameterSet.NumberOfIssuerGenerators; i++)
                {
                    isp.E[i] = (byte)0;
                }
                isp.S = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
                IssuerKeyAndParameters ikap = isp.Generate();
                IssuerParameters ip = ikap.IssuerParameters;

                RunProtocol(ikap, ip);
            }
        }
        public void CustomGroupTest()
        {
            // we reuse an exisiting group, but without setting it by name.
            // we expect new generators to be generated.
            ParameterSet set;
            ParameterSet.TryGetNamedParameterSet(SubgroupParameterSets.ParamSet_SG_2048256_V1Name, out set);

            IssuerSetupParameters isp = new IssuerSetupParameters();
            isp.UidP = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
            isp.NumberOfAttributes = 1;
            isp.Gq = set.Group; // reusing an existing group.
            IssuerKeyAndParameters ikap = isp.Generate();
            IssuerParameters ip = ikap.IssuerParameters;

            // new generators should have been generated, to the issuer parameters' g1 and parameter set's g1
            // should be different.
            Assert.AreNotEqual(ip.G[1], set.G[0]); // set's index 0 is g_1
        }
        public void FreshParametersTest()
        {
            //
            // test with 1 attribute
            //

            // Issuer setup
            IssuerSetupParameters isp = new IssuerSetupParameters();
            isp.UidP = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
            isp.NumberOfAttributes = 1;
            isp.UseRecommendedParameterSet = false; // use freshly generated generators
            isp.GroupConstruction = GroupType.Subgroup;
            IssuerKeyAndParameters ikap = isp.Generate();
            IssuerParameters ip = ikap.IssuerParameters;

            // get the default subgroup to make sure that is _not_ what we are generating
            ParameterSet set;
            ParameterSet.TryGetNamedParameterSet("1.3.6.1.4.1.311.75.1.1.1", out set);
            Assert.AreNotEqual(ip.G[1], set.G[0]); // set's index 0 is g_1

            RunProtocol(ikap, ip);

            //
            // test with max+1 attributes
            //

            isp.NumberOfAttributes = IssuerSetupParameters.RecommendedParametersMaxNumberOfAttributes + 1;
            ikap = isp.Generate();
            ip = ikap.IssuerParameters;
            Assert.IsTrue(ip.E.Length == IssuerSetupParameters.RecommendedParametersMaxNumberOfAttributes + 1);
            RunProtocol(ikap, ip);

            //
            // test invalid number of attributes
            //

            isp.UseRecommendedParameterSet = true;
            try
            {
                ikap = isp.Generate();
                Assert.Fail();
            }
            catch (System.ArgumentException) 
            {
                // expected
            };
        }
        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);
            }
        }
        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();
            isp.GroupConstruction = useSubgroupConstruction ? GroupType.Subgroup : GroupType.ECC;
            isp.UidP = GetRandomBytes(MaxByteArrayLength);
            isp.UidH = hashFunction;
            isp.E = IssuerSetupParameters.GetDefaultEValues(numberOfAttributes);
            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);

        }
    private static IssuerKeyAndParametersComposite UseCustomParameterSet(string uniqueIdentifier, byte[] attributeEncoding, string hash, string sessionID)
    {
      IssuerSetupParameters isp = new IssuerSetupParameters();

      
      isp.GroupConstruction = GroupConstruction.Subgroup;
      // pick a unique identifier for the issuer params
      isp.UidP = encoding.GetBytes(uniqueIdentifier);

      // set the encoding parameters for the attributes
      isp.E = attributeEncoding;

      isp.UseRecommendedParameterSet = false; // we don't use the recommended parameters

      // specification field unused in ABC4Trust
      isp.S = null;

      // generate the serializable IssuerKeyAndParameters		
      IssuerKeyAndParameters ikap = isp.Generate(true);
      sessionDB[sessionID].group = ikap.IssuerParameters.Gq;
      sessionDB[sessionID].groupElement = ikap.IssuerParameters.Gd;
      IssuerKeyAndParametersComposite ikpc = new IssuerKeyAndParametersComposite();
      
      ikpc.IssuerParameters = ConvertUtils.convertIssuerParameters(ikap.IssuerParameters);
      ikpc.PrivateKey = ikap.PrivateKey.ToByteArray();

      return ikpc;
    }
    private static IssuerKeyAndParametersComposite UsePreComputeParameterSet(string uniqueIdentifier, byte[] attributeEncoding, string hash, string sessionID)
    {
      IssuerSetupParameters isp = new IssuerSetupParameters();

      // pick the group construction (defaults to subgroup, but ECC is more efficient)
      // TODOv2: Enable the UProve module to switch between ECC and subgroup based on ie. a config file.
      // isp.GroupConstruction = GroupConstruction.ECC;
      // right now, we need to use the subgroup construction to interop with Idemix
      isp.GroupConstruction = GroupConstruction.Subgroup;
      isp.ParameterSet = sessionDB[sessionID].parameterSet;
      sessionDB[sessionID].group = isp.ParameterSet.Group;
      sessionDB[sessionID].groupElement = isp.ParameterSet.Gd;

      isp.UidH = hash;

      // pick a unique identifier for the issuer params
      isp.UidP = encoding.GetBytes(uniqueIdentifier);

      // set the encoding parameters for the attributes
      isp.E = attributeEncoding;

      // specification field unused in ABC4Trust
      isp.S = null;

      // generate the serializable IssuerKeyAndParameters		
      IssuerKeyAndParameters ikap = isp.Generate(true);
      IssuerKeyAndParametersComposite ikpc = new IssuerKeyAndParametersComposite();
      ikpc.IssuerParameters = ConvertUtils.convertIssuerParameters(ikap.IssuerParameters);
      ikpc.PrivateKey = ikap.PrivateKey.ToByteArray();

      return ikpc;
    }
 IssuerKeyAndParameters LoadIssuerKeyAndParameters(bool useSubgroupConstruction, string oid, bool supportDevice, Dictionary<string, string> vectors)
 {
     IssuerSetupParameters isp = new IssuerSetupParameters();
     
     isp.UseRecommendedParameterSet = true;
     isp.GroupConstruction = useSubgroupConstruction ? GroupType.Subgroup : GroupType.ECC;
     isp.UidP = HexToBytes(vectors["UIDp"]);
     isp.UidH = vectors["UIDh"];
     isp.E = new byte[] 
     { 
         byte.Parse(vectors["e1"]),
         byte.Parse(vectors["e2"]),
         byte.Parse(vectors["e3"]),
         byte.Parse(vectors["e4"]),
         byte.Parse(vectors["e5"]) 
     };
     isp.S = HexToBytes(vectors["S"]);
     IssuerKeyAndParameters ikap = isp.Generate(supportDevice);
     Assert.AreEqual<string>(ikap.IssuerParameters.Gq.GroupName, oid);
     return ikap;
 }