Esempio n. 1
0
        public void EncryptData_MultiplePublicKeysWithDifferentTypesGiven_ShouldCipherDataBeDecrypted()
        {
            var crypto   = new VirgilCrypto();
            var keyPairs = new List <KeyPair>
            {
                crypto.GenerateKeys(KeyPairType.EC_SECP256R1),
                crypto.GenerateKeys(KeyPairType.EC_SECP384R1),
                crypto.GenerateKeys(KeyPairType.EC_SECP521R1),
                crypto.GenerateKeys(KeyPairType.EC_BP256R1),
                crypto.GenerateKeys(KeyPairType.EC_BP384R1),
                crypto.GenerateKeys(KeyPairType.EC_BP512R1),
                crypto.GenerateKeys(KeyPairType.EC_SECP256K1),
                crypto.GenerateKeys(KeyPairType.EC_CURVE25519),
                crypto.GenerateKeys(KeyPairType.FAST_EC_ED25519),
                crypto.GenerateKeys(KeyPairType.FAST_EC_X25519)
            };

            var data          = Encoding.UTF8.GetBytes("Encrypt me!!!");
            var encryptedData = crypto.Encrypt(data, keyPairs.Select(it => it.PublicKey).ToArray());

            foreach (var keyPair in keyPairs)
            {
                var decryptedData = crypto.Decrypt(encryptedData, keyPair.PrivateKey);
                data.ShouldAllBeEquivalentTo(decryptedData);
            }
        }
Esempio n. 2
0
        public void EncryptStream_SmallStreamBufferGiven_ShouldCipherStreamBeDecrypted()
        {
            var crypto  = new VirgilCrypto();
            var keyPair = crypto.GenerateKeys();

            var originalData = Encoding.UTF8.GetBytes("Hello There :)");

            byte[] cipherData;
            byte[] resultData;

            using (var inputStream = new MemoryStream(originalData))
                using (var cipherStream = new MemoryStream())
                {
                    crypto.Encrypt(inputStream, cipherStream, keyPair.PublicKey);
                    cipherData = cipherStream.ToArray();
                }

            using (var cipherStream = new MemoryStream(cipherData))
                using (var resultStream = new MemoryStream())
                {
                    crypto.Decrypt(cipherStream, resultStream, keyPair.PrivateKey);
                    resultData = resultStream.ToArray();
                }

            originalData.ShouldAllBeEquivalentTo(resultData);
        }
Esempio n. 3
0
        private VirgilClient PredefinedClient(VirgilCrypto crypto)
        {
            var clientParams = new VirgilClientParams(ConfigurationManager.AppSettings["virgil:AppAccessToken"]);

            clientParams.SetCardsServiceAddress(ConfigurationManager.AppSettings["virgil:CardsServicesAddress"]);
            clientParams.SetIdentityServiceAddress(ConfigurationManager.AppSettings["virgil:IdentityServiceAddress"]);
            clientParams.SetRAServiceAddress(ConfigurationManager.AppSettings["virgil:RAServicesAddress"]);
            clientParams.SetReadCardsServiceAddress(ConfigurationManager.AppSettings["virgil:CardsReadServicesAddress"]);

            var validator = new CardValidator(crypto);

            // To use staging Verifier instead of default verifier
            var cardVerifier = new CardVerifierInfo
            {
                CardId        = ConfigurationManager.AppSettings["virgil:ServiceCardId"],
                PublicKeyData = VirgilBuffer.From(ConfigurationManager.AppSettings["virgil:ServicePublicKeyDerBase64"],
                                                  StringEncoding.Base64)
            };

            validator.AddVerifier(cardVerifier.CardId, cardVerifier.PublicKeyData.GetBytes());

            var client = new VirgilClient(clientParams);

            client.SetCardValidator(validator);

            return(client);
        }
