/// <summary> /// Imports the Private key from material representation. /// </summary> /// <param name="keyBytes">private key material representation bytes.</param> /// <param name="password">the password that was used during /// <see cref="ExportPrivateKey(IPrivateKey, string)"/>.</param> /// <returns>Imported private key.</returns> /// <example> /// <code> /// var crypto = new VirgilCardCrypto(); /// var privateKey = crypto.ImportPrivateKey(exportedPrivateKey, "my_password"); /// </code> /// </example> /// <remarks>How to get exportedPrivateKey <see cref="ExportPrivateKey(IPrivateKey, string)"/></remarks> public IPrivateKey ImportPrivateKey(byte[] keyBytes, string password) { if (keyBytes == null) { throw new ArgumentNullException("keyBytes"); } try { byte[] privateKeyBytes = string.IsNullOrEmpty(password) ? keyBytes : VirgilKeyPair.DecryptPrivateKey(keyBytes, Encoding.UTF8.GetBytes(password)); byte[] publicKey = VirgilKeyPair.ExtractPublicKey(privateKeyBytes, new byte[] { }); PrivateKey privateKey = new PrivateKey(); privateKey.Id = this.ComputePublicKeyHash(publicKey); privateKey.RawKey = VirgilKeyPair.PrivateKeyToDER(privateKeyBytes); return(privateKey); } catch (Exception ex) { throw new VirgilCryptoException(ex.Message); } }
public static async Task <PersonalCard> LoadLatest(IdentityInfo token, string privateKeyPassword = null) { var services = ServiceLocator.Services; var searchResult = await services.Cards.Search(token.Value, token.Type) .ConfigureAwait(false); var card = searchResult .OrderByDescending(it => it.CreatedAt) .Select(it => new { PublicKeyId = it.PublicKey.Id, Id = it.Id }) .FirstOrDefault(); if (card == null) { throw new CardNotFoundException("Card not found"); } var grabResponse = await services.PrivateKeys.Get(card.Id, token) .ConfigureAwait(false); if (!VirgilKeyPair.CheckPrivateKeyPassword(grabResponse.PrivateKey, privateKeyPassword.GetBytes())) { throw new WrongPrivateKeyPasswordException("Wrong password"); } var privateKey = new PrivateKey(grabResponse.PrivateKey); var cards = await services.Cards.GetCardsRealtedToThePublicKey(card.PublicKeyId, card.Id, privateKey, privateKeyPassword) .ConfigureAwait(false); return (cards.Select(it => new PersonalCard(it, privateKey)) .OrderByDescending(it => it.CreatedAt) .FirstOrDefault()); }
/// <summary> /// Generates asymmetric key pair that is comprised of both public and private keys by specified type. /// </summary> /// <param name="keyPairType">type of the generated keys. /// The possible values can be found in <see cref="KeyPairType"/>.</param> /// <param name="keyMaterial">the only data to be used for key generation, /// length must be more than 31.</param> /// <returns>Generated key pair with the specified type.</returns> /// <example> /// Generated key pair with type EC_SECP256R1. /// <code> /// var crypto = new VirgilCrypto(); /// var keyPair = crypto.GenerateKeys(KeyPairType.EC_SECP256R1); /// </code> /// </example> public KeyPair GenerateKeys(KeyPairType keyPairType, byte[] keyMaterial = null) { try { VirgilKeyPair keyPair; if (keyMaterial == null || keyMaterial.Length == 0) { keyPair = VirgilKeyPair.Generate(VirgilCryptoExtentions.ToVirgilKeyPairType(keyPairType)); } else { keyPair = VirgilKeyPair.GenerateFromKeyMaterial( VirgilCryptoExtentions.ToVirgilKeyPairType(keyPairType), keyMaterial); } byte[] keyPairId = this.ComputePublicKeyHash(keyPair.PublicKey()); PrivateKey privateKey = new PrivateKey(); privateKey.Id = keyPairId; privateKey.RawKey = VirgilKeyPair.PrivateKeyToDER(keyPair.PrivateKey()); PublicKey publicKey = new PublicKey(); publicKey.Id = keyPairId; publicKey.RawKey = VirgilKeyPair.PublicKeyToDER(keyPair.PublicKey()); return(new KeyPair(publicKey, privateKey)); } catch (Exception ex) { throw new VirgilCryptoException(ex.Message); } }
/// <summary> /// Generates and Registers a card for specified identity. /// </summary> private static async Task <ChatMember> Register(string email) { Console.WriteLine("\nGenerating and Publishing the keys...\n"); // generate a new public/private key pair. var keyPair = VirgilKeyPair.Generate(); // The app is registering a Virgil Card which includes a // public key and an email address identifier. The card will // be used for the public key identification and searching // for it in the Public Keys Service. var emailVerifier = await serviceHub.Identity.VerifyEmail(email); Console.WriteLine("\nThe email with confirmation code has been sent to your email address. Please check it!\n"); var confirmationCode = Param <string> .Mandatory("Enter Code: ").WaitInput(); var identity = await emailVerifier.Confirm(confirmationCode); var card = await serviceHub.Cards.Create(identity, keyPair.PublicKey(), keyPair.PrivateKey()); // Private key can be added to Virgil Security storage if you want to // easily synchronise yout private key between devices. await serviceHub.PrivateKeys.Stash(card.Id, keyPair.PrivateKey()); return(new ChatMember(card, keyPair.PrivateKey())); }
public async Task Confirm(string code) { var token = await this.request.Confirm(code); this.state = States.Confirmed; try { this.privateKeyResponse = await this.DownloadPrivateKey(token); } catch (VirgilPrivateServicesException e) when(e.ErrorCode == 40020) { throw new PrivateKeyNotFoundException(); } this.state = States.PrivateKeyDownloaded; if (VirgilKeyPair.IsPrivateKeyEncrypted(this.privateKeyResponse.PrivateKey) && !VirgilKeyPair.CheckPrivateKeyPassword( this.privateKeyResponse.PrivateKey, Encoding.UTF8.GetBytes(this.password)) ) { throw new WrongPrivateKeyPasswordException("Wrong password"); } var card = new PersonalCard(this.recipientCard, new PrivateKey(this.privateKeyResponse.PrivateKey)); this.aggregator.Publish(new CardLoaded(card, this.password)); this.state = States.Finished; }
/// <summary> /// Imports the Private key from material representation. /// </summary> public override IPrivateKey ImportPrivateKey(byte[] keyData, string password = null) { if (keyData == null) { throw new ArgumentNullException(nameof(keyData)); } try { var privateKeyBytes = string.IsNullOrEmpty(password) ? keyData : VirgilKeyPair.DecryptPrivateKey(keyData, Encoding.UTF8.GetBytes(password)); var publicKey = VirgilKeyPair.ExtractPublicKey(privateKeyBytes, new byte[] { }); var privateKey = new PrivateKey { ReceiverId = this.ComputePublicKeyHash(publicKey), Value = VirgilKeyPair.PrivateKeyToDER(privateKeyBytes) }; return(privateKey); } catch (Exception ex) { throw new CryptoException(ex.Message); } }
/// <summary> /// Generates asymmetric key pair that is comprised of both public and private keys by specified type. /// </summary> public KeyPair GenerateKeys(KeyPairType keyPairType) { try { using (var keyPair = VirgilKeyPair.Generate(keyPairType.ToVirgilKeyPairType())) { var keyPairId = this.ComputePublicKeyHash(keyPair.PublicKey()); var privateKey = new PrivateKey { ReceiverId = keyPairId, Value = VirgilKeyPair.PrivateKeyToDER(keyPair.PrivateKey()), }; var publicKey = new PublicKey { ReceiverId = keyPairId, Value = VirgilKeyPair.PublicKeyToDER(keyPair.PublicKey()) }; return(new KeyPair(publicKey, privateKey)); } } catch (Exception ex) { throw new CryptoException(ex.Message); } }
private byte[] ComputePublicKeyHash(byte[] publicKey) { byte[] publicKeyDER = VirgilKeyPair.PublicKeyToDER(publicKey); var hash = UseSHA256Fingerprints ? this.GenerateHash(publicKeyDER, HashAlgorithm.SHA256) : this.GenerateHash(publicKeyDER, HashAlgorithm.SHA512).Take(8).ToArray(); return(hash); }
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)); }
static public bool CheckKeys(string publicKey, string privateKey) { try { return(VirgilKeyPair.IsKeyPairMatch(Convert.FromBase64String(publicKey), Convert.FromBase64String(privateKey))); } catch { return(false); } }
/// <summary> /// Exports the Public key into material representation. /// </summary> /// <param name="publicKey">public key for export.</param> /// <returns>Key material representation bytes.</returns> /// <example> /// <code> /// var crypto = new VirgilCrypto(); /// var keyPair = crypto.GenerateKeys(); /// var exportedPublicKey = crypto.ExportPublicKey(keyPair.PublicKey); /// </code> /// </example> /// <remarks>How to import public key <see cref="ImportPublicKey(byte[])"/>.</remarks> /// <remarks>How to get generate keys <see cref="GenerateKeys()"/>.</remarks> public byte[] ExportPublicKey(IPublicKey publicKey) { try { return(VirgilKeyPair.PublicKeyToDER(VirgilCryptoExtentions.Get(publicKey).RawKey)); } catch (Exception ex) { throw new VirgilCryptoException(ex.Message); } }
/// <summary> /// Exports the Public key into material representation. /// </summary> public override byte[] ExportPublicKey(IPublicKey publicKey) { try { return(VirgilKeyPair.PublicKeyToDER(publicKey.Get().Value)); } catch (Exception ex) { throw new CryptoException(ex.Message); } }
internal PersonalCard(CardModel virgilCardDto, PublicKeyModel publicKey, PrivateKey privateKey) { this.VirgilCardDto = virgilCardDto; this.Id = virgilCardDto.Id; this.Identity = new Identity(virgilCardDto.Identity); this.PublicKey = new PublishedPublicKey(publicKey); this.Hash = virgilCardDto.Hash; this.CreatedAt = virgilCardDto.CreatedAt; this.PrivateKey = privateKey; this.IsPrivateKeyEncrypted = VirgilKeyPair.IsPrivateKeyEncrypted(privateKey); }
public static void GenerateKeys() { var keyPair = VirgilKeyPair .Generate(VirgilKeyPair.Type.FAST_EC_ED25519); //Will use generator but it is used for symetric crypto var secret = VirgilKeyPair .Generate(VirgilKeyPair.Type.FAST_EC_X25519) .PrivateKey(); File.WriteAllBytes(GetFileName(PUBLIC), keyPair.PublicKey()); File.WriteAllBytes(GetFileName(PRIVATE), keyPair.PrivateKey()); File.WriteAllBytes(GetFileName(SECRET), secret); }
public async static Task CreateKeyPair() { var keysService = new KeysClient(AppToken); var privateKeysService = new KeyringClient(AppToken); //var key = await keysService.PublicKeys.Search(EmailId); byte[] publicKey; byte[] privateKey; // Step 1. Generate Public/Private key pair. using (var keyPair = new VirgilKeyPair()) { publicKey = keyPair.PublicKey(); privateKey = keyPair.PrivateKey(); } Console.WriteLine("Generated Public/Private keys\n"); Console.WriteLine(Encoding.UTF8.GetString(publicKey)); Console.WriteLine(Encoding.UTF8.GetString(privateKey)); // Step 2. Register Public Key on Keys Service. var userData = new UserData { Class = UserDataClass.UserId, Type = UserDataType.EmailId, Value = EmailId }; var vPublicKey = await keysService.PublicKeys.Create(publicKey, privateKey, userData); // Step 3. Confirm UDID (User data identity) with code recived on email box. Console.WriteLine("Enter Confirmation Code:"); var confirmCode = Console.ReadLine(); await keysService.UserData.Confirm(vPublicKey.UserData.First().UserDataId, confirmCode, vPublicKey.PublicKeyId, privateKey); Console.WriteLine("Public Key has been successfully published." + vPublicKey.PublicKeyId); // Step 4. Store Private Key on Private Keys Service. await privateKeysService.Container.Initialize(ContainerType.Easy, vPublicKey.PublicKeyId, privateKey, ContainerPassword); privateKeysService.Connection.SetCredentials(new Credentials(EmailId, ContainerPassword)); await privateKeysService.PrivateKeys.Add(vPublicKey.PublicKeyId, privateKey); }
/// <summary> /// Imports the Public key from material representation. /// </summary> /// <param name="keyData">public key material representation bytes.</param> /// <returns>Imported public key.</returns> /// <example> /// <code> /// var crypto = new VirgilCrypto(); /// var publicKey = crypto.ImportPublicKey(exportedPublicKey); /// </code> /// </example> /// <remarks>How to get exportedPublicKey <see cref="ExportPublicKey(IPublicKey)"/>.</remarks> public IPublicKey ImportPublicKey(byte[] keyData) { try { PublicKey publicKey = new PublicKey(); publicKey.Id = this.ComputePublicKeyHash(keyData); publicKey.RawKey = VirgilKeyPair.PublicKeyToDER(keyData); return(publicKey); } catch (Exception ex) { throw new VirgilCryptoException(ex.Message); } }
static public string[] GetPublicPrivateKeys() { VirgilKeyPair pair = VirgilKeyPair.Generate(VirgilKeyPair.Type.EC_SECP256K1); var keys = new string[2]; keys[0] = Encoding.UTF8.GetString(pair.PublicKey()) .Replace("-----BEGIN PUBLIC KEY-----", "") .Replace("-----END PUBLIC KEY-----", "") .Replace("\n", ""); keys[1] = Encoding.UTF8.GetString(pair.PrivateKey()) .Replace("-----BEGIN EC PRIVATE KEY-----", "") .Replace("-----END EC PRIVATE KEY-----", "") .Replace("\n", ""); return(keys); }
/// <summary> /// Imports the Public key from material representation. /// </summary> public override IPublicKey ImportPublicKey(byte[] keyData) { try { var publicKey = new PublicKey { ReceiverId = this.ComputePublicKeyHash(keyData), Value = VirgilKeyPair.PublicKeyToDER(keyData) }; return(publicKey); } catch (Exception ex) { throw new CryptoException(ex.Message); } }
public void ExportPrivateKey_Should_ReturnDerFormat() { var privateKey2Passw = "qwerty"; var crypto = new VirgilCrypto(); var privateKey1 = crypto.ImportPrivateKey( Convert.FromBase64String(AppSettings.PrivateKeySTC31_1)); var privateKey2 = crypto.ImportPrivateKey( Convert.FromBase64String(AppSettings.PrivateKeySTC31_2), privateKey2Passw); var exportedPrivateKey1Bytes = crypto.ExportPrivateKey(privateKey1); var privateKeyToDer = VirgilKeyPair.PrivateKeyToDER(((PrivateKey)privateKey1).RawKey); var exportedPrivateKey2Bytes = crypto.ExportPrivateKey(privateKey2); var privateKeyToDer2 = VirgilKeyPair.PrivateKeyToDER(((PrivateKey)privateKey2).RawKey); Assert.IsTrue(privateKeyToDer.SequenceEqual(exportedPrivateKey1Bytes)); Assert.IsTrue(privateKeyToDer2.SequenceEqual(exportedPrivateKey2Bytes)); }
public void DecryptWithAnotherPassword(string anotherPassword) { if (VirgilKeyPair.IsPrivateKeyEncrypted(this.privateKeyResponse.PrivateKey) && !VirgilKeyPair.CheckPrivateKeyPassword( this.privateKeyResponse.PrivateKey, Encoding.UTF8.GetBytes(anotherPassword)) ) { throw new WrongPrivateKeyPasswordException("Wrong password"); } var card = new PersonalCard(this.recipientCard, new PrivateKey(this.privateKeyResponse.PrivateKey)); this.aggregator.Publish(new CardLoaded(card, anotherPassword)); }
/// <summary> /// Extracts the Public key from the specified <see cref="IPrivateKey"/> /// </summary> /// <param name="privateKey"> The private key.</param> /// <returns>The instance of <see cref="IPublicKey"/></returns> public IPublicKey ExtractPublicKey(IPrivateKey privateKey) { try { byte[] publicKeyData = VirgilKeyPair.ExtractPublicKey( VirgilCryptoExtentions.Get(privateKey).RawKey, new byte[] { }); PublicKey publicKey = new PublicKey(); publicKey.Id = VirgilCryptoExtentions.Get(privateKey).Id; publicKey.RawKey = VirgilKeyPair.PublicKeyToDER(publicKeyData); return(publicKey); } catch (Exception ex) { throw new VirgilCryptoException(ex.Message); } }
/// <summary> /// Extracts the Public key from Private key. /// </summary> public override IPublicKey ExtractPublicKey(IPrivateKey privateKey) { try { var publicKeyData = VirgilKeyPair.ExtractPublicKey(privateKey.Get().Value, new byte[] { }); var publicKey = new PublicKey { ReceiverId = privateKey.Get().ReceiverId, Value = VirgilKeyPair.PublicKeyToDER(publicKeyData) }; return(publicKey); } catch (Exception ex) { throw new CryptoException(ex.Message); } }
/// <summary> /// Exports the Private key into material representation. /// </summary> public override byte[] ExportPrivateKey(IPrivateKey privateKey, string password = null) { try { if (string.IsNullOrEmpty(password)) { return(VirgilKeyPair.PrivateKeyToDER(privateKey.Get().Value)); } var passwordBytes = Encoding.UTF8.GetBytes(password); var encryptedKey = VirgilKeyPair.EncryptPrivateKey(privateKey.Get().Value, passwordBytes); return(VirgilKeyPair.PrivateKeyToDER(encryptedKey, passwordBytes)); } catch (Exception ex) { throw new CryptoException(ex.Message); } }
public override void Execute() { Console.Write("Enter text to sign: "); var dataToSign = Encoding.UTF8.GetBytes(Console.ReadLine()); // generate public/private key pair byte[] publicKey; byte[] privateKey; using (var keyPair = new VirgilKeyPair()) { publicKey = keyPair.PublicKey(); privateKey = keyPair.PrivateKey(); } using (var signer = new VirgilSigner()) { this.StartWatch(); var sign = signer.Sign(dataToSign, privateKey); this.StopWatch(); Console.WriteLine("Digital signature in Base64: {0}", Convert.ToBase64String(sign)); this.DisplayElapsedTime(); this.RestartWatch(); var isValid = signer.Verify(dataToSign, sign, publicKey); this.StopWatch(); Console.WriteLine("Verification result is: {0}", isValid); this.DisplayElapsedTime(); } }
/// <summary> /// Exports the Private key into material representation. /// </summary> /// <param name="privateKey">private key for export.</param> /// <param name="password">password that is used for encryption of private key raw bytes.</param> /// <returns>Private key material representation bytes.</returns> /// <example> /// <code> /// var crypto = new VirgilCrypto(); /// var keyPair = crypto.GenerateKeys(); /// var crypto = new VirgilCrypto(); /// var exportedPrivateKey = crypto.ExportPrivateKey(keyPair.PrivateKey, "my_password"); /// </code> /// </example> /// <remarks>How to import private key <see cref="ImportPrivateKey(byte[], string)"/>.</remarks> /// <remarks>How to get generate keys <see cref="VirgilCrypto.GenerateKeys()"/>.</remarks> public byte[] ExportPrivateKey(IPrivateKey privateKey, string password) { if (privateKey == null) { throw new ArgumentNullException("privateKey"); } try { if (string.IsNullOrEmpty(password)) { return(VirgilKeyPair.PrivateKeyToDER(VirgilCryptoExtentions.Get(privateKey).RawKey)); } byte[] passwordBytes = Encoding.UTF8.GetBytes(password); byte[] encryptedKey = VirgilKeyPair.EncryptPrivateKey(VirgilCryptoExtentions.Get(privateKey).RawKey, passwordBytes); return(VirgilKeyPair.PrivateKeyToDER(encryptedKey, passwordBytes)); } catch (Exception ex) { throw new VirgilCryptoException(ex.Message); } }
public override void Execute() { var password = Param <string> .Optional("Enter password").WaitInput(); var type = Param <VirgilKeyPair.Type> .Optional("Enter keys type").WaitInput(); var isBase64 = Param <bool> .Optional("Output in Base64 format yes/no?").WaitInput(); Console.WriteLine(); this.StartWatch(); var keyPair = string.IsNullOrWhiteSpace(password) ? VirgilKeyPair.Generate(type) : VirgilKeyPair.Generate(type, Encoding.UTF8.GetBytes(password)); this.StopWatch(); // Output var publicKey = keyPair.PublicKey(); var privateKey = keyPair.PrivateKey(); if (isBase64) { Console.WriteLine("Public Key\n\n" + Convert.ToBase64String(publicKey) + "\n"); Console.WriteLine("Private Key\n\n" + Convert.ToBase64String(privateKey) + "\n"); } else { Console.WriteLine(Encoding.UTF8.GetString(publicKey)); Console.WriteLine(Encoding.UTF8.GetString(privateKey)); } this.DisplayElapsedTime(); }
public PublicKey(VirgilKeyPair nativeKeyPair) { this.Data = nativeKeyPair.PublicKey(); }
private byte[] ComputePublicKeyHash(byte[] publicKey) { var publicKeyDER = VirgilKeyPair.PublicKeyToDER(publicKey); return(this.ComputeHash(publicKeyDER, HashAlgorithm.SHA256)); }
public bool IsPasswordValid(string anotherPassword) { return(VirgilKeyPair.CheckPrivateKeyPassword(this.privateKeyResponse.PrivateKey, Encoding.UTF8.GetBytes(anotherPassword))); }
public bool CheckPrivateKeyPassword(string password) { return(VirgilKeyPair.CheckPrivateKeyPassword(this.PrivateKey.Data, password.GetBytes())); }