Beispiel #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);
            }
        }
        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);
        }
        public void DecryptEncryptedMessageWithWrongPassword_Should_RaiseException()
        {
            var crypto       = new VirgilCrypto();
            var aliceKeyPair = crypto.GenerateKeys();
            var bobKeyPair   = crypto.GenerateKeys();

            var messageBytes          = Encoding.UTF8.GetBytes("hi");
            var encryptedDataForAlice = crypto.Encrypt(messageBytes, aliceKeyPair.PublicKey);

            Assert.Throws <VirgilCryptoException>(() => crypto.Decrypt(encryptedDataForAlice, bobKeyPair.PrivateKey));
        }
        public async Task SearchForTheVirgilCards_MultipleIdentitiesGiven_ShouldReturnVirgilCards()
        {
            // Initialization

            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 bobIdentity  = "bob-" + Guid.NewGuid();
            var bobKeys      = crypto.GenerateKeys();
            var bobPublicKey = crypto.ExportPublicKey(bobKeys.PublicKey);

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

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

            requestSigner.SelfSign(bobRequest, bobKeys.PrivateKey);
            requestSigner.AuthoritySign(bobRequest, IntegrationHelper.AppID, appKey);

            // Publish Virgil Cards

            var aliceCard = await client.PublishCardAsync(aliceRequest);

            var bobCard = await client.PublishCardAsync(bobRequest);

            // Search for the Virgil Cards

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

            // Assertions

            foundCards.Should().HaveCount(2);

            foundCards.Single(it => it.Id == aliceCard.Id).ShouldBeEquivalentTo(aliceCard);
            foundCards.Single(it => it.Id == bobCard.Id).ShouldBeEquivalentTo(bobCard);

            await IntegrationHelper.RevokeCard(aliceCard.Id);

            await IntegrationHelper.RevokeCard(bobCard.Id);
        }
Beispiel #5
0
        public void SignAndEncryptData_PublicAndPrivateKeysGiven_ShouldDecryptAndVerifyDataSuccessfully()
        {
            var crypto = new VirgilCrypto();

            var alice = crypto.GenerateKeys();
            var bob   = crypto.GenerateKeys();

            var originalData = Encoding.UTF8.GetBytes(IntegrationHelper.RandomText);
            var cipherData   = crypto.SignThenEncrypt(originalData, alice.PrivateKey, bob.PublicKey);

            var decryptedData = crypto.DecryptThenVerify(cipherData, bob.PrivateKey, alice.PublicKey);

            decryptedData.ShouldAllBeEquivalentTo(originalData);
        }
        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);
        }
Beispiel #7
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
            })
                );
        }
Beispiel #8
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);
        }
        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);
        }
Beispiel #11
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);
        }
Beispiel #12
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));
        }
Beispiel #13
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);
        }
Beispiel #14
0
        public (IPublicKey, IPrivateKey) GenerateKeyPair(byte[] keyMaterial)
        {
            var crypto  = new VirgilCrypto();
            var keyPair = crypto.GenerateKeys(this.DefaultKeyPairType, keyMaterial);

            return(keyPair.PublicKey, keyPair.PrivateKey);
        }
Beispiel #15
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));
        }