Esempio n. 4
0
        public (IPublicKey, IPrivateKey) GenerateKeyPair(byte[] keyMaterial)
        {
            var crypto  = new VirgilCrypto();
            var keyPair = crypto.GenerateKeys(this.DefaultKeyPairType, keyMaterial);

            return(keyPair.PublicKey, keyPair.PrivateKey);
        }
Esempio n. 5
0
        public async Task CreateNewVirgilCard_IdentityAndPublicKeyGiven_ShouldBeFoundByIdentity()
        {
            var crypto = new VirgilCrypto();
            var client = IntegrationHelper.GetVirgilClient();

            var appKey = crypto.ImportPrivateKey(IntegrationHelper.AppKey, IntegrationHelper.AppKeyPassword);

            var aliceKeys         = crypto.GenerateKeys();
            var exportedPublicKey = crypto.ExportPublicKey(aliceKeys.PublicKey);

            var aliceIdentity = "alice-" + Guid.NewGuid();

            var request = new PublishCardRequest(aliceIdentity, "member", exportedPublicKey);

            var requestSigner = new RequestSigner(crypto);

            requestSigner.SelfSign(request, aliceKeys.PrivateKey);
            requestSigner.AuthoritySign(request, IntegrationHelper.AppID, appKey);

            var newCard = await client.PublishCardAsync(request);

            var cards = await client.SearchCardsAsync(new SearchCriteria { Identities = new[] { aliceIdentity } });

            cards.Should().HaveCount(1);
            var foundCard = cards.Single();

            newCard.ShouldBeEquivalentTo(foundCard);
        }
        public void Ctor_HexStringGiven_ValuesShouldMatchWithVirgilCryptoImpl()
        {
            var hash = new VirgilCrypto().ComputeHash(Encoding.UTF8.GetBytes("1234567890"), HashAlgorithm.SHA256);
            var hex  = VirgilByteArrayUtils.BytesToHex(hash);

            hash.ShouldAllBeEquivalentTo(new Fingerprint(hex).GetValue());
        }
Esempio n. 7
0
        public async Task CreateNewVirgilCard_SignatureValidation_ShouldPassValidation()
        {
            var crypto = new VirgilCrypto();
            var client = IntegrationHelper.GetVirgilClient();

            // CREATING A VIRGIL CARD

            var appKey = crypto.ImportPrivateKey(IntegrationHelper.AppKey, IntegrationHelper.AppKeyPassword);

            var aliceKeys         = crypto.GenerateKeys();
            var exportedPublicKey = crypto.ExportPublicKey(aliceKeys.PublicKey);

            var aliceIdentity = "alice-" + Guid.NewGuid();
            var request       = new PublishCardRequest(aliceIdentity, "member", exportedPublicKey);

            var requestSigner = new RequestSigner(crypto);

            requestSigner.SelfSign(request, aliceKeys.PrivateKey);
            requestSigner.AuthoritySign(request, IntegrationHelper.AppID, appKey);

            var aliceCard = await client.PublishCardAsync(request);

            // VALIDATING A VIRGIL CARD

            var appPublicKey         = crypto.ExtractPublicKey(appKey);
            var exportedAppPublicKey = crypto.ExportPublicKey(appPublicKey);

            var validator = new CardValidator(crypto);

            validator.AddVerifier(IntegrationHelper.AppID, exportedAppPublicKey);

            validator.Validate(aliceCard).Should().BeTrue();

            await IntegrationHelper.RevokeCard(aliceCard.Id);
        }
