public override int Run(string[] remainingArguments) { var ret = 0; Crypter crypter = null; IKeySet ks = new KeySet(_location); Func <string> prompt = CachedPrompt.Password(() => { Console.WriteLine(Localized.MsgForKeySet); return(Util.PromptForPassword()); }).Prompt; IDisposable dks = null; if (!String.IsNullOrWhiteSpace(_crypterLocation)) { if (_password) { var cks = new PbeKeySet(_crypterLocation, prompt); crypter = new Crypter(cks); dks = cks; } else { crypter = new Crypter(_crypterLocation); } ks = new EncryptedKeySet(ks, crypter); } else if (_password) { ks = new PbeKeySet(ks, prompt); } var d2ks = ks as IDisposable; using (crypter) using (dks) using (d2ks) { if (!ks.ExportPrimaryAsPkcs(_destination, CachedPrompt.Password(() => { Console.WriteLine( Localized.MsgForExport); return (Util.DoublePromptForPassword ()); }).Prompt)) { ret = -1; } else { Console.WriteLine(Localized.MsgExportedPem); } } return(ret); }
/// <summary> /// Import the PKCS key. /// </summary> /// <param name="purpose">The purpose.</param> /// <param name="input">The input.</param> /// <param name="passwordPrompt">The pass phrase prompt.</param> /// <param name="official"></param> /// <param name="hint"></param> /// <returns></returns> /// <exception cref="InvalidKeySetException">DSA key cannot be used for encryption and decryption!</exception> /// <exception cref="InvalidKeySetException">Unsupported key type!</exception> public virtual ImportedKeySet PkcsKey(KeyPurpose purpose, Stream input, Func <string> passwordPrompt = null, bool official = false, KeyType hint = null) { using (var password = CachedPrompt.Password(passwordPrompt)) { AsymmetricKeyParameter bouncyKey; var resetStream = Utility.ResetStreamWhenFinished(input); using (var streamReader = new NondestructiveStreamReader(input)) { bouncyKey = new PemReader(streamReader, new PasswordFinder(password.Prompt)).ReadObject() as AsymmetricKeyParameter; } if (bouncyKey == null) { resetStream.Reset(); bouncyKey = passwordPrompt == null ? PrivateKeyFactory.CreateKey(input) : PrivateKeyFactory.DecryptKey( (password.Prompt() ?? String.Empty).ToCharArray(), input); } Key key; switch (bouncyKey) { case RsaPrivateCrtKeyParameters rsa: key = KeyFromBouncyCastle(rsa, purpose, official, hint); break; case DsaPrivateKeyParameters dsa: if (KeyPurpose.DecryptAndEncrypt == purpose) { throw new InvalidKeySetException("DSA key cannot be used for encryption and decryption!"); } key = KeyFromBouncyCastle(dsa); break; case RsaKeyParameters rsa: key = KeyFromBouncyCastle(rsa, purpose, official, hint); break; case DsaPublicKeyParameters dsa: if (KeyPurpose.Encrypt == purpose) { throw new InvalidKeySetException("DSA key cannot be used for encryption!"); } key = KeyFromBouncyCastle(dsa); break; default: throw new InvalidKeySetException("Unsupported key type!"); } return(new ImportedKeySet(key, purpose, "imported from pkcs file")); } }
public override int Run(string[] remainingArguments) { IKeySet ks = new FileSystemKeySet(_location); bool add = !ks.Metadata.Encrypted; Func <string> prompt = CachedPrompt.Password(Util.PromptForPassword).Prompt; if (!add) { Console.WriteLine(Localized.PasswordPromptOldPassword); ks = new PbeKeySet(ks, prompt); } using (ks as PbeKeySet) using (var keySet = new MutableKeySet(ks)) { keySet.ForceKeyDataChange(); IKeySetWriter writer = new FileSystemKeySetWriter(_location, overwrite: true); if (!_remove) { Console.WriteLine(Localized.PasswordPromptNewPassword); Func <string> newPrompt = CachedPrompt.Password(Util.DoublePromptForPassword).Prompt; writer = new PbeKeySetWriter(writer, newPrompt); } else { keySet.Metadata.Encrypted = false; } using (writer as PbeKeySetWriter) { if (keySet.Save(writer)) { if (_remove) { Console.WriteLine(Localized.MsgRemovedPassword); } else if (add) { Console.WriteLine(Localized.MsgAddedPasssword); } else { Console.WriteLine(Localized.MsgChangedPassword); } return(0); } return(-1); } } }
protected IKeySet ProduceKeySet(string location, string crypterLocation, bool password, out IDisposable d1, out IDisposable d2, out IDisposable d3) { if (String.IsNullOrWhiteSpace(location)) { d1 = null; d2 = null; d3 = null; return(null); } Crypter crypter = null; IKeySet ks = new FileSystemKeySet(location); Func <string> prompt = CachedPrompt.Password(Util.PromptForPassword).Prompt; IDisposable dks = null; if (!String.IsNullOrWhiteSpace(crypterLocation)) { if (password) { var cks = KeySet.LayerSecurity(FileSystemKeySet.Creator(crypterLocation), PbeKeySet.Creator(prompt) ); crypter = new Crypter(cks); dks = cks; } else { crypter = new Crypter(crypterLocation); } ks = new EncryptedKeySet(ks, crypter); } else if (_password) { ks = new PbeKeySet(ks, prompt); } d1 = crypter; d2 = dks; d3 = ks; return(ks); }
/// <summary> /// Initializes a new instance of the <see cref="PbeKeySetWriter"/> class. /// </summary> /// <param name="writer">The writer.</param> /// <param name="passwordPrompt">The password prompt.</param> /// <param name="iterationCount">The interations count.</param> public PbeKeySetWriter(IKeySetWriter writer, Func <string> passwordPrompt, int iterationCount = 4096) { _password = CachedPrompt.Password(passwordPrompt); _writer = writer; _iterationCount = iterationCount; }
public override int Run(string[] remainingArguments) { var ret = 0; Crypter crypter = null; IKeySet ks = new FileSystemKeySet(_location); Func <string> prompt = CachedPrompt.Password(Util.PromptForPassword).Prompt; IDisposable dks = null; if (!String.IsNullOrWhiteSpace(_crypterLocation)) { if (_password) { var cks = KeySet.LayerSecurity(FileSystemKeySet.Creator(_crypterLocation), PbeKeySet.Creator(prompt) ); crypter = new Crypter(cks); dks = cks; } else { crypter = new Crypter(_crypterLocation); } ks = new EncryptedKeySet(ks, crypter); } else if (_password) { ks = new PbeKeySet(ks, prompt); } var d2ks = ks as IDisposable; using (crypter) using (dks) using (d2ks) using (var keySet = new MutableKeySet(ks)) { var pubKeySet = keySet.PublicKey(); if (pubKeySet != null) { using (pubKeySet) { IKeySetWriter writer = new FileSystemKeySetWriter(_destination, overwrite: false); if (pubKeySet.Save(writer)) { Console.WriteLine(Localized.MsgNewPublicKeySet); ret = 0; } else { ret = -1; } } } else { ret = -1; } } return(ret); }
/// <summary> /// Initializes a new instance of the <see cref="EncryptedKeySet"/> class. /// </summary> /// <param name="keySet">The key set.</param> /// <param name="passwordPrompt">The password prompt.</param> public PbeKeySet(IKeySet keySet, Func <string> passwordPrompt) { _keySet = keySet; _password = CachedPrompt.Password(passwordPrompt); }
/// <summary> /// Import the PKCS key. /// </summary> /// <param name="purpose">The purpose.</param> /// <param name="input">The input.</param> /// <param name="passwordPrompt">The pass phrase prompt.</param> /// <returns></returns> /// <exception cref="InvalidKeySetException">DSA key cannot be used for encryption and decryption!</exception> /// <exception cref="InvalidKeySetException">Unsupported key type!</exception> public virtual ImportedKeySet PkcsKey(KeyPurpose purpose, Stream input, Func <string> passwordPrompt = null) { using (var password = CachedPrompt.Password(passwordPrompt)) { AsymmetricKeyParameter bouncyKey; var resetStream = Utility.ResetStreamWhenFinished(input); using (var streamReader = new NondestructiveStreamReader(input)) { bouncyKey = new PemReader(streamReader, new PasswordFinder(password.Prompt)).ReadObject() as AsymmetricKeyParameter; } if (bouncyKey == null) { resetStream.Reset(); bouncyKey = passwordPrompt == null ? PrivateKeyFactory.CreateKey(input) : PrivateKeyFactory.DecryptKey( (password.Prompt() ?? String.Empty).ToCharArray(), input); } Key key; if (bouncyKey is RsaPrivateCrtKeyParameters) { var keyParam = bouncyKey as RsaPrivateCrtKeyParameters; key = new RsaPrivateKey() { PublicKey = new RsaPublicKey() { Modulus = keyParam.Modulus.ToSystemBigInteger(), PublicExponent = keyParam.PublicExponent.ToSystemBigInteger(), Size = keyParam.Modulus.BitLength, }, PrimeP = keyParam.P.ToSystemBigInteger(), PrimeExponentP = keyParam.DP.ToSystemBigInteger(), PrimeExponentQ = keyParam.DQ.ToSystemBigInteger(), PrimeQ = keyParam.Q.ToSystemBigInteger(), CrtCoefficient = keyParam.QInv.ToSystemBigInteger(), PrivateExponent = keyParam.Exponent.ToSystemBigInteger(), Size = keyParam.Modulus.BitLength, }; } else if (bouncyKey is DsaPrivateKeyParameters) { var keyParam = bouncyKey as DsaPrivateKeyParameters; if (KeyPurpose.DecryptAndEncrypt == purpose) { throw new InvalidKeySetException("DSA key cannot be used for encryption and decryption!"); } key = new DsaPrivateKey() { X = keyParam.X.ToSystemBigInteger(), PublicKey = new DsaPublicKey { Y = keyParam.Parameters.G.ModPow(keyParam.X, keyParam.Parameters.P) .ToSystemBigInteger(), G = keyParam.Parameters.G.ToSystemBigInteger(), P = keyParam.Parameters.P.ToSystemBigInteger(), Q = keyParam.Parameters.Q.ToSystemBigInteger(), Size = keyParam.Parameters.P.BitLength }, Size = keyParam.Parameters.P.BitLength }; } else { throw new InvalidKeySetException("Unsupported key type!"); } return(new ImportedKeySet(key, purpose, "imported from pkcs file")); } }
public override int Run(string[] remainingArguments) { var ret = 0; Crypter crypter = null; IKeySet ks = new KeySet(_location); Func <string> singlePrompt = CachedPrompt.Password(() => { Console.WriteLine(Localized.MsgForKeySet); return(Util.PromptForPassword()); }).Prompt; var prompt = ks.Metadata.Encrypted ? singlePrompt : CachedPrompt.Password(() => { Console.WriteLine(Localized.MsgForKeySet); return(Util.PromptForPassword()); }).Prompt; IDisposable dks = null; if (!String.IsNullOrWhiteSpace(_crypterLocation)) { if (_password) { var cks = new PbeKeySet(_crypterLocation, singlePrompt); crypter = new Crypter(cks); dks = cks; } else { crypter = new Crypter(_crypterLocation); } ks = new EncryptedKeySet(ks, crypter); } else if (_password) { ks = new PbeKeySet(ks, prompt); } var d2ks = ks as IDisposable; using (crypter) using (dks) using (d2ks) using (var keySet = new MutableKeySet(ks)) { if (_status != KeyStatus.Primary && _status != KeyStatus.Active) { Console.WriteLine("{0} {1}.", Localized.Status, _status.Identifier); return(-1); } ImportedKeySet importedKeySet = null; try { importedKeySet = ImportedKeySet.Import.X509Certificate(keySet.Metadata.Purpose, _importLocation); } catch { importedKeySet = ImportedKeySet.Import.PkcsKey( keySet.Metadata.Purpose, _importLocation, CachedPrompt.Password(() => { Console.WriteLine(Localized.MsgForImport); return(Util.PromptForPassword()); }).Prompt); } if (importedKeySet == null) { Console.WriteLine(Localized.MsgUnparsableImport); ret = -1; } else { if (keySet.Metadata.KeyType != importedKeySet.Metadata.KeyType) { if (!keySet.Metadata.Versions.Any()) { keySet.Metadata.KeyType = importedKeySet.Metadata.KeyType; } else { ret = -1; Console.WriteLine(Localized.MsgConflictingKeyTypes, keySet.Metadata.KeyType.Identifier, importedKeySet.Metadata.KeyType); } } using (importedKeySet) { if (ret != -1) { var ver = keySet.AddKey(_status, importedKeySet.GetKey(1)); IKeySetWriter writer = new KeySetWriter(_location, overwrite: true); if (crypter != null) { writer = new EncryptedKeySetWriter(writer, crypter); } else if (_password) { writer = new PbeKeySetWriter(writer, prompt); } if (keySet.Save(writer)) { Console.WriteLine("{0} {1}.", Localized.MsgImportedNewKey, ver); ret = 0; } else { ret = -1; } } } } } return(ret); }
public override int Run(string[] remainingArguments) { var ret = 0; Crypter crypter = null; IKeySet ks = new KeySet(_location); Func <string> crypterPrompt = CachedPrompt.Password(Util.PromptForPassword).Prompt; var prompt = ks.Metadata.Encrypted ? new Func <string>(CachedPrompt.Password(Util.PromptForPassword).Prompt) : new Func <string>(CachedPrompt.Password(Util.DoublePromptForPassword).Prompt); IDisposable dks = null; if (!String.IsNullOrWhiteSpace(_crypterLocation)) { if (_password) { var cks = new PbeKeySet(_crypterLocation, crypterPrompt); crypter = new Crypter(cks); dks = cks; } else { crypter = new Crypter(_crypterLocation); } ks = new EncryptedKeySet(ks, crypter); } else if (_password) { ks = new PbeKeySet(ks, prompt); } var d2ks = ks as IDisposable; using (crypter) using (dks) using (d2ks) using (var keySet = new MutableKeySet(ks)) { if (_status != KeyStatus.Primary && _status != KeyStatus.Active) { Console.WriteLine("{0} {1}.", Localized.MsgInvalidStatus, _status.Identifier); return(-1); } object options = null; if (!String.IsNullOrWhiteSpace(_padding)) { options = new { Padding = _padding }; } var ver = keySet.AddKey(_status, _size, options); IKeySetWriter writer = new KeySetWriter(_location, overwrite: true); if (crypter != null) { writer = new EncryptedKeySetWriter(writer, crypter); } else if (_password) { writer = new PbeKeySetWriter(writer, prompt); } using (writer as IDisposable) { try { if (keySet.Save(writer)) { Console.WriteLine("{0} {1}.", Localized.MsgCreatedKey, ver); ret = 0; } else { ret = -1; } } catch { ret = -1; } } } if (ret != 0) { Console.WriteLine("{0} {1}.", Localized.MsgCouldNotWrite, _location); } return(ret); }
public override int Run(string[] remainingArguments) { var ret = 0; Crypter crypter = null; IKeySet ks = new FileSystemKeySet(_location); Func <string> singlePrompt = CachedPrompt.Password(() => { Console.WriteLine(Localized.MsgForKeySet); return(Util.PromptForPassword()); }).Prompt; var prompt = ks.Metadata.Encrypted ? singlePrompt : CachedPrompt.Password(() => { Console.WriteLine(Localized.MsgForKeySet); return(Util.PromptForPassword()); }).Prompt; IDisposable dks = null; if (!String.IsNullOrWhiteSpace(_crypterLocation)) { if (_password) { var cks = KeySet.LayerSecurity(FileSystemKeySet.Creator(_crypterLocation), PbeKeySet.Creator(singlePrompt)); crypter = new Crypter(cks); dks = cks; } else { crypter = new Crypter(_crypterLocation); } ks = new EncryptedKeySet(ks, crypter); } else if (_password) { ks = new PbeKeySet(ks, prompt); } var d2ks = ks as IDisposable; using (crypter) using (dks) using (d2ks) using (var keySet = new MutableKeySet(ks)) { var official = keySet.Metadata.OriginallyOfficial && keySet.Metadata.ValidOfficial() && !_force; KeyType hint = null; if (!String.IsNullOrWhiteSpace(_type)) { hint = AddKey.KeyTypeForString(_type); } if (_status != KeyStatus.Primary && _status != KeyStatus.Active) { Console.WriteLine("{0} {1}.", Localized.Status, _status.Identifier); return(-1); } ImportedKeySet importedKeySet = null; try { importedKeySet = ImportedKeySet.Import.X509Certificate(keySet.Metadata.Purpose, _importLocation, official, hint); } catch { if (_importLocation.EndsWith("pfx", StringComparison.Ordinal) || _importLocation.EndsWith("p12", StringComparison.Ordinal) ) { importedKeySet = ImportedKeySet.Import.Pkcs12Keys( keySet.Metadata.Purpose, _importLocation, CachedPrompt.Password(() => { Console.WriteLine(Localized.MsgForImport); return(Util.PromptForPassword()); }).Prompt, official, hint); } else { importedKeySet = ImportedKeySet.Import.PkcsKey( keySet.Metadata.Purpose, _importLocation, CachedPrompt.Password(() => { Console.WriteLine(Localized.MsgForImport); return(Util.PromptForPassword()); }).Prompt, official, hint); } } if (importedKeySet == null) { Console.WriteLine(Localized.MsgUnparsableImport); ret = -1; } else { if (keySet.Metadata.OriginallyOfficial && keySet.Metadata.ValidOfficial()) { if (!_force && !importedKeySet.Metadata.ValidOfficial()) { var keySetKeyType = keySet.Metadata.OfficialKeyType(); ret = -1; Console.WriteLine(Localized.MsgMismatchedType, "Multiple Types", keySetKeyType); } else { var importedKeyType = importedKeySet.Metadata.OfficialKeyType(); var keySetKeyType = keySet.Metadata.OfficialKeyType(); if (importedKeyType != keySetKeyType && !_force) { ret = -1; Console.WriteLine(Localized.MsgMismatchedType, importedKeyType, keySetKeyType); } } } if (keySet.Metadata.Kind != importedKeySet.Metadata.Kind) { if (!keySet.Metadata.Versions.Any()) { keySet.Metadata.Kind = importedKeySet.Metadata.Kind; } else { ret = -1; Console.WriteLine(Localized.MsgConflictingKeyTypes, keySet.Metadata.Kind.Identifier, importedKeySet.Metadata.Kind); } } using (importedKeySet) { if (ret != -1) { var count = importedKeySet.Metadata.Versions.Count(); var outMsg = ""; foreach (var v in importedKeySet.Metadata.Versions) { var status = v.Status; if (count == 1 || _status != KeyStatus.Primary) { status = _status; } var ver = keySet.AddKey(status, importedKeySet.GetKey(v.VersionNumber)); outMsg = ver.ToString(); } if (count > 1) { outMsg = $"{count} keys"; } IKeySetWriter writer = new FileSystemKeySetWriter(_location, overwrite: true); if (crypter != null) { writer = new EncryptedKeySetWriter(writer, crypter); } else if (_password) { writer = new PbeKeySetWriter(writer, prompt); } if (keySet.Save(writer)) { Console.WriteLine("{0} {1}.", Localized.MsgImportedNewKey, outMsg); ret = 0; } else { ret = -1; } } } } } return(ret); }
public override int Run(string[] remainingArguments) { var ret = 0; Crypter crypter = null; IKeySet ks = new FileSystemKeySet(_location); Func <string> crypterPrompt = CachedPrompt.Password(Util.PromptForPassword).Prompt; var prompt = ks.Metadata.Encrypted ? new Func <string>(CachedPrompt.Password(Util.PromptForPassword).Prompt) : new Func <string>(CachedPrompt.Password(Util.DoublePromptForPassword).Prompt); IDisposable dks = null; if (!String.IsNullOrWhiteSpace(_crypterLocation)) { if (_password) { var cks = KeySet.LayerSecurity( FileSystemKeySet.Creator(_crypterLocation), PbeKeySet.Creator(crypterPrompt) ); crypter = new Crypter(cks); dks = cks; } else { crypter = new Crypter(_crypterLocation); } ks = new EncryptedKeySet(ks, crypter); } else if (_password) { ks = new PbeKeySet(ks, prompt); } var d2ks = ks as IDisposable; using (crypter) using (dks) using (d2ks) using (var keySet = new MutableKeySet(ks)) { if (_status != KeyStatus.Primary && _status != KeyStatus.Active) { Console.WriteLine("{0} {1}.", Localized.MsgInvalidStatus, _status.Identifier); return(-1); } object options = null; if (!String.IsNullOrWhiteSpace(_padding)) { options = new { Padding = _padding }; } int ver; var type = KeyTypeForString(_type); if (ks.Metadata.OriginallyOfficial && ks.Metadata.ValidOfficial()) { var keytype = ks.Metadata.OfficialKeyType(); if (type == null) { type = keytype; } else if (type != keytype && !_force) { throw new ConsoleHelpAsException(String.Format(Localized.MsgMismatchedType, type, keytype)); } } try { ver = keySet.AddKey(_status, _size, type, options); } #pragma warning disable 168 catch (InvalidKeyTypeException ex) #pragma warning restore 168 { throw new ConsoleHelpAsException(String.Format(Localized.MsgMismatchedKind, type?.Kind, keySet.Metadata.Kind)); } IKeySetWriter writer = new FileSystemKeySetWriter(_location, overwrite: true); if (crypter != null) { writer = new EncryptedKeySetWriter(writer, crypter); } else if (_password) { writer = new PbeKeySetWriter(writer, prompt); } using (writer as IDisposable) { try { if (keySet.Save(writer)) { Console.WriteLine("{0} {1}.", Localized.MsgCreatedKey, ver); ret = 0; } else { ret = -1; } } catch { ret = -1; } } } if (ret != 0) { Console.WriteLine("{0} {1}.", Localized.MsgCouldNotWrite, _location); } return(ret); }
public virtual ImportedKeySet Pkcs12Keys(KeyPurpose purpose, Stream input, Func <string> passwordPrompt = null, bool official = false, KeyType hint = null) { using (var password = CachedPrompt.Password(passwordPrompt)) { var keyStore = new Pkcs12Store(input, password.Prompt().ToCharArray()); var keys = new List <Key>(); foreach (string n in keyStore.Aliases) { if (keyStore.IsKeyEntry(n)) { AsymmetricKeyEntry key = keyStore.GetKey(n); if (key.Key.IsPrivate) { switch (key.Key) { case RsaPrivateCrtKeyParameters rsa: keys.Add(KeyFromBouncyCastle(rsa, purpose, official, hint)); break; case DsaPrivateKeyParameters dsa: if (purpose == KeyPurpose.SignAndVerify) { keys.Add(KeyFromBouncyCastle(dsa)); } break; } } } } if (!keys.Any()) { foreach (string n in keyStore.Aliases) { if (keyStore.IsCertificateEntry(n)) { var entry = keyStore.GetCertificate(n); var pubKey = entry.Certificate.GetPublicKey(); switch (pubKey) { case RsaKeyParameters rsa: keys.Add(KeyFromBouncyCastle(rsa, purpose, official, hint)); break; case DsaPublicKeyParameters dsa: if (purpose == KeyPurpose.SignAndVerify) { keys.Add(KeyFromBouncyCastle(dsa)); } break; } } } } if (keys.Any()) { return(new ImportedKeySet(keys, purpose, "imported keys")); } throw new InvalidKeySetException("couldn't find any keys in file"); } }