public MockDataFixture()
        {
            Alice_Keys = new DidDocument(Utilities.LoadJson("TestData/ed25519-alice-keys.json"));
            Bob_Keys   = new DidDocument(Utilities.LoadJson("TestData/ed25519-bob-keys.json"));
            Diana_Keys = new DidDocument(Utilities.LoadJson("TestData/ed25519-diana-keys.json"));

            ExampleDoc = Utilities.LoadJson("TestData/example-doc.json");
            ExampleDocAlphaInvocation = Utilities.LoadJson("TestData/example-doc-with-alpha-invocation.json");

            RootCapAlpha = new CapabilityDelegation
            {
                Context   = Constants.SECURITY_CONTEXT_V2_URL,
                Id        = "https://example.org/alice/caps#1",
                Invoker   = "https://example.com/i/alice/keys/1",
                Delegator = "https://example.com/i/alice/keys/1"
            };

            DocumentLoader = new CachingDocumentLoader()
                             .AddCached(Alice_Keys.Id, Alice_Keys)
                             .AddCached((Alice_Keys.VerificationMethod.First() as VerificationMethod).Id, Alice_Keys)
                             .AddCached(Bob_Keys.Id, Bob_Keys)
                             .AddCached((Bob_Keys.CapabilityDelegation.First() as VerificationMethod).Id, Bob_Keys)
                             .AddCached((Bob_Keys.CapabilityInvocation.First() as VerificationMethod).Id, Bob_Keys)
                             .AddCached(Diana_Keys.Id, Diana_Keys)
                             .AddCached((Diana_Keys.VerificationMethod.First() as VerificationMethod).Id, Diana_Keys)
                             .AddCached((Diana_Keys.CapabilityDelegation.First() as VerificationMethod).Id, Diana_Keys)
                             .AddCached(ExampleDoc["id"].ToString(), ExampleDoc)
                             .AddCached(RootCapAlpha.Id, RootCapAlpha);
        }
        public static IEnumerable <VerificationMethod> FindVerificationMethods(DidDocument didDocument, string proofPurpose, IDocumentLoader documentLoader)
        {
            var processorOptions = new JsonLdProcessorOptions {
                DocumentLoader = documentLoader.Load
            };

            processorOptions.ExpandContext = Constants.SECURITY_CONTEXT_V2_URL;

            var result = JsonLdProcessor.Frame(
                input: didDocument,
                frame: new JObject
            {
                { "@context", Constants.SECURITY_CONTEXT_V2_URL },
                { "@explicit", true },
                { proofPurpose, new JObject {
                      { "@embed", "@always" }
                  } }
            },
                options: processorOptions);

            if (result[proofPurpose] == null || !(result[proofPurpose] is JArray purposes))
            {
                throw new Exception($"No verification keys found for prupose `{proofPurpose}`");
            }

            return(purposes.Select(x => new VerificationMethod(x as JObject)).ToList());
        }
Esempio n. 3
0
        public void CreateUpdatedAsDateTimeOffset()
        {
            var didDoc = new DidDocument();

            Assert.Null(didDoc.Created);
            Assert.Null(didDoc.Updated);

            var now = DateTimeOffset.UtcNow;

            didDoc.Created = didDoc.Updated = now;

            Assert.Equal(now, didDoc.Created);
            Assert.Equal(now, didDoc.Updated);
        }
        public async Task DidDocumentFromWalletJsonTest()
        {
            String lcdUrl = "http://localhost:1317";
            // string didcom = "1fvwfjx2yealxyw5hktqnvm5ynljlc8jqkkd8kl";
            NetworkInfo   networkInfo    = new NetworkInfo(bech32Hrp: "did:com:", lcdUrl: lcdUrl);
            String        mnemonicString = "gorilla soldier device force cupboard transfer lake series cement another bachelor fatigue royal lens juice game sentence right invite trade perfect town heavy what";
            List <String> mnemonic       = new List <String>(mnemonicString.Split(" ", StringSplitOptions.RemoveEmptyEntries));
            Wallet        wallet         = Wallet.derive(mnemonic, networkInfo);

            // Here the mock server part...
            // Build the mockup server

            String localTestUrl1 = $"{lcdUrl}/auth/accounts/did:com:1fvwfjx2yealxyw5hktqnvm5ynljlc8jqkkd8kl";
            // String localTestUrl2 = $"{lcdUrl}/identities/did:com:1fvwfjx2yealxyw5hktqnvm5ynljlc8jqkkd8kl";

            var _server = new MockHttpServer();
            //  I need this in order to get the correct data out of the mock server
            Dictionary <string, object> nodeResponse1 = JsonConvert.DeserializeObject <Dictionary <String, Object> >(TestResources.TestResources.accountResponse);

            // Dictionary<String, Object> nodeResponse2 = JsonConvert.DeserializeObject<Dictionary<String, Object>>(TestResources.TestResources.tumblerIdentityJson);
            // Initialize Server Response
            _server
            .WithService(localTestUrl1)
            .Api("", "GET", nodeResponse1);
            //_server
            //    .WithService(localTestUrl2)
            //    .Api("", "GET", nodeResponse2);

            // Link the client to the retrieval class Network
            HttpClient client = new HttpClient(_server);

            Network.client = client;

            KeyPair rsaKeyPair = KeysHelper.generateRsaKeyPair();
            KeyPair ecKeyPair  = KeysHelper.generateEcKeyPair();

            List <PublicKey> pubKeys = new List <PublicKey>();

            pubKeys.Add(rsaKeyPair.publicKey);
            pubKeys.Add(ecKeyPair.publicKey);

            DidDocument       didDocument = DidDocumentHelper.fromWallet(wallet, pubKeys);
            TransactionResult results     = await IdHelper.setDidDocument(didDocument, wallet);

            // Just to test no exception in the code
            Assert.AreEqual(true, true);
        }