Esempio n. 8
0
        public void SecondExtraSign_Should_ThrowException()
        {
            //STC-8
            var rawSignedModel = faker.PredefinedRawSignedModel(null, false, false, false);
            var crypto         = new VirgilCrypto();
            var signer         = new ModelSigner(new VirgilCardCrypto());

            var keyPair = crypto.GenerateKeys();

            signer.Sign(rawSignedModel,
                        new SignParams()
            {
                Signer           = "test_id",
                SignerPrivateKey = keyPair.PrivateKey
            });

            Assert.Throws <VirgilException>(
                () => signer.Sign(rawSignedModel,
                                  new SignParams()
            {
                Signer           = "test_id",
                SignerPrivateKey = keyPair.PrivateKey
            })
                );
        }
        public async Task GetSignleVirgilCard_ByGivenId_ShouldReturnVirgilCard()
        {
            var crypto        = new VirgilCrypto();
            var client        = IntegrationHelper.GetVirgilClient();
            var requestSigner = new RequestSigner(crypto);

            var appKey = crypto.ImportPrivateKey(IntegrationHelper.AppKey, IntegrationHelper.AppKeyPassword);

            // Prepare Requests

            var aliceIdentity  = "alice-" + Guid.NewGuid();
            var aliceKeys      = crypto.GenerateKeys();
            var alicePublicKey = crypto.ExportPublicKey(aliceKeys.PublicKey);

            var aliceRequest = new PublishCardRequest(aliceIdentity, "member", alicePublicKey);

            requestSigner.SelfSign(aliceRequest, aliceKeys.PrivateKey);
            requestSigner.AuthoritySign(aliceRequest, IntegrationHelper.AppID, appKey);

            var aliceCard = await client.PublishCardAsync(aliceRequest);

            var foundAliceCard = await client.GetCardAsync(aliceCard.Id);

            aliceCard.ShouldBeEquivalentTo(foundAliceCard);

            await IntegrationHelper.RevokeCard(aliceCard.Id);
        }
Esempio n. 10
0
        public void ValidateWithoutDefaultVerifiers_CardWithoutServiceSignature_ShouldReturnTrue()
        {
            var card = new CardModel(new PublishCardSnapshotModel
            {
                PublicKeyData = Convert.FromBase64String("MCowBQYDK2VwAyEAZzBtEQEWMQ9VeJrqSoO939VR5qimaTs4reqe9ut1VPk="),
            })
            {
                Id       = "eb95e1b31ff3090598a05bf108c06088af5f70cfd6338924932396e9dfce840a",
                Snapshot = Convert.FromBase64String("eyJpZGVudGl0eSI6ImFsaWNlIiwiaWRlbnRpdHlfdHlwZSI6Im1lbWJlciIsInB1YmxpY19rZXkiOiJNQ293QlFZREsyVndBeUVBWnpCdEVRRVdNUTlWZUpycVNvTzkzOVZSNXFpbWFUczRyZXFlOXV0MVZQaz0iLCJzY29wZSI6ImFwcGxpY2F0aW9uIiwiZGF0YSI6e30sImluZm8iOm51bGx9"),
                Meta     = new CardMetaModel
                {
                    Version    = "4.0",
                    Signatures = new Dictionary <string, byte[]>
                    {
                        ["eb95e1b31ff3090598a05bf108c06088af5f70cfd6338924932396e9dfce840a"] =
                            Convert.FromBase64String("MFEwDQYJYIZIAWUDBAICBQAEQFpw+jB5eDT1Dj3I2WqCewGqhAdG9f8pncAYeYcWHGWIONZlog1gjBb/y5/km8VbIPjrn4wlF0Ld8L5tRqRZOQM="),
                        ["0b23070f8bafc48765658b92f168ae70b7638bc6fde0d246258de8a1116a52c4"] =
                            Convert.FromBase64String("MFEwDQYJYIZIAWUDBAICBQAEQJggpfBBpO9mHG2Q7hxdkY5b20krS4w4WG6IxNUHGmN1ZvKq0LECgNc2yuvXkDiSqXQ011zN1yhGwxe/LwtkZg8=")
                    }
                }
            };

            var crypto    = new VirgilCrypto();
            var validator = new CardValidator(crypto);

            validator.Validate(card).Should().BeTrue();
        }
