Esempio n. 1
0
        public async Task <IActionResult> SignPersonFaceVerification([FromBody] BiometricPersonDataForSignatureDto biometricPersonData)
        {
            byte[] imageSource = Convert.FromBase64String(biometricPersonData.ImageSource);
            byte[] imageTarget = Convert.FromBase64String(biometricPersonData.ImageTarget);

            byte[] assetId = await _assetsService.GenerateAssetId(AttributesSchemes.ATTR_SCHEME_NAME_PASSPORTPHOTO, biometricPersonData.ImageSource, null).ConfigureAwait(false);

            byte[] sourceImageCommitment = biometricPersonData.SourceImageCommitment.HexStringToByteArray();

            SurjectionProof surjectionProof = new SurjectionProof
            {
                AssetCommitments = new byte[][] { biometricPersonData.SourceImageProofCommitment.HexStringToByteArray() },
                Rs = new BorromeanRingSignature
                {
                    E = biometricPersonData.SourceImageProofSignatureE.HexStringToByteArray(),
                    S = new byte[][] { biometricPersonData.SourceImageProofSignatureS.HexStringToByteArray() }
                }
            };

            if (!ConfidentialAssetsHelper.VerifyIssuanceSurjectionProof(surjectionProof, sourceImageCommitment, new byte[][] { assetId }))
            {
                return(BadRequest("Surjection proofs validation failed"));
            }

            //byte[] auxBytes = null; // Convert.FromBase64String(biometricPersonData.AuxMessage);

            //byte[] msg = new byte[sourceImageCommitment.Length + auxBytes?.Length ?? 0];

            //Array.Copy(sourceImageCommitment, 0, msg, 0, sourceImageCommitment.Length);

            //if ((auxBytes?.Length ?? 0) > 0)
            //{
            //	Array.Copy(auxBytes, 0, msg, sourceImageCommitment.Length, auxBytes.Length);
            //}

            bool res = await _facesService.VerifyFaces(imageSource, imageTarget).ConfigureAwait(false);

            if (res)
            {
                Tuple <byte[], byte[]> signRes = _facesService.Sign(sourceImageCommitment);

                return(Ok(new BiometricSignedVerificationDto {
                    PublicKey = signRes.Item1.ToHexString(), Signature = signRes.Item2.ToHexString()
                }));
            }

            return(BadRequest());
        }
Esempio n. 2
0
        public RelationProofsValidationResults VerifyRelationProofs(GroupsRelationsProofs relationsProofs, IUtxoClientCryptoService clientCryptoService)
        {
            //TODO: need to add eligibility proofs

            RelationProofsValidationResults validationResults = new RelationProofsValidationResults();

            clientCryptoService.DecodeEcdhTuple(relationsProofs.EcdhTuple, relationsProofs.TransactionPublicKey, out byte[] sessionKey, out byte[] imageHash);

            RelationProofSession proofSession = _gatewayService.PopRelationProofSession(sessionKey.ToHexString());

            byte[] image = Convert.FromBase64String(proofSession.ImageContent);
            validationResults.ImageContent = proofSession.ImageContent;
            byte[] imageHashFromSession = ConfidentialAssetsHelper.FastHash256(image);

            validationResults.IsImageCorrect = imageHashFromSession.Equals32(imageHash);

            foreach (var relationEntry in proofSession.RelationEntries)
            {
                bool isRelationContentMatching = false;

                foreach (var relationProof in relationsProofs.RelationProofs)
                {
                    byte[] registrationCommitment = relationProof.RelationProof.AssetCommitments[0];
                    byte[] groupNameCommitment    = _gatewayService.GetEmployeeRecordGroup(relationProof.GroupOwner, registrationCommitment);
                    bool   isRelationProofCorrect = groupNameCommitment != null?ConfidentialAssetsHelper.VerifySurjectionProof(relationProof.RelationProof, relationsProofs.AssetCommitment) : false;

                    if (isRelationProofCorrect)
                    {
                        byte[] relationAssetId = _assetsService.GenerateAssetId(AttributeType.EmployeeGroup, relationProof.GroupOwner.ToHexString() + relationEntry.RelatedAssetName);
                        if (ConfidentialAssetsHelper.VerifyIssuanceSurjectionProof(relationProof.GroupNameProof, groupNameCommitment, new byte[][] { relationAssetId }))
                        {
                            isRelationContentMatching = true;
                            break;
                        }
                    }
                }

                validationResults.ValidationResults.Add(new RelationProofValidationResult {
                    RelatedAttributeOwner = relationEntry.RelatedAssetOwnerName, RelatedAttributeContent = relationEntry.RelatedAssetName, IsRelationCorrect = isRelationContentMatching
                });
            }

            return(validationResults);
        }