Esempio n. 5
0
        public void VerificationMethodSerialization()
        {
            var didDoc = new DidDocument();

            didDoc.Authentication = new IVerificationMethod[]
            {
                new VerificationMethod {
                    Id = "did:123"
                },
                new VerificationMethodReference("did:123#key-1")
            };

            var json = JsonConvert.SerializeObject(didDoc);

            var didDoc1 = new DidDocument(JObject.Parse(json));
            var auth    = didDoc1.Authentication.ToList();

            Assert.Equal(2, auth.Count);
            Assert.IsType <VerificationMethod>(auth[0]);
            Assert.IsType <VerificationMethodReference>(auth[1]);
        }
        public void ShouldCreateMinimalSelfManagedDidDocument()
        {
            var doc = new DidDocument
            {
                Id        = "did:example:123456789abcdefghi",
                PublicKey = new List <PublicKey>()
                {
                    new PublicKey()
                    {
                        Id           = "did:example:123456789abcdefghi#keys-1",
                        Type         = "RsaVerificationKey2018",
                        Owner        = "did:example:123456789abcdefghi",
                        PublicKeyPem = "-----BEGIN PUBLIC KEY...END PUBLIC KEY-----\r\n"
                    }
                },
                Authentication = new List <Authentication>()
                {
                    new Authentication()
                    {
                        Type      = "RsaSignatureAuthentication2018",
                        PublicKey = "did:example:123456789abcdefghi#keys-1"
                    }
                },
                Service = new List <Service>()
                {
                    new Service()
                    {
                        Type            = "ExampleService",
                        ServiceEndpoint = "https://example.com/endpoint/8377464"
                    }
                }
            };

            var result = JsonConvert.SerializeObject(doc);

            Assert.True(result == "{\"@context\":\"https://w3id.org/did/v1\",\"id\":\"did:example:123456789abcdefghi\",\"publicKey\":[{\"id\":\"did:example:123456789abcdefghi#keys-1\",\"type\":\"RsaVerificationKey2018\",\"owner\":\"did:example:123456789abcdefghi\",\"publicKeyPem\":\"-----BEGIN PUBLIC KEY...END PUBLIC KEY-----\\r\\n\"}],\"service\":[{\"type\":\"ExampleService\",\"serviceEndpoint\":\"https://example.com/endpoint/8377464\"}],\"authentication\":[{\"type\":\"RsaSignatureAuthentication2018\",\"publicKey\":\"did:example:123456789abcdefghi#keys-1\"}]}");
        }
Esempio n. 7
0
        public async Task VerifyProofRandomKey()
        {
            var signer = new Ed25519VerificationKey2018(Mock.Diana_Keys.VerificationMethod.First() as JObject);

            var document = new DidDocument {
                Id = signer.Controller
            };

            var signedDocument = await LdSignatures.SignAsync(
                document,
                new ProofOptions
            {
                Suite = new Ed25519Signature2018
                {
                    Signer             = signer,
                    VerificationMethod = signer.Id
                },
                Purpose        = new AssertionMethodPurpose(),
                DocumentLoader = Mock.DocumentLoader
            });

            signedDocument["@context"] = new JArray(new[]
            {
                Constants.DID_V1_URL,
                Constants.SECURITY_CONTEXT_V2_URL
            });

            var result = await LdSignatures.VerifyAsync(signedDocument, new ProofOptions
            {
                Suite          = new Ed25519Signature2018(),
                Purpose        = new AssertionMethodPurpose(),
                DocumentLoader = Mock.DocumentLoader
            });

            Assert.NotNull(result);
        }
