public ResAcc <string> GenerarSelloDigital(string sArchivoKey, string sContrasenia, string sCadenaOriginal) { var Res = new ResAcc <string>(true); try { byte[] encryptedPrivateKeyInfoData = File.ReadAllBytes(sArchivoKey); AsymmetricKeyParameter parameter = PrivateKeyFactory.DecryptKey(sContrasenia.ToCharArray(), encryptedPrivateKeyInfoData); MemoryStream stream = new MemoryStream(); new StreamWriter(stream); StringWriter writer = new StringWriter(); new PemWriter(writer).WriteObject(parameter); writer.Close(); ISigner signer = SignerUtilities.GetSigner("SHA1WithRSA"); byte[] bytes = Encoding.UTF8.GetBytes(sCadenaOriginal); signer.Init(true, parameter); signer.BlockUpdate(bytes, 0, bytes.Length); Res.Respuesta = Convert.ToBase64String(signer.GenerateSignature()).ToString(); } catch (Exception e) { Res.Exito = false; Res.Mensaje = "Error al generar el sello digital\n\n"; Res.Mensaje += (e.InnerException == null ? e.Message : e.InnerException.Message); } return(Res); }
/// <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")); } }
/// <summary> /// Genera el archivo pfx y devuelve el resultado con su contraseña /// </summary> /// <param name="rutaArchivoCer"></param> /// <param name="rutaArchivoKey"></param> /// <param name="secretArchivoKey"></param> /// <param name="rutaGuardado"></param> /// <param name="nombreArchivoPfx"></param> /// <param name="secretArchivoPfx"></param> /// <param name="conservarArchivo"></param> /// <returns>Pfx</returns> public static CfdiPfx generarArchivoPfx(string rutaArchivoCer, string rutaArchivoKey, string secretArchivoKey, string rutaGuardado, string nombreArchivoPfx, string secretArchivoPfx, Boolean conservarArchivo) { try { string rutaArchivoPfx = Path.Combine(rutaGuardado, nombreArchivoPfx); if (!Directory.Exists(rutaGuardado)) { Directory.CreateDirectory(rutaGuardado); } if (File.Exists(rutaArchivoPfx)) { File.Delete(rutaArchivoPfx); } X509Certificate2 certificado = new X509Certificate2(rutaArchivoCer); Org.BouncyCastle.X509.X509Certificate certificate = DotNetUtilities.FromX509Certificate(certificado); byte[] bytesArchivoKey = File.ReadAllBytes(rutaArchivoKey); AsymmetricKeyParameter privateKey = PrivateKeyFactory.DecryptKey(secretArchivoKey.ToCharArray(), bytesArchivoKey); var certEntry = new X509CertificateEntry(certificate); string friendlyName = certificate.SubjectDN.ToString(); PrivateKeyInfo keyInfo = PrivateKeyInfoFactory.CreatePrivateKeyInfo(privateKey); byte[] keyBytes = keyInfo.ToAsn1Object().GetEncoded(); var builder = new Pkcs12StoreBuilder(); builder.SetUseDerEncoding(true); var store = builder.Build(); store.SetKeyEntry("PrivateKeyAlias", new AsymmetricKeyEntry(privateKey), new X509CertificateEntry[] { certEntry }); byte[] pfxBytes = null; using (MemoryStream stream = new MemoryStream()) { store.Save(stream, secretArchivoPfx.ToCharArray(), new SecureRandom()); pfxBytes = stream.ToArray(); // Este sirve para la cancelacion } var result = Pkcs12Utilities.ConvertToDefiniteLength(pfxBytes); if (conservarArchivo) { File.WriteAllBytes(rutaArchivoPfx, result); } return(new CfdiPfx(result, secretArchivoPfx)); } catch (Exception ex) { throw ex; } }
public static bool PrivateKeyTest(byte[] data, byte[] password) { try { var key = PrivateKeyFactory.DecryptKey(UTF8Encoding.UTF8.GetString(password).ToCharArray(), data); return(key.IsPrivate); } catch { } return(false); }
public string ExportarLlavePem(string pathLlave, string passwordLlave) { byte[] llaveBytes = File.ReadAllBytes(pathLlave); AsymmetricKeyParameter asp = PrivateKeyFactory.DecryptKey(passwordLlave.ToCharArray(), llaveBytes); StringWriter stWriter = new StringWriter(); PemWriter pmw = new PemWriter(stWriter); pmw.WriteObject(asp); stWriter.Close(); return(stWriter.ToString()); }
public string DecodePrivateKey(string filename, string passw) { byte[] dataKey = System.IO.File.ReadAllBytes(filename); AsymmetricKeyParameter asp = PrivateKeyFactory.DecryptKey(passw.ToCharArray(), dataKey); System.IO.MemoryStream ms = new System.IO.MemoryStream(); System.IO.TextWriter writer = new System.IO.StreamWriter(ms); System.IO.StringWriter stWrite = new System.IO.StringWriter(); PemWriter pmw = new PemWriter(stWrite); pmw.WriteObject(asp); stWrite.Close(); return(stWrite.ToString()); }
private void doOpensslTestKeys() { string[] names = GetTestDataEntries("keys"); foreach (string name in names) { // Console.Write(name + " => "); Stream data = GetTestDataAsStream(name); AsymmetricKeyParameter key = PrivateKeyFactory.DecryptKey("12345678a".ToCharArray(), data); // Console.WriteLine(key.GetType().Name); if (!(key is RsaPrivateCrtKeyParameters)) { Fail("Sample key could not be decrypted: " + name); } } }
/// <summary> /// Initialize the crypto objects to sign the original string of the invoice /// </summary> public void InitializePrivateKey() { try { asymmetricKeyParameter = PrivateKeyFactory.DecryptKey(Password.ToCharArray(), PrivateKeyBytes); rsaKeyParameters = (RsaKeyParameters)asymmetricKeyParameter; signer = SignerUtilities.GetSigner(Constants.ALGORITHM_MX); signer.Init(true, rsaKeyParameters); keyInitialized = true; } catch (Exception exception) { Console.WriteLine(exception.Message); } }
public static string SHA1WithRSA(string message, byte[] data, byte[] password) { ISigner signer; byte[] signature; AsymmetricKeyParameter key; key = PrivateKeyFactory.DecryptKey(Encoding.UTF8.GetString(password).ToCharArray(), data); signer = SignerUtilities.GetSigner("SHA1WithRSA"); signer.Init(true, key); data = Encoding.UTF8.GetBytes(message); signer.BlockUpdate(data, 0, data.Length); signature = signer.GenerateSignature(); return(Convert.ToBase64String(signature)); }
public void ReadPrivate() { try { System.IO.StringWriter stWrite = new System.IO.StringWriter(); PrivateKeyParameter = PrivateKeyFactory.DecryptKey(Password.ToCharArray(), KeyBytes); MemoryStream ms = new MemoryStream(); TextWriter writer = new StreamWriter(ms); Org.BouncyCastle.OpenSsl.PemWriter pmw = new Org.BouncyCastle.OpenSsl.PemWriter(stWrite); pmw.WriteObject(PrivateKeyParameter); stWrite.Close(); PrivateKeyRSA = stWrite.ToString(); } catch (Exception exe) { throw new Exception(Resource.ErrorPassword); } }
public IAsymmetricKey DecryptPrivateKey(IAsymmetricKey key, string password) { AsymmetricKeyParameter asymmetricKey; try { asymmetricKey = PrivateKeyFactory.DecryptKey(password.ToCharArray(), key.Content); } catch (InvalidCipherTextException) { throw new ArgumentException("Incorrect password was provided or the key is corrupt."); } var privateKeyInfo = PrivateKeyInfoFactory.CreatePrivateKeyInfo(asymmetricKey); byte[] privateKey = privateKeyInfo .ToAsn1Object() .GetDerEncoded(); return(keyProvider.GetPrivateKey(privateKey)); }
public static RSACryptoServiceProvider DecodePrivateKey(byte[] archivo, string pass, string format) { try { if (format == ".pem") { var datos = Encoding.ASCII.GetString(archivo); datos = datos.Replace("-----BEGIN ENCRYPTED PRIVATE KEY-----", ""); datos = datos.Replace("-----END ENCRYPTED PRIVATE KEY-----", ""); archivo = Convert.FromBase64String(datos); } var key = PrivateKeyFactory.DecryptKey(pass.ToCharArray(), archivo); RsaPrivateCrtKeyParameters pars = (RsaPrivateCrtKeyParameters)key; RSAParameters parms = DotNetUtils.ToRSAParameters(pars); RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(); rsa.ImportParameters(parms); return(rsa); } catch (Exception ex) { return(null); } }
/// <summary> /// Convierte un archivo .key a su representativo en .pem pkcs8 (Deprecated) /// </summary> /// <param name="rutaArchivoKey"></param> /// <param name="secretArchivoKey"></param> /// <param name="rutaGuardado"></param> /// <param name="nombreArchivoPem"></param> /// <returns>Boolean</returns> public static Boolean convertirKeyAPem(string rutaArchivoKey, string secretArchivoKey, string rutaGuardado, string nombreArchivoPem) { try { string rutaArchivoPem = Path.Combine(rutaGuardado, nombreArchivoPem); if (!Directory.Exists(rutaGuardado)) { Directory.CreateDirectory(rutaGuardado); } if (File.Exists(rutaArchivoPem)) { File.Delete(rutaArchivoPem); } byte[] bytesArchivoKey = File.ReadAllBytes(rutaArchivoKey); AsymmetricKeyParameter asp = PrivateKeyFactory.DecryptKey(secretArchivoKey.ToCharArray(), bytesArchivoKey); MemoryStream ms = new MemoryStream(); TextWriter writer = new StreamWriter(ms); StringWriter stWrite = new StringWriter(); PemWriter pmw = new PemWriter(stWrite); pmw.WriteObject(asp); stWrite.Close(); File.WriteAllText(rutaArchivoPem, stWrite.ToString()); return(true); } catch (Exception ex) { throw ex; } }
private object ReadPrivateKey(PemObject pemObject) { string text = pemObject.Type.Substring(0, pemObject.Type.Length - "PRIVATE KEY".Length).Trim(); byte[] array = pemObject.Content; IDictionary dictionary = Platform.CreateHashtable(); foreach (PemHeader pemHeader in pemObject.Headers) { dictionary[pemHeader.Name] = pemHeader.Value; } string a = (string)dictionary["Proc-Type"]; if (a == "4,ENCRYPTED") { if (this.pFinder == null) { throw new PasswordException("No password finder specified, but a password is required"); } char[] password = this.pFinder.GetPassword(); if (password == null) { throw new PasswordException("Password is null, but a password is required"); } string text2 = (string)dictionary["DEK-Info"]; string[] array2 = text2.Split(new char[] { ',' }); string dekAlgName = array2[0].Trim(); byte[] iv = Hex.Decode(array2[1].Trim()); array = PemUtilities.Crypt(false, array, password, dekAlgName, iv); } object result; try { Asn1Sequence instance = Asn1Sequence.GetInstance(array); string a2; if ((a2 = text) != null) { AsymmetricKeyParameter asymmetricKeyParameter; AsymmetricKeyParameter publicParameter; if (!(a2 == "RSA")) { if (!(a2 == "DSA")) { if (!(a2 == "EC")) { if (!(a2 == "ENCRYPTED")) { if (!(a2 == "")) { goto IL_356; } result = PrivateKeyFactory.CreateKey(PrivateKeyInfo.GetInstance(instance)); return(result); } else { char[] password2 = this.pFinder.GetPassword(); if (password2 == null) { throw new PasswordException("Password is null, but a password is required"); } result = PrivateKeyFactory.DecryptKey(password2, EncryptedPrivateKeyInfo.GetInstance(instance)); return(result); } } else { ECPrivateKeyStructure eCPrivateKeyStructure = new ECPrivateKeyStructure(instance); AlgorithmIdentifier algID = new AlgorithmIdentifier(X9ObjectIdentifiers.IdECPublicKey, eCPrivateKeyStructure.GetParameters()); PrivateKeyInfo keyInfo = new PrivateKeyInfo(algID, eCPrivateKeyStructure.ToAsn1Object()); asymmetricKeyParameter = PrivateKeyFactory.CreateKey(keyInfo); DerBitString publicKey = eCPrivateKeyStructure.GetPublicKey(); if (publicKey != null) { SubjectPublicKeyInfo keyInfo2 = new SubjectPublicKeyInfo(algID, publicKey.GetBytes()); publicParameter = PublicKeyFactory.CreateKey(keyInfo2); } else { publicParameter = ECKeyPairGenerator.GetCorrespondingPublicKey((ECPrivateKeyParameters)asymmetricKeyParameter); } } } else { if (instance.Count != 6) { throw new PemException("malformed sequence in DSA private key"); } DerInteger derInteger = (DerInteger)instance[1]; DerInteger derInteger2 = (DerInteger)instance[2]; DerInteger derInteger3 = (DerInteger)instance[3]; DerInteger derInteger4 = (DerInteger)instance[4]; DerInteger derInteger5 = (DerInteger)instance[5]; DsaParameters parameters = new DsaParameters(derInteger.Value, derInteger2.Value, derInteger3.Value); asymmetricKeyParameter = new DsaPrivateKeyParameters(derInteger5.Value, parameters); publicParameter = new DsaPublicKeyParameters(derInteger4.Value, parameters); } } else { if (instance.Count != 9) { throw new PemException("malformed sequence in RSA private key"); } RsaPrivateKeyStructure instance2 = RsaPrivateKeyStructure.GetInstance(instance); publicParameter = new RsaKeyParameters(false, instance2.Modulus, instance2.PublicExponent); asymmetricKeyParameter = new RsaPrivateCrtKeyParameters(instance2.Modulus, instance2.PublicExponent, instance2.PrivateExponent, instance2.Prime1, instance2.Prime2, instance2.Exponent1, instance2.Exponent2, instance2.Coefficient); } result = new AsymmetricCipherKeyPair(publicParameter, asymmetricKeyParameter); return(result); } IL_356: throw new ArgumentException("Unknown key type: " + text, "type"); } catch (IOException ex) { throw ex; } catch (Exception ex2) { throw new PemException("problem creating " + text + " private key: " + ex2.ToString()); } return(result); }
/** * Read a Key Pair */ private object ReadPrivateKey(PemObject pemObject) { // // extract the key // Debug.Assert(pemObject.Type.EndsWith("PRIVATE KEY")); string type = pemObject.Type.Substring(0, pemObject.Type.Length - "PRIVATE KEY".Length).Trim(); byte[] keyBytes = pemObject.Content; IDictionary fields = Platform.CreateHashtable(); foreach (PemHeader header in pemObject.Headers) { fields[header.Name] = header.Value; } string procType = (string)fields["Proc-Type"]; if (procType == "4,ENCRYPTED") { if (pFinder == null) { throw new PasswordException("No password finder specified, but a password is required"); } char[] password = pFinder.GetPassword(); if (password == null) { throw new PasswordException("Password is null, but a password is required"); } string dekInfo = (string)fields["DEK-Info"]; string[] tknz = dekInfo.Split(','); string dekAlgName = tknz[0].Trim(); byte[] iv = Hex.Decode(tknz[1].Trim()); keyBytes = PemUtilities.Crypt(false, keyBytes, password, dekAlgName, iv); } try { AsymmetricKeyParameter pubSpec, privSpec; Asn1Sequence seq = (Asn1Sequence)Asn1Object.FromByteArray(keyBytes); switch (type) { case "RSA": { if (seq.Count != 9) { throw new PemException("malformed sequence in RSA private key"); } RsaPrivateKeyStructure rsa = new RsaPrivateKeyStructure(seq); pubSpec = new RsaKeyParameters(false, rsa.Modulus, rsa.PublicExponent); privSpec = new RsaPrivateCrtKeyParameters( rsa.Modulus, rsa.PublicExponent, rsa.PrivateExponent, rsa.Prime1, rsa.Prime2, rsa.Exponent1, rsa.Exponent2, rsa.Coefficient); break; } case "DSA": { if (seq.Count != 6) { throw new PemException("malformed sequence in DSA private key"); } // TODO Create an ASN1 object somewhere for this? //DerInteger v = (DerInteger)seq[0]; DerInteger p = (DerInteger)seq[1]; DerInteger q = (DerInteger)seq[2]; DerInteger g = (DerInteger)seq[3]; DerInteger y = (DerInteger)seq[4]; DerInteger x = (DerInteger)seq[5]; DsaParameters parameters = new DsaParameters(p.Value, q.Value, g.Value); privSpec = new DsaPrivateKeyParameters(x.Value, parameters); pubSpec = new DsaPublicKeyParameters(y.Value, parameters); break; } case "EC": { ECPrivateKeyStructure pKey = new ECPrivateKeyStructure(seq); AlgorithmIdentifier algId = new AlgorithmIdentifier( X9ObjectIdentifiers.IdECPublicKey, pKey.GetParameters()); PrivateKeyInfo privInfo = new PrivateKeyInfo(algId, pKey.ToAsn1Object()); // TODO Are the keys returned here ECDSA, as Java version forces? privSpec = PrivateKeyFactory.CreateKey(privInfo); DerBitString pubKey = pKey.GetPublicKey(); if (pubKey != null) { SubjectPublicKeyInfo pubInfo = new SubjectPublicKeyInfo(algId, pubKey.GetBytes()); // TODO Are the keys returned here ECDSA, as Java version forces? pubSpec = PublicKeyFactory.CreateKey(pubInfo); } else { pubSpec = ECKeyPairGenerator.GetCorrespondingPublicKey( (ECPrivateKeyParameters)privSpec); } break; } case "ENCRYPTED": { char[] password = pFinder.GetPassword(); if (password == null) { throw new PasswordException("Password is null, but a password is required"); } return(PrivateKeyFactory.DecryptKey(password, EncryptedPrivateKeyInfo.GetInstance(seq))); } case "": { return(PrivateKeyFactory.CreateKey(PrivateKeyInfo.GetInstance(seq))); } default: throw new ArgumentException("Unknown key type: " + type, "type"); } return(new AsymmetricCipherKeyPair(pubSpec, privSpec)); } catch (IOException e) { throw e; } catch (Exception e) { throw new PemException( "problem creating " + type + " private key: " + e.ToString()); } }
public bool validateCerKEYContent(byte[] cer, byte[] key, string password, string rfc) { try { if (String.IsNullOrEmpty(password)) { throw new DigitalSignException(5050, "5051", "Es necesario especificar la contraseña del certificado.", null); } SecureString secureString = new SecureString(); secureString.Clear(); foreach (char c in password) { secureString.AppendChar(c); } RSACryptoServiceProvider lrsa = OpensslKey.DecodeEncryptedPrivateKeyInfo(key, secureString); if (lrsa == null) { throw new DigitalSignException(5052, "5052", "La constraseña de los certificados proporcionada no es correcta.", null); } //validate Subject X509Certificate2 x509Certificate2 = new X509Certificate2(cer); if (!x509Certificate2.Subject.ToLower().Contains(rfc.ToLower())) { throw new DigitalSignException(5053, "5053", "El certificado no corresponde con el RFC proporcionado.", null); } //matches cer and key char[] arrayOfChars = password.ToCharArray(); AsymmetricKeyParameter privateKey = PrivateKeyFactory.DecryptKey(arrayOfChars, key); Org.BouncyCastle.X509.X509Certificate bouncyCastleCert = new Org.BouncyCastle.X509.X509Certificate( new X509CertificateParser().ReadCertificate(x509Certificate2.GetRawCertData()).CertificateStructure); RsaKeyParameters publicKey = (RsaKeyParameters)bouncyCastleCert.GetPublicKey(); byte[] numArray = new byte[256]; new SecureRandom().NextBytes(numArray); var signer = new Signer(); byte[] signature = signer.Sign(privateKey, numArray); var isMatched = signer.VerifySignature(publicKey, numArray, signature); if (!isMatched) { throw new DigitalSignException(5054, "5054", "El .CER no corresponde con el .KEY proporcionado.", null); } //validación de CSD / FIEL if (! (KeyUsageHasUsage(x509Certificate2, X509KeyUsageFlags.DigitalSignature) && KeyUsageHasUsage(x509Certificate2, X509KeyUsageFlags.NonRepudiation) && !KeyUsageHasUsage(x509Certificate2, X509KeyUsageFlags.DataEncipherment) && !KeyUsageHasUsage(x509Certificate2, X509KeyUsageFlags.KeyAgreement) )) { throw new DigitalSignException(5055, "5055", "El certificado proporcionado debe de ser un CSD válido (No debe de ser FIEL).", null); } return(true); } catch (DigitalSignException) { throw; } catch (Exception ex) { throw new DigitalSignException(109, "109", "El certificado proporcionado no es correcto.", ex); } }
/// <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")); } }
/// <summary> /// Decrypts the provided private key. /// </summary> /// <param name="privateKey">The encrypted private key.</param> /// <param name="passPhrase">The pass phrase to decrypt the private key.</param> /// <returns>The private key.</returns> public static AsymmetricKeyParameter FromEncryptedPrivateKeyString(string privateKey, string passPhrase) { return(PrivateKeyFactory.DecryptKey(passPhrase.ToCharArray(), Convert.FromBase64String(privateKey))); }