Esempio n. 3
0
        public SignedEcCommitment GenerateDerivedCommitment(long pollId, SelectionCommitmentRequest request)
        {
            if (request is null)
            {
                throw new ArgumentNullException(nameof(request));
            }

            EcPollRecord poll = _dataAccessService.GetEcPoll(pollId);

            byte[][] assetIds = poll.Candidates.Select(c => c.AssetId.HexStringToByteArray()).ToArray();

            bool res1 = ConfidentialAssetsHelper.VerifySurjectionProof(request.CandidateCommitmentProofs, request.Commitment);

            if (!res1)
            {
                throw new ArgumentException("Verification to candidate commitments failed");
            }

            foreach (var candidateCommitment in request.CandidateCommitments)
            {
                bool res2 = ConfidentialAssetsHelper.VerifyIssuanceSurjectionProof(candidateCommitment.IssuanceProof, candidateCommitment.Commitment, assetIds);
                if (!res2)
                {
                    throw new ArgumentException($"Verification of candidate's {candidateCommitment.Commitment.ToHexString()} issuance proof failed");
                }
            }

            byte[] ecBlindingFactor = ConfidentialAssetsHelper.GetRandomSeed();
            byte[] ecCommitment     = ConfidentialAssetsHelper.BlindAssetCommitment(request.Commitment, ecBlindingFactor);

            _dataAccessService.AddPollSelection(pollId, ecCommitment.ToHexString(), ecBlindingFactor.ToHexString());

            var persistency = _executionContextManager.ResolveStateExecutionServices(poll.AccountId);
            var signature   = persistency.ClientCryptoService.Sign(ecCommitment);

            return(new SignedEcCommitment
            {
                EcCommitment = ecCommitment,
                Signature = signature
            });
        }
Esempio n. 4
0
        private void ProcessEmployeeRegistrationRequest(EmployeeRegistrationRequest packet)
        {
            _clientCryptoService.DecodeEcdhTuple(packet.EcdhTuple, packet.TransactionPublicKey, out byte[] blindingFactor, out byte[] assetId, out byte[] issuer, out byte[] payload);
            string            sessionKey  = payload.ToHexString();
            List <SpEmployee> spEmployees = _dataAccessService.GetSpEmployees(_accountId, assetId.ToHexString());

            bool  categoryFound         = false;
            bool  alreadyRegistered     = false;
            bool  categoryProofsCorrect = false;
            ulong relationId            = 0;

            foreach (SpEmployee item in spEmployees)
            {
                if (item.SpEmployeeGroup != null)
                {
                    categoryFound = true;
                }
                else
                {
                    continue;
                }

                if (!string.IsNullOrEmpty(item.RegistrationCommitment) && item.RegistrationCommitment.Equals(packet.AssetCommitment.ToHexString()))
                {
                    alreadyRegistered = true;
                    break;
                }

                byte[] groupAssetId = _assetsService.GenerateAssetId(AttributeType.EmployeeGroup, _clientCryptoService.PublicKeys[0].ArraySegment.Array.ToHexString() + item.SpEmployeeGroup.GroupName);
                if (ConfidentialAssetsHelper.VerifyIssuanceSurjectionProof(packet.GroupSurjectionProof, packet.GroupCommitment, new byte[][] { groupAssetId }))
                {
                    categoryProofsCorrect = true;
                    relationId            = item.SpEmployeeId;
                    break;
                }
            }

            if (!categoryFound)
            {
                _idenitiesHubContext.Clients.Group(sessionKey).SendAsync("PushEmployeeNotRegistered");
                return;
            }

            if (alreadyRegistered)
            {
                _idenitiesHubContext.Clients.Group(sessionKey).SendAsync("PushRelationAlreadyRegistered");
                return;
            }

            if (!categoryProofsCorrect)
            {
                _idenitiesHubContext.Clients.Group(sessionKey).SendAsync("PushEmployeeIncorrectRegistration", new { Code = 3, Message = "Group proofs were wrong" });
                return;
            }

            AttributeType attributeType = _assetsService.GetAttributeType(assetId);

            bool isEligibilityCorrect = CheckEligibilityProofs(packet.AssetCommitment, packet.EligibilityProof, issuer);

            if (!isEligibilityCorrect)
            {
                _idenitiesHubContext.Clients.Group(sessionKey).SendAsync("PushEmployeeIncorrectRegistration", new { Code = 2, Message = "Eligibility proofs were wrong" }).Wait();
                return;
            }

            IEnumerable <SpIdenitityValidation> spIdenitityValidations = _dataAccessService.GetSpIdenitityValidations(_accountId);

            if (!CheckSpIdentityValidations(packet.AssetCommitment, packet.AssociatedProofs, spIdenitityValidations, sessionKey))
            {
                return;
            }

            _dataAccessService.SetSpEmployeeRegistrationCommitment(_accountId, relationId, packet.AssetCommitment.ToHexString());
            _transactionsService.IssueEmployeeRecord(packet.AssetCommitment, packet.GroupCommitment);
            _idenitiesHubContext.Clients.Group(_accountId.ToString(CultureInfo.InvariantCulture)).SendAsync("PushEmployeeUpdate", new EmployeeDto {
                AssetId = assetId.ToHexString(), RegistrationCommitment = packet.AssetCommitment.ToHexString()
            });
            _idenitiesHubContext.Clients.Group(sessionKey).SendAsync("PushEmployeeRegistration", new { Commitment = packet.AssetCommitment.ToHexString() });
        }