Esempio n. 8
0
        public void DidDocumentWellFormedFromWalletTest()
        {
            NetworkInfo   networkInfo    = new NetworkInfo(bech32Hrp: "did:com:", lcdUrl: "");
            String        mnemonicString = "dash ordinary anxiety zone slot rail flavor tortoise guilt divert pet sound ostrich increase resist short ship lift town ice split payment round apology";
            List <String> mnemonic       = new List <String>(mnemonicString.Split(" ", StringSplitOptions.RemoveEmptyEntries));
            Wallet        wallet         = Wallet.derive(mnemonic, networkInfo);

            // Numbers are different from Dart version as BouncyCastle didn't like the Dart ones (namely 125 and 126)
            BigInteger   modulusVerification   = new BigInteger("8377", 10);
            BigInteger   exponentVerification  = new BigInteger("131", 10);
            RSAPublicKey rsaPubKeyVerification = new RSAPublicKey(new RsaKeyParameters(isPrivate: false, modulus: modulusVerification, exponent: exponentVerification));

            DidDocumentPublicKey verificationPubKey = new DidDocumentPublicKey(
                id: $"{wallet.bech32Address}#keys-1",
                type: "RsaVerificationKey2018",
                controller: wallet.bech32Address,
                publicKeyPem: rsaPubKeyVerification.getEncoded()
                );

            // Numbers are different from Dart version as BouncyCastle didn't like the Dart ones (namely 135 and 136)
            BigInteger   modulusSignature   = new BigInteger("8707", 10);
            BigInteger   exponentSignature  = new BigInteger("139", 10);
            RSAPublicKey rsaPubKeySignature = new RSAPublicKey(new RsaKeyParameters(isPrivate: false, modulus: modulusSignature, exponent: exponentSignature), keyType: "RsaSignatureKey2018");

            DidDocumentPublicKey signaturePubKey = new DidDocumentPublicKey(
                id: $"{wallet.bech32Address}#keys-2",
                type: "RsaSignatureKey2018",
                controller: wallet.bech32Address,
                publicKeyPem: rsaPubKeySignature.getEncoded()
                );

            DidDocumentProofSignatureContent proofSignatureContent = new DidDocumentProofSignatureContent(
                context: "https://www.w3.org/ns/did/v1",
                id: wallet.bech32Address,
                publicKeys: new List <DidDocumentPublicKey> {
                verificationPubKey, signaturePubKey
            }
                );


            DidDocumentProof expectedComputedProof = new DidDocumentProof(
                type: "EcdsaSecp256k1VerificationKey2019",
                timestamp: GenericUtils.getTimeStamp(), //*** Here we should have a ISO-8601 time stamp!
                proofPurpose: "authentication",
                controller: wallet.bech32Address,
                verificationMethod: wallet.bech32PublicKey,
                signatureValue: Convert.ToBase64String(
                    SignHelper.signSorted(proofSignatureContent.toJson(), wallet)
                    )
                );

            DidDocument expectedDidDocument = new DidDocument(
                context: "https://www.w3.org/ns/did/v1",
                id: wallet.bech32Address,
                publicKeys: new List <DidDocumentPublicKey> {
                verificationPubKey, signaturePubKey
            },
                proof: expectedComputedProof,
                service: new List <DidDocumentService>()
                );

            // This is only to be sure that timestampp is different
            System.Threading.Thread.Sleep(2000);

            DidDocument didDocument = DidDocumentHelper.fromWallet(wallet, new List <PublicKey> {
                rsaPubKeyVerification, rsaPubKeySignature
            });

            //This is the comparison class
            CompareLogic compareLogic = new CompareLogic();

            // Check it - we use compareNet objects here
            Assert.AreEqual(compareLogic.Compare(didDocument.context, expectedDidDocument.context).AreEqual, true);
            Assert.AreEqual(compareLogic.Compare(didDocument.id, expectedDidDocument.id).AreEqual, true);
            Assert.AreEqual(compareLogic.Compare(didDocument.publicKeys, expectedDidDocument.publicKeys).AreEqual, true);

            Assert.AreEqual(compareLogic.Compare(didDocument.proof.type, expectedDidDocument.proof.type).AreEqual, true);
            Assert.AreEqual(compareLogic.Compare(didDocument.proof.proofPurpose, expectedDidDocument.proof.proofPurpose).AreEqual, true);
            Assert.AreEqual(compareLogic.Compare(didDocument.proof.controller, expectedDidDocument.proof.controller).AreEqual, true);
            Assert.AreEqual(compareLogic.Compare(didDocument.proof.verificationMethod, expectedDidDocument.proof.verificationMethod).AreEqual, true);
            Assert.AreEqual(compareLogic.Compare(didDocument.proof.timestamp, expectedComputedProof.timestamp).AreEqual, false);
            // The difference depends on the "secureRandom" method used at the time of the signature.
            Assert.AreEqual(compareLogic.Compare(didDocument.proof.signatureValue, expectedDidDocument.proof.signatureValue).AreEqual, false);

            Assert.AreEqual(didDocument.proof.signatureValue.Length, expectedDidDocument.proof.signatureValue.Length);
            // WE also verify the json here

            Dictionary <String, Object> expectedDidDocumentJson = expectedDidDocument.toJson();
            Dictionary <String, Object> didDocumentJson         = didDocument.toJson();
            // Assert.AreEqual(compareLogic.Compare(expectedDidDocumentJson, didDocumentJson).AreEqual, true);
            // They cannot be equal because of time stamps
        }
Esempio n. 9
0
 public void EmptyDocumentHash()
 {
     _ = new DidDocument().GetHashCode();
 }