Esempio n. 11
0
        public static Tuple <Jwt, JwtGenerator> PredefinedToken(
            this Faker faker,
            VirgilAccessTokenSigner signer,
            TimeSpan lifeTime,
            out string apiPublicKeyId,
            out string apiPublicKeyBase64)
        {
            var crypto      = new VirgilCrypto();
            var apiKeyPair  = crypto.GenerateKeys();
            var fingerprint = crypto.GenerateHash(crypto.ExportPublicKey(apiKeyPair.PublicKey));

            apiPublicKeyId = Bytes.ToString(fingerprint, StringEncoding.HEX);

            apiPublicKeyBase64 = Bytes.ToString(
                crypto.ExportPublicKey(apiKeyPair.PublicKey), StringEncoding.BASE64);

            var jwtGenerator = new JwtGenerator(
                faker.AppId(),
                apiKeyPair.PrivateKey,
                apiPublicKeyId,
                lifeTime,
                signer);

            var additionalData = new Dictionary <string, string>
            {
                { "username", "some_username" }
            };
            var dict  = additionalData.ToDictionary(entry => (object)entry.Key, entry => (object)entry.Value);
            var token = jwtGenerator.GenerateToken("some_identity", dict);

            return(new Tuple <Jwt, JwtGenerator>(token, jwtGenerator));
        }
Esempio n. 12
0
        public void Ctor_ByteArrayGiven_HexStringShouldMatchWithVirgilCryptoImpl()
        {
            var hash = new VirgilCrypto().ComputeHash(Encoding.UTF8.GetBytes("1234567890"), HashAlgorithm.SHA256);
            var hex  = VirgilByteArrayUtils.BytesToHex(hash);

            hex.Should().Be(new Fingerprint(hash).ToHEX());
        }
Esempio n. 13
0
        public void ExtraSign_Should_AddValidSignature()
        {
            //STC-8
            var rawSignedModel = faker.PredefinedRawSignedModel(null, true, false, false);
            var crypto         = new VirgilCrypto();
            var signer         = new ModelSigner(new VirgilCardCrypto());

            Assert.AreEqual(rawSignedModel.Signatures.Count, 1);
            var keyPair    = crypto.GenerateKeys();
            var signParams = new SignParams()
            {
                Signer           = "test_id",
                SignerPrivateKey = keyPair.PrivateKey
            };

            signer.Sign(rawSignedModel, signParams
                        );
            Assert.AreEqual(rawSignedModel.Signatures.Count, 2);
            var extraSignature = rawSignedModel.Signatures.Last();

            Assert.AreEqual(extraSignature.Signer, signParams.Signer);
            Assert.AreEqual(extraSignature.Snapshot, null);
            Assert.True(crypto.VerifySignature(
                            extraSignature.Signature,
                            rawSignedModel.ContentSnapshot,
                            keyPair.PublicKey));
        }
        public void Export_WithoutParameters_ShouldBeEquivalentToImportedRequest()
        {
            var crypto = new VirgilCrypto();

            var aliceKeys         = crypto.GenerateKeys();
            var exportedPublicKey = crypto.ExportPublicKey(aliceKeys.PublicKey);

            const string identity     = "alice";
            const string identityType = "member";

            var request = new PublishCardRequest(
                identity: identity,
                identityType: identityType,
                publicKeyData: exportedPublicKey,
                customFields: new Dictionary <string, string>
            {
                ["key1"] = "value1",
                ["key2"] = "value2"
            },
                info: new CardInfoModel
            {
                Device     = "Device",
                DeviceName = "DeviceName"
            });

            var requestSigner = new RequestSigner(crypto);

            requestSigner.SelfSign(request, aliceKeys.PrivateKey);

            var exportedRequest = request.Export();
            var importedRequest = new PublishCardRequest(exportedRequest);

            request.ShouldBeEquivalentTo(importedRequest);
        }
