/// <summary> /// Creates a new <see cref="VirgilKey"/> with custom Public/Private key pair. /// </summary> /// <param name="keyName">Name of the key.</param> /// <param name="keyPair">The key pair.</param> /// <param name="password">The password.</param> /// <returns>The instance of <see cref="VirgilKey"/></returns> /// <exception cref="ArgumentException"></exception> /// <exception cref="ArgumentNullException"></exception> /// <exception cref="VirgilKeyIsAlreadyExistsException"></exception> public static VirgilKey Create(string keyName, KeyPair keyPair, string password = null) { if (string.IsNullOrWhiteSpace(keyName)) { throw new ArgumentException(Localization.ExceptionArgumentIsNullOrWhitespace, nameof(keyName)); } if (keyPair == null) { throw new ArgumentNullException(nameof(keyPair)); } var crypto = VirgilConfig.GetService <Crypto>(); var storage = VirgilConfig.GetService <IKeyStorage>(); if (storage.Exists(keyName)) { throw new VirgilKeyIsAlreadyExistsException(); } var virgilKey = new VirgilKey { KeyPair = keyPair, KeyName = keyName }; var exportedPrivateKey = crypto.ExportPrivateKey(virgilKey.KeyPair.PrivateKey, password); storage.Store(new KeyEntry { Name = keyName, Value = exportedPrivateKey }); return(virgilKey); }
/// <summary> /// Loads the <see cref="VirgilKey"/> by specified key name. /// </summary> /// <param name="keyName">Name of the key.</param> /// <param name="password">The password.</param> /// <returns>The instance of <see cref="VirgilKey"/></returns> /// <exception cref="ArgumentException"></exception> /// <exception cref="VirgilKeyIsNotFoundException"></exception> public static VirgilKey Load(string keyName, string password = null) { if (string.IsNullOrWhiteSpace(keyName)) { throw new ArgumentException(Localization.ExceptionArgumentIsNullOrWhitespace, nameof(keyName)); } var crypto = VirgilConfig.GetService <Crypto>(); var storage = VirgilConfig.GetService <IKeyStorage>(); if (!storage.Exists(keyName)) { throw new VirgilKeyIsNotFoundException(); } var entry = storage.Load(keyName); var privateKey = crypto.ImportPrivateKey(entry.Value, password); var publicKey = crypto.ExtractPublicKey(privateKey); var virgilKey = new VirgilKey { KeyName = keyName, KeyPair = new KeyPair(publicKey, privateKey) }; return(virgilKey); }