Esempio n. 5
0
        private async Task CheckAssociatedProof(Memory <byte> rootCommitment, IEnumerable <AttributesByIssuer> associatedAttributes, string schemeName)
        {
            AttributesByIssuer associatedAttributesForCheck = associatedAttributes.FirstOrDefault(c => c.RootAttribute.SchemeName == schemeName || c.Attributes.Any(a => a.SchemeName == schemeName));

            if (associatedAttributesForCheck == null)
            {
                throw new ValidationProofsWereNotCompleteException(schemeName);
            }

            //_logger.LogIfDebug(() => $"{nameof(CheckAssociatedProof)}: \r\n{nameof(rootCommitment)}={rootCommitment.ToHexString()}, \r\n{nameof(associatedRootAttribute)}={{0}}");
            bool proofToRoot = ConfidentialAssetsHelper.VerifySurjectionProof(associatedAttributesForCheck.RootAttribute.BindingProof, rootCommitment.Span);

            if (!proofToRoot)
            {
                _logger.Error("Proof of binding to Root failed");
                throw new ValidationProofFailedException(schemeName);
            }

            AttributeProofs attributeForCheck;

            if (schemeName == associatedAttributesForCheck.RootAttribute.SchemeName)
            {
                attributeForCheck = associatedAttributesForCheck.RootAttribute;

                if (attributeForCheck == null)
                {
                    throw new ValidationProofsWereNotCompleteException(schemeName);
                }
            }
            else
            {
                attributeForCheck = associatedAttributesForCheck.Attributes.FirstOrDefault(a => a.SchemeName == schemeName);

                if (attributeForCheck == null)
                {
                    throw new ValidationProofsWereNotCompleteException(schemeName);
                }

                // Check binding to the Root Attribute
                bool proofToAssociatedRoot = ConfidentialAssetsHelper.VerifySurjectionProof(attributeForCheck.BindingProof, associatedAttributesForCheck.RootAttribute.Commitment.Value.Span);
                if (!proofToAssociatedRoot)
                {
                    _logger.Error("Proof of binding to Associated Root failed");
                    throw new ValidationProofFailedException(schemeName);
                }
            }

            if (attributeForCheck.CommitmentProof.Values?.Any() ?? false)
            {
                long schemeId = await _assetsService.GetSchemeId(schemeName, associatedAttributesForCheck.Issuer.ToString()).ConfigureAwait(false);

                byte[][] assetIds = attributeForCheck.CommitmentProof.Values.Select(v => _assetsService.GenerateAssetId(schemeId, v)).ToArray();

                bool proofOfValue = ConfidentialAssetsHelper.VerifyIssuanceSurjectionProof(attributeForCheck.CommitmentProof.SurjectionProof, attributeForCheck.Commitment.Value.Span, assetIds);
                if (!proofOfValue)
                {
                    _logger.Error("Proof of value failed");
                    throw new ValidationProofFailedException(schemeName);
                }
            }
            else
            {
                bool proofOfValueKnowledge = ConfidentialAssetsHelper.VerifySurjectionProof(attributeForCheck.CommitmentProof.SurjectionProof, attributeForCheck.Commitment.Value.Span);
                if (!proofOfValueKnowledge)
                {
                    _logger.Error("Proof of value knowledge failed");
                    throw new ValidationProofFailedException(schemeName);
                }
            }
        }