Esempio n. 15
0
        public async Task EncryptAndDecrypt_UsingBrainKeys()
        {
            Func <TokenContext, Task <string> > tokenCallback = (c) =>
            {
                var virgilCrypto = new VirgilCrypto();
                var signer       = new VirgilAccessTokenSigner();

                var apiKey = virgilCrypto.ImportPrivateKey(
                    Bytes.FromString(AppSettings.Get.ApiKey, StringEncoding.BASE64));

                var generator = new JwtGenerator(AppSettings.Get.AppId, apiKey,
                                                 AppSettings.Get.ApiKeyId, TimeSpan.FromDays(1), signer);

                var jwt = generator.GenerateToken("BRAINKEY_CLIENT");

                return(Task.FromResult(jwt.ToString()));
            };

            var brainKey = BrainKey.Initialize(tokenCallback);
            var keyPair1 = await brainKey.GenerateKeyPair("some password");

            await Task.Delay(TimeSpan.FromSeconds(2));

            var keyPair2 = await brainKey.GenerateKeyPair("some password");

            await Task.Delay(TimeSpan.FromSeconds(2));

            var crypto       = new VirgilCrypto();
            var plaindata    = GetRandom.Bytes(128);
            var chipherdata  = crypto.SignThenEncrypt(plaindata, keyPair1.PrivateKey, keyPair2.PublicKey);
            var originaldata = crypto.DecryptThenVerify(chipherdata, keyPair2.PrivateKey, keyPair1.PublicKey);

            originaldata.Should().BeEquivalentTo(plaindata);
        }
Esempio n. 16
0
        public async Task CardManager_Should_RaiseException_IfExpiredToken()
        {
            // STC-26
            var aliceName = "alice-" + Guid.NewGuid();
            //var aliceCard = await IntegrationHelper.PublishCard(aliceName);
            var crypto  = new VirgilCrypto();
            var keypair = crypto.GenerateKeys();

            var jwtFromServer = await IntegrationHelper.EmulateServerResponseToBuildTokenRequest(
                new TokenContext(faker.Random.AlphaNumeric(20), "some_operation"), 0.3
                );

            var jwt = new Jwt(jwtFromServer);
            var constAccessTokenProvider = new ConstAccessTokenProvider(jwt);

            var cardManager = IntegrationHelper.GetManagerWithConstAccessTokenProvider(constAccessTokenProvider);
            var aliceCard   = await cardManager.PublishCardAsync(
                new CardParams()
            {
                Identity       = aliceName,
                PublicKey      = keypair.PublicKey,
                PrivateKey     = keypair.PrivateKey,
                PreviousCardId = null,
                ExtraFields    = new Dictionary <string, string>
                {
                    { "some meta key", "some meta val" }
                }
            });

            // var aaa = await IntegrationHelper.GetCardAsync(aliceCard.Id);
            Thread.Sleep(30000);
            Assert.ThrowsAsync <UnauthorizedClientException>(
                async() => await cardManager.GetCardAsync(aliceCard.Id));
        }
        public async Task SearchForVirgilCards_ValidationWithServiceKey_ShouldPassValidation()
        {
            var crypto = new VirgilCrypto();
            var client = IntegrationHelper.GetVirgilClient();

            client.SetCardValidator(new CardValidator(crypto));

            // CREATING A VIRGIL CARD

            var appKey = crypto.ImportPrivateKey(IntegrationHelper.AppKey, IntegrationHelper.AppKeyPassword);

            var aliceKeys         = crypto.GenerateKeys();
            var exportedPublicKey = crypto.ExportPublicKey(aliceKeys.PublicKey);

            var aliceIdentity = "alice-" + Guid.NewGuid();
            var request       = new PublishCardRequest(aliceIdentity, "member", exportedPublicKey);

            var requestSigner = new RequestSigner(crypto);

            requestSigner.SelfSign(request, aliceKeys.PrivateKey);
            requestSigner.AuthoritySign(request, IntegrationHelper.AppID, appKey);

            var aliceCard = await client.PublishCardAsync(request);

            // VALIDATING A VIRGIL CARD

            var cards = await client.SearchCardsAsync(SearchCriteria.ByIdentity(aliceIdentity));

            aliceCard.ShouldBeEquivalentTo(cards.Single());

            await IntegrationHelper.RevokeCard(aliceCard.Id);
        }