Beispiel #16
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 Validate_Should_ValidateByAppSign()
        {
            var crypto               = new VirgilCrypto();
            var validator            = new VirgilCardVerifier(new VirgilCardCrypto());
            var vrigilPublicKeyBytes = crypto.ExportPublicKey(faker.PredefinedVirgilKeyPair().PublicKey);

            validator.ChangeServiceCreds(
                Bytes.ToString(vrigilPublicKeyBytes, StringEncoding.BASE64)
                );

            var appKeyPair = crypto.GenerateKeys();

            var appPublicKey = Bytes.ToString(crypto.ExportPublicKey(crypto.ExtractPublicKey(appKeyPair.PrivateKey)),
                                              StringEncoding.BASE64);

            var list = new List <VerifierCredentials>
            {
                new VerifierCredentials()
                {
                    Signer = "my_app", PublicKeyBase64 = appPublicKey
                }
            };

            //validator.Whitelist = list;
            var keypair    = crypto.GenerateKeys();
            var cardCrypto = new VirgilCardCrypto();

            /* var csr = CSR.Generate(cardCrypto, new CardParams
             * {
             *   Identity = "some_identity",
             *   PublicKey = crypto.ExtractPublicKey(keypair.PrivateKey),
             *   PrivateKey = keypair.PrivateKey
             * });
             *
             *
             * csr.Sign(cardCrypto, new ExtendedSignParams
             * {
             *   SignerId = "",
             *   SignerType = SignerType.App.ToLowerString(),
             *   SignerPrivateKey = appKeyPair.PrivateKey
             * });
             *
             * var card = CardUtils.Parse(cardCrypto, csr.RawSignedModel);
             *
             * var result = validator.VerifyCard(card);
             * result.Should().BeTrue();*/
        }
Beispiel #18
0
        private Jwt JwtSignedByWrongApiKey(string identity)
        {
            var crypto              = new VirgilCrypto();
            var wrongApiKeyPair     = crypto.GenerateKeys();
            var wrongApiPublicKeyId = faker.AppId();

            return(GenerateJwt(identity, wrongApiKeyPair.PrivateKey, wrongApiPublicKeyId));
        }
Beispiel #19
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));
        }
Beispiel #20
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));
        }
        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);
        }
        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));
        }
Beispiel #24
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 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));
        }
        public void SignData_PlainTextGiven_ShouldPassVerfifcation()
        {
            var crypto = new VirgilCrypto();

            var keyPair = crypto.GenerateKeys();
            var data    = Encoding.UTF8.GetBytes("Hello Bob!");

            var signature = crypto.Sign(data, keyPair.PrivateKey);

            crypto.Verify(data, signature, keyPair.PublicKey).Should().BeTrue();
        }
Beispiel #27
0
        public void EncryptData_SinglePublicKeyGiven_ShouldCipherDataBeDecrypted()
        {
            var crypto = new VirgilCrypto();

            var keyPair = crypto.GenerateKeys();

            var data          = Encoding.UTF8.GetBytes("Encrypt me!!!");
            var encryptedData = crypto.Encrypt(data, keyPair.PublicKey);
            var decryptedData = crypto.Decrypt(encryptedData, keyPair.PrivateKey);

            data.ShouldAllBeEquivalentTo(decryptedData);
        }
Beispiel #28
0
        public void SecondSelfSign_Should_ThrowException()
        {
            //STC-8
            var rawSignedModel = faker.PredefinedRawSignedModel(null, true, false, false);
            var crypto         = new VirgilCrypto();
            var keyPair        = crypto.GenerateKeys();
            var signer         = new ModelSigner(new VirgilCardCrypto());

            Assert.Throws <VirgilException>(
                () => signer.SelfSign(rawSignedModel, keyPair.PrivateKey)
                );
        }
        public AppDelegate()
        {
            var faker = new Faker();
            //try to use SDK PrivateKeyStorage
            var alias = faker.Person.UserName;

            var crypto     = new VirgilCrypto();
            var keypair    = crypto.GenerateKeys();
            var keyStorage = new PrivateKeyStorage(new VirgilPrivateKeyExporter(crypto));

            keyStorage.Store(keypair.PrivateKey, alias);
            keyStorage.Delete(alias);
        }
        public void GenerateSignature_Should_ReturnValidSignature()
        {
            var crypto            = new VirgilCrypto();
            var keyPair           = crypto.GenerateKeys();
            var snapshot          = Encoding.UTF8.GetBytes("some card snapshot");
            var signatureSnapshot = Encoding.UTF8.GetBytes("some signature snapshot");
            var extendedSnapshot  = signatureSnapshot != null
                ? CombineBytesArrays(snapshot, signatureSnapshot)
                : snapshot;

            var signature = crypto.GenerateSignature(extendedSnapshot, keyPair.PrivateKey);

            Assert.IsTrue(crypto.VerifySignature(signature, extendedSnapshot, keyPair.PublicKey));
        }