private (string keyPairId, SigningCredentials signingCredentials) GetSigningCredentials(SigType sigType) { switch (sigType) { case SigType.Asymmetric: { if (_privateKeyStore == null) { return(null, null); } var(keyPairId, key) = _privateKeyStore.GetLatestKey(); // latest key, ordered by CreationTimeUtc var rsaParameters = new OpenSSLPrivateKeyDecoder().DecodeParameters(key); var securityKey = new RsaSecurityKey(rsaParameters); //return (keyPairId, new SigningCredentials(securityKey, SecurityAlgorithms.RsaSha256Signature)); return(keyPairId, new SigningCredentials(securityKey, "RS256")); // to make it compatible with non-microsoft clients } case SigType.Symmetric: default: { if (_symmetricKeyStore == null) { return(null, null); } var secret = _symmetricKeyStore.GetKey(); return(null, new SigningCredentials(new SymmetricSecurityKey(Encoding.ASCII.GetBytes(secret)), SecurityAlgorithms.HmacSha256Signature)); } } }
public void KeyToXML([Argument] string path, [Option("private")] bool privateKey, [Option("public")] bool publicKey) { if (!privateKey && !publicKey) { privateKey = true; publicKey = true; } string privateKeyText = File.ReadAllText(path); IOpenSSLPrivateKeyDecoder decoder = new OpenSSLPrivateKeyDecoder(); RSAParameters parameters = decoder.DecodeParameters(privateKeyText); using (var rsa = RSA.Create(parameters)) { var dir = Path.GetDirectoryName(path); var name = Path.GetFileNameWithoutExtension(path); if (privateKey) { File.WriteAllText(Path.Combine(dir, name + "_private.xml"), rsa.ToXmlString(true)); } if (publicKey) { File.WriteAllText(Path.Combine(dir, name + "_public.xml"), rsa.ToXmlString(false)); } } }
/// <summary> /// CertificateFromFileProvider /// </summary> /// <param name="certificateText">The certificate or public key text.</param> /// <param name="privateKeyText">The private (rsa) key text.</param> /// <param name="securePassword">The optional securePassword to decrypt the private key.</param> public CertificateFromFileProvider([NotNull] string certificateText, [NotNull] string privateKeyText, [CanBeNull] SecureString securePassword = null) { if (certificateText == null) { throw new ArgumentNullException(nameof(certificateText)); } if (privateKeyText == null) { throw new ArgumentNullException(nameof(privateKeyText)); } Certificate = new X509Certificate2(GetPublicKeyBytes(certificateText)); #if NETSTANDARD PublicKey = Certificate.GetRSAPublicKey(); #else PublicKey = (RSACryptoServiceProvider)Certificate.PublicKey.Key; #endif IOpenSSLPrivateKeyDecoder decoder = new OpenSSLPrivateKeyDecoder(); PrivateKey = decoder.Decode(privateKeyText, securePassword); #if !NETSTANDARD Certificate.PrivateKey = PrivateKey; #endif }
private JwtSecurityToken CreateJwsToken(ClientAssertion clientAssertion, string privateKeyText) { _logger.LogInformation("Create JwsToken for {assertion}", clientAssertion); var decoder = new OpenSSLPrivateKeyDecoder(); var rsaParams = decoder.DecodeParameters(privateKeyText, null); var rsa = RSA.Create(); rsa.ImportParameters(rsaParams); var authorityAudience = $"{_configuration["OAuth2:AuthServerUrl"].TrimEnd('/')}/connect/token"; var token = new JwtSecurityToken( clientAssertion.Issuer, clientAssertion.AuthorityAudience ?? authorityAudience, new List <Claim> { new Claim("iss", clientAssertion.Issuer), new Claim("sub", clientAssertion.Subject), new Claim("aud", clientAssertion.Audience), new Claim("jti", clientAssertion.JwtId), new Claim("iat", ConvertDateTimeToTimestamp(clientAssertion.IssuedAt)), new Claim("exp", ConvertDateTimeToTimestamp(clientAssertion.Expiration)) }, DateTime.UtcNow, DateTime.UtcNow.AddSeconds(30), new SigningCredentials(new RsaSecurityKey(rsa), SecurityAlgorithms.RsaSha256)); return(token); }
public BillingCryptoService(byte[] privateKey) { var keyString = Encoding.ASCII.GetString(privateKey); var decoder = new OpenSSLPrivateKeyDecoder(); _provider = decoder.Decode(keyString); }
public static string CreateToken(object payload, string privateKey) { IOpenSSLPrivateKeyDecoder decoder = new OpenSSLPrivateKeyDecoder(); using (RSACryptoServiceProvider cryptoServiceProvider = decoder.Decode(privateKey)) { return(Jose.JWT.Encode(payload, cryptoServiceProvider, Jose.JwsAlgorithm.RS256)); } }
/// <summary> /// Creates an RSACryptoServiceProvider with the custom private key specified by privateKeyFilePath parameter. /// To generate RSA private.key and public.crt key-pair files, use OpenSSL command: /// openssl req -x509 -sha256 -nodes -days 365 -newkey rsa:2048 -keyout private.key -out certificate_pub.crt /// Source: https://github.com/StefH/OpenSSL-X509Certificate2-Provider /// Nuget package necessary: https://www.nuget.org/packages/OpenSSL.X509Certificate2.Provider /// </summary> /// <param name="privateKeyFilePath">Path to the .key file containing the RSA private key.</param> /// <returns></returns> public static RSACryptoServiceProvider CreateRSACryptoServiceProvider(string privateKeyFilePath) { string privateKeyText = File.ReadAllText(privateKeyFilePath); IOpenSSLPrivateKeyDecoder decoder = new OpenSSLPrivateKeyDecoder(); RSACryptoServiceProvider rsaProvider = decoder.Decode(privateKeyText); return(rsaProvider); }
public static RSA ConvertToRsa(this string privateKey) { var decoder = new OpenSSLPrivateKeyDecoder(); var rsaParams = decoder.DecodeParameters(privateKey, null); var rsa = RSA.Create(); rsa.ImportParameters(rsaParams); return(rsa); }
public void KeyGenerate([Argument] string path = ".", [Option("size")] int keySize = 4096) { string privateKeyText = File.ReadAllText("../../cert/private.key"); IOpenSSLPrivateKeyDecoder decoder = new OpenSSLPrivateKeyDecoder(); RSAParameters parameters = decoder.DecodeParameters(privateKeyText); using (var rsa = RSA.Create(parameters)) { File.WriteAllText(Path.Combine(path, "private.key"), ExportPrivateKey(rsa)); File.WriteAllText(Path.Combine(path, "private.xml"), rsa.ToXmlString(true)); File.WriteAllText(Path.Combine(path, "public.xml"), rsa.ToXmlString(false)); } }
public static string Sign(this string data, string privateKey) { var decoder = new OpenSSLPrivateKeyDecoder(); var rsaParams = decoder.DecodeParameters(privateKey, null); var rsa = RSA.Create(); rsa.ImportParameters(rsaParams); var signature = rsa.SignData(Encoding.UTF8.GetBytes(data), HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1); return(Base64UrlEncode(signature)); }
public static void TestPrivateRsaKey() { Console.WriteLine("TestPrivateRsaKey"); string privateKeyText = File.ReadAllText("private_rsa.key"); IOpenSSLPrivateKeyDecoder decoder = new OpenSSLPrivateKeyDecoder(); RSACryptoServiceProvider cryptoServiceProvider = decoder.Decode(privateKeyText); // Sign the data byte[] hello = new UTF8Encoding().GetBytes("Hello World RSA"); byte[] hashValue = cryptoServiceProvider.SignData(hello, CryptoConfig.MapNameToOID("SHA256")); ShowBytes("hashValue", hashValue); }
/// <summary> /// Sign data /// </summary> /// <param name="sign"></param> /// <returns></returns> protected byte[] Sign(string sign = null) { if (sign == null) { sign = GetHash(); } byte[] indata = Encoding.UTF8.GetBytes(sign); IOpenSSLPrivateKeyDecoder decoder = new OpenSSLPrivateKeyDecoder(); RSAParameters parameters = decoder.DecodeParameters(PrivateKeyPem); RSACryptoServiceProvider RSAalg = new RSACryptoServiceProvider(); RSAalg.ImportParameters(parameters); var data = RSAalg.SignData(indata, HashAlgorithmName.SHA1, RSASignaturePadding.Pkcs1); return(data); }
private static X509Certificate2 CreateX509FromVaultCertificate(CertificateCredentials data) { var publicKeyBytes = Encoding.UTF8.GetBytes(data.CertificateContent); var publicKey = new X509Certificate2(publicKeyBytes, string.Empty, X509KeyStorageFlags.EphemeralKeySet); // https://github.com/StefH/OpenSSL-X509Certificate2-Provider var decoder = new OpenSSLPrivateKeyDecoder(); var privateKey = decoder.Decode(data.PrivateKeyContent); var privateKeyParameters = decoder.DecodeParameters(data.PrivateKeyContent); // Combine the public key & private key using the CopyWithPrivateKey extension method // https://docs.microsoft.com/en-us/dotnet/api/system.security.cryptography.x509certificates.rsacertificateextensions.copywithprivatekey?view=netcore-2.2 using (var certwithkey = publicKey.CopyWithPrivateKey(privateKey)) { return(new X509Certificate2(certwithkey.Export(X509ContentType.Pkcs12))); } }
/// <summary> /// Initializes a new instance of the <see cref="CertificateFromFileProvider"/> class. /// </summary> /// <param name="certificateText">The certificate or public key text.</param> /// <param name="privateKeyText">The private (rsa) key text.</param> /// <param name="useKeyContainer">Store the private key in a key container. <see href="https://docs.microsoft.com/en-us/dotnet/standard/security/how-to-store-asymmetric-keys-in-a-key-container" /></param> /// <param name="securePassword">The optional securePassword to decrypt the private key.</param> /// <exception cref="ArgumentNullException">certificateText or privateKeyText</exception> public CertificateFromFileProvider([NotNull] string certificateText, [NotNull] string privateKeyText, bool useKeyContainer = false, [CanBeNull] SecureString securePassword = null) { if (certificateText == null) { throw new ArgumentNullException(nameof(certificateText)); } if (privateKeyText == null) { throw new ArgumentNullException(nameof(privateKeyText)); } Certificate = new X509Certificate2(GetPublicKeyBytes(certificateText)); #if NETSTANDARD PublicKey = Certificate.GetRSAPublicKey(); #else PublicKey = (RSACryptoServiceProvider)Certificate.PublicKey.Key; #endif IOpenSSLPrivateKeyDecoder decoder = new OpenSSLPrivateKeyDecoder(); var privateKey = decoder.Decode(privateKeyText, securePassword); if (useKeyContainer) { var cspParameters = new CspParameters { KeyContainerName = $"{{{Guid.NewGuid()}}}" }; var cspPrivateKey = new RSACryptoServiceProvider(cspParameters); cspPrivateKey.ImportParameters(privateKey.ExportParameters(true)); PrivateKey = cspPrivateKey; } else { PrivateKey = privateKey; } #if !NETSTANDARD Certificate.PrivateKey = PrivateKey; #endif }
public static void TestPublicKey() { Console.WriteLine("TestPublicKey"); //load the public key for testing. string publicKeyText = File.ReadAllText("public.key"); IOpenSSLPublicKeyDecoder publicKeyDecoder = new OpenSSLPublicKeyDecoder(); RSACryptoServiceProvider publicKeyCsp = publicKeyDecoder.Decode(publicKeyText); var publicParameters = publicKeyCsp.ExportParameters(false); //load the corresponding private key that matches the public key //to verify that the parameters match string privateKeyText = File.ReadAllText("private.key"); IOpenSSLPrivateKeyDecoder privateKeyDecoder = new OpenSSLPrivateKeyDecoder(); RSACryptoServiceProvider privateKeyCsp = privateKeyDecoder.Decode(privateKeyText); var privateParameters = privateKeyCsp.ExportParameters(false); if (!publicParameters.Modulus.SequenceEqual(privateParameters.Modulus) || !publicParameters.Exponent.SequenceEqual(privateParameters.Exponent)) { throw new Exception("public.key does not match private.key"); } }