Esempio n. 18
0
        public void Validate_CardWithFakedOwnerSignature_ShouldReturnFalse()
        {
            var card = new CardModel(new PublishCardSnapshotModel
            {
                PublicKeyData = Convert.FromBase64String("MCowBQYDK2VwAyEAZzBtEQEWMQ9VeJrqSoO939VR5qimaTs4reqe9ut1VPk="),
            })
            {
                Id       = "eb95e1b31ff3090598a05bf108c06088af5f70cfd6338924932396e9dfce840a",
                Snapshot = Convert.FromBase64String("eyJpZGVudGl0eSI6ImFsaWNlIiwiaWRlbnRpdHlfdHlwZSI6Im1lbWJlciIsInB1YmxpY19rZXkiOiJNQ293QlFZREsyVndBeUVBWnpCdEVRRVdNUTlWZUpycVNvTzkzOVZSNXFpbWFUczRyZXFlOXV0MVZQaz0iLCJzY29wZSI6ImFwcGxpY2F0aW9uIiwiZGF0YSI6e30sImluZm8iOm51bGx9"),
                Meta     = new CardMetaModel
                {
                    Version    = "4.0",
                    Signatures = new Dictionary <string, byte[]>
                    {
                        ["eb95e1b31ff3090598a05bf108c06088af5f70cfd6338924932396e9dfce840a"] =
                            Convert.FromBase64String("MFEwDQYJYIZIAWUDBAICBQAEQMpaO3OmXlsYhzR7pvF0Xuu7Dv84r3SRrmqjMvod9ik+oQ0M0uc+dwHNeNtQpy84qI14cXXaMAJDcfgtKyHPdA0="),
                        ["0b23070f8bafc48765658b92f168ae70b7638bc6fde0d246258de8a1116a52c4"] =
                            Convert.FromBase64String("MFEwDQYJYIZIAWUDBAICBQAEQJggpfBBpO9mHG2Q7hxdkY5b20krS4w4WG6IxNUHGmN1ZvKq0LECgNc2yuvXkDiSqXQ011zN1yhGwxe/LwtkZg8="),
                        ["3e29d43373348cfb373b7eae189214dc01d7237765e572db685839b64adca853"] =
                            Convert.FromBase64String("MFEwDQYJYIZIAWUDBAICBQAEQMpaO3OmXlsYhzR7pvF0Xuu7Dv84r3SRrmqjMvod9ik+oQ0M0uc+dwHNeNtQpy84qI14cXXaMAJDcfgtKyHPdA0="),
                    }
                }
            };

            var crypto    = new VirgilCrypto();
            var validator = new CardValidator(crypto);

            validator.AddDefaultVerifiers();
            validator.Validate(card).Should().BeFalse();
        }
        public void GenerateHash_Should_GenerateNonEmptyArray()
        {
            var crypto = new VirgilCrypto();
            var hash   = crypto.GenerateHash(Encoding.UTF8.GetBytes("hi"));

            Assert.AreNotEqual(hash, null);
        }
Esempio n. 20
0
        public static byte[] EncryptMessage(byte[] senderPrivateKey, byte[] receiverPublicKey, byte[] plainText)
        {
            var crypto     = new VirgilCrypto(KeyPairType.EC_SECP256K1);
            var ecdhKey    = Ecdh(senderPrivateKey, receiverPublicKey);
            var newKeyPair = crypto.GenerateKeys(KeyPairType.EC_SECP256K1, ecdhKey);

            return(crypto.Encrypt(plainText, newKeyPair.PublicKey));
        }
Esempio n. 21
0
        public static byte[] DecryptMessage(byte[] senderPublicKey, byte[] receiverPrivateKey, byte[] cipherText)
        {
            var crypto     = new VirgilCrypto(KeyPairType.EC_SECP256K1);
            var ecdhKey    = Ecdh(receiverPrivateKey, senderPublicKey);
            var newKeyPair = crypto.GenerateKeys(KeyPairType.EC_SECP256K1, ecdhKey);

            return(crypto.Decrypt(cipherText, newKeyPair.PrivateKey));
        }
Esempio n. 22
0
        private Jwt JwtSignedByWrongApiKey(string identity)
        {
            var crypto              = new VirgilCrypto();
            var wrongApiKeyPair     = crypto.GenerateKeys();
            var wrongApiPublicKeyId = faker.AppId();

            return(GenerateJwt(identity, wrongApiKeyPair.PrivateKey, wrongApiPublicKeyId));
        }
Esempio n. 23
0
        public static KeyPair PredefinedVirgilKeyPair(this Faker faker)
        {
            var crypto     = new VirgilCrypto();
            var privateKey =
                crypto.ImportPrivateKey(Bytes.FromString(AppSettings.PredefinedPrivateKeyBase64, StringEncoding.BASE64));
            var publicKey = crypto.ExtractPublicKey(privateKey);

            return(new KeyPair((PublicKey)publicKey, (PrivateKey)privateKey));
        }
        public void DecryptEncryptedMessage_Should_ReturnEquivalentMessage()
        {
            var crypto        = new VirgilCrypto();
            var keyPair       = crypto.GenerateKeys();
            var messageBytes  = Encoding.UTF8.GetBytes("hi");
            var encryptedData = crypto.Encrypt(messageBytes, keyPair.PublicKey);

            Assert.AreEqual(messageBytes, crypto.Decrypt(encryptedData, keyPair.PrivateKey));
        }
        public void ExtractPublicKey_Should_ReturnEquivalentKey()
        {
            var crypto             = new VirgilCrypto();
            var keyPair            = crypto.GenerateKeys();
            var extractedPublicKey = crypto.ExtractPublicKey(keyPair.PrivateKey);

            Assert.IsTrue(((PublicKey)extractedPublicKey).RawKey.SequenceEqual(keyPair.PublicKey.RawKey));
            Assert.IsTrue(((PublicKey)extractedPublicKey).Id.SequenceEqual(keyPair.PublicKey.Id));
        }
        public void KeyPairId_Should_Be8BytesFromSha512FromPublicKey()
        {
            var crypto  = new VirgilCrypto();
            var keyPair = crypto.GenerateKeys();
            var keyId   = crypto.GenerateHash(keyPair.PublicKey.RawKey, HashAlgorithm.SHA512).Take(8).ToArray();

            Assert.AreEqual(keyPair.PrivateKey.Id, keyId);
            Assert.AreEqual(keyPair.PublicKey.Id, keyId);
        }
Esempio n. 27
0
        public async Task AddOrDeleteRelationWithoutAuthoritySign_ExceptionShouldOccur()
        {
            const string identityType  = "member";
            var          crypto        = new VirgilCrypto();
            var          client        = PredefinedClient(crypto);
            var          requestSigner = new RequestSigner(crypto);

            var aliceKeys = crypto.GenerateKeys();
            var aliceExportedPublicKey = crypto.ExportPublicKey(aliceKeys.PublicKey);
            var aliceRequest           = new PublishCardRequest("alice", identityType, aliceExportedPublicKey);

            var bobKeys = crypto.GenerateKeys();
            var bobExportedPublicKey = crypto.ExportPublicKey(bobKeys.PublicKey);
            var bobRequest           = new PublishCardRequest("bob", identityType, bobExportedPublicKey);

            var appId  = ConfigurationManager.AppSettings["virgil:AppID"];
            var appKey = crypto.ImportPrivateKey(
                VirgilBuffer.FromFile(ConfigurationManager.AppSettings["virgil:AppKeyPath"]).GetBytes(),
                ConfigurationManager.AppSettings["virgil:AppKeyPassword"]);


            // publish cards
            requestSigner.SelfSign(aliceRequest, aliceKeys.PrivateKey);
            requestSigner.AuthoritySign(aliceRequest, appId, appKey);
            var aliceCardModel = await client
                                 .PublishCardAsync(aliceRequest).ConfigureAwait(false);

            requestSigner.SelfSign(bobRequest, bobKeys.PrivateKey);
            requestSigner.AuthoritySign(bobRequest, appId, appKey);
            var bobCardModel = await client
                               .PublishCardAsync(bobRequest).ConfigureAwait(false);

            aliceCardModel.Meta.Relations.Count.ShouldBeEquivalentTo(0);


            // add Bob's card to Alice's relations
            var addRelationRequest = new AddRelationRequest(bobCardModel.SnapshotModel);

            Assert.ThrowsAsync <Exceptions.RelationException>(() => client.AddRelationAsync(addRelationRequest));

            // Delete Bob's card from Alice's relations
            var deleteRelationRequest = new DeleteRelationRequest(bobCardModel.Id, RevocationReason.Unspecified);

            Assert.ThrowsAsync <Exceptions.RelationException>(() => client.DeleteRelationAsync(deleteRelationRequest));

            // delete cards
            var revokeBobRequest = new RevokeCardRequest(bobCardModel.Id, RevocationReason.Unspecified);

            requestSigner.AuthoritySign(revokeBobRequest, appId, appKey);
            await client.RevokeCardAsync(revokeBobRequest);

            var revokeAliceRequest = new RevokeCardRequest(aliceCardModel.Id, RevocationReason.Unspecified);

            requestSigner.AuthoritySign(revokeAliceRequest, appId, appKey);
            await client.RevokeCardAsync(revokeAliceRequest);
        }
Esempio n. 28
0
        public void DecryptEncryptedMessageByGeneratedFromKeyMateria_Should_ReturnEquivalentMessage()
        {
            var crypto        = new VirgilCrypto();
            var keyMateria    = Encoding.UTF8.GetBytes("26dfhvnslvdsfkdfvnndsb234q2xrFOuY5EDSAFGCCXHCJSHJAD");
            var keyPair       = crypto.GenerateKeys(keyMateria);
            var messageBytes  = Encoding.UTF8.GetBytes("hi");
            var encryptedData = crypto.Encrypt(messageBytes, keyPair.PublicKey);

            Assert.AreEqual(messageBytes, crypto.Decrypt(encryptedData, keyPair.PrivateKey));
        }
        public void ExportPublicKey_Should_ReturnDerFormat()
        {
            var crypto    = new VirgilCrypto();
            var publicKey = crypto.ImportPublicKey(
                Convert.FromBase64String(AppSettings.PublicKeySTC32));
            var exportedPublicKey1Bytes = crypto.ExportPublicKey(publicKey);
            var privateKeyToDer         = VirgilKeyPair.PublicKeyToDER(((PublicKey)publicKey).RawKey);

            Assert.IsTrue(privateKeyToDer.SequenceEqual(exportedPublicKey1Bytes));
        }
        public void ImportExportedPublicKey_Should_ReturnEquivalentKey()
        {
            var crypto      = new VirgilCrypto();
            var keyPair     = crypto.GenerateKeys();
            var exportedKey = crypto.ExportPublicKey(keyPair.PublicKey);
            var importedKey = (PublicKey)crypto.ImportPublicKey(exportedKey);

            Assert.IsTrue(importedKey.Id.SequenceEqual(keyPair.PublicKey.Id));
            Assert.IsTrue(importedKey.RawKey.SequenceEqual(keyPair.PublicKey.RawKey));
        }