public static X509Certificate2 GetCertificateWithPrivateKey(X509Certificate bcCertificate, AsymmetricCipherKeyPair keyPair) { Assert.IsType <RsaPrivateCrtKeyParameters>(keyPair.Private); var privateKeyParameters = (RsaPrivateCrtKeyParameters)keyPair.Private; #if IS_DESKTOP RSA privateKey = DotNetUtilities.ToRSA(privateKeyParameters); var certificate = new X509Certificate2(bcCertificate.GetEncoded()); certificate.PrivateKey = privateKey; #else RSAParameters rsaParameters = DotNetUtilities.ToRSAParameters(privateKeyParameters); var privateKey = new RSACryptoServiceProvider(); privateKey.ImportParameters(rsaParameters); X509Certificate2 certificate; using (var certificateTmp = new X509Certificate2(bcCertificate.GetEncoded())) { certificate = RSACertificateExtensions.CopyWithPrivateKey(certificateTmp, privateKey); } #endif return(certificate); }
/// <summary> /// Validates the public key requirements for a certificate /// </summary> /// <param name="certificate">Certificate to validate</param> /// <returns>True if the certificate's public key is valid within NuGet signature requirements</returns> public static bool IsCertificatePublicKeyValid(X509Certificate2 certificate) { // Check if the public key is RSA with a valid keysize var RSAPublicKey = RSACertificateExtensions.GetRSAPublicKey(certificate); if (RSAPublicKey != null) { return(RSAPublicKey.KeySize >= SigningSpecifications.V1.RSAPublicKeyMinLength); } return(false); }
/// <summary> /// Validates the public key requirements for a certificate /// </summary> /// <param name="certificate">Certificate to validate</param> /// <returns>True if the certificate's public key is valid within NuGet signature requirements</returns> public static bool IsCertificatePublicKeyValid(X509Certificate2 certificate) { // Check if the public key is RSA with a valid keysize #if NET45 System.Security.Cryptography.RSA RSAPublicKey = certificate.PublicKey.Key as System.Security.Cryptography.RSA; #else System.Security.Cryptography.RSA RSAPublicKey = RSACertificateExtensions.GetRSAPublicKey(certificate); #endif if (RSAPublicKey != null) { return(RSAPublicKey.KeySize >= SigningSpecifications.V1.RSAPublicKeyMinLength); } return(false); }
private (X509Certificate2 deviceCertificate, X509Certificate2Collection collectionCertificates) LoadCertificateFromPfx(byte[] certificateRaw, string password) { var certificateCollection = new X509Certificate2Collection(); certificateCollection.Import( certificateRaw, password, X509KeyStorageFlags.Exportable | X509KeyStorageFlags.UserKeySet | X509KeyStorageFlags.PersistKeySet); X509Certificate2 certificate = null; var outcollection = new X509Certificate2Collection(); foreach (X509Certificate2 element in certificateCollection) { DebugHelper.LogVerbose($"Found certificate: {element?.Thumbprint} " + $"{element?.Subject}; PrivateKey: {element?.HasPrivateKey}"); if (certificate == null && element.HasPrivateKey) { certificate = element; } else if (certificate == null && !((X509BasicConstraintsExtension)element.Extensions["Basic Constraints"]).CertificateAuthority) { using (RSA key = SimulatedDevice.GetPrivateKey()) { certificate = new X509Certificate2(RSACertificateExtensions.CopyWithPrivateKey(element, key) .Export(X509ContentType.Pkcs12, SecretManager.CertificatePasskey), SecretManager.CertificatePasskey, X509KeyStorageFlags.Exportable | X509KeyStorageFlags.UserKeySet | X509KeyStorageFlags.PersistKeySet); } } else { outcollection.Add(element); } } if (certificate == null) { DebugHelper.LogError($"ERROR: the certificate did not " + $"contain any certificate with a private key."); return(null, null); } else { DebugHelper.LogVerbose($"Using certificate {certificate.Thumbprint} " + $"{certificate.Subject}"); return(certificate, outcollection); } }
private void button_Auth_Click(object sender, EventArgs e) { X509Certificate2 cert = new X509Certificate2("MPS_APK_AUTH.pfx", "Zqmh1234"); RSA key = RSACertificateExtensions.GetRSAPrivateKey(cert); FileStream fs = new FileStream(textBox_APK.Text, FileMode.Open); byte[] hash = HashAlgorithm.Create("SHA1").ComputeHash(fs); fs.Close(); string signData = new ByteArray(hash).ToHexString(); string authExpireString = dateTimePicker_AuthExpire.Checked ? dateTimePicker_AuthExpire.Value.ToString("yyyyMMdd") : "00000000"; signData += authExpireString; byte[] data = new ByteArray(signData, ByteArray.StringEncodingTypeEnum.ASCII).Data; byte[] value = key.SignData(data, HashAlgorithmName.SHA1, RSASignaturePadding.Pkcs1); // Test verify if (!key.VerifyData(data, value, HashAlgorithmName.SHA1, RSASignaturePadding.Pkcs1) || !RSACertificateExtensions.GetRSAPublicKey(cert).VerifyData(data, value, HashAlgorithmName.SHA1, RSASignaturePadding.Pkcs1)) { MessageBox.Show("私钥证书验证签名失败", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } X509Certificate2 cert2 = new X509Certificate2("MPS_APK_AUTH.cer"); if (!RSACertificateExtensions.GetRSAPublicKey(cert2).VerifyData(data, value, HashAlgorithmName.SHA1, RSASignaturePadding.Pkcs1)) { MessageBox.Show("私钥证书验证签名失败", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } //wirte to file string signFileName = textBox_APK.Text + ".sign"; StreamWriter sw = new StreamWriter(signFileName); sw.WriteLine("Expire: " + authExpireString); sw.WriteLine("Signature: " + Convert.ToBase64String(value)); //sw.WriteLine(new ByteArray(value).ToHexString()); sw.Close(); MessageBox.Show($"授权文件-{signFileName}-生成成功", "信息", MessageBoxButtons.OK, MessageBoxIcon.Information); }
private X509Certificate2 OpenCertificateStore(Stream stream) { Pkcs12Store store = new Pkcs12Store(); store.Load(stream, new char[] { }); var keyAlias = store.Aliases.Cast <string>().SingleOrDefault(a => store.IsKeyEntry(a)); var key = (RsaPrivateCrtKeyParameters)store.GetKey(keyAlias).Key; var bouncyCertificate = store.GetCertificate(keyAlias).Certificate; var certificate = new X509Certificate2(DotNetUtilities.ToX509Certificate(bouncyCertificate)); var parameters = DotNetUtilities.ToRSAParameters(key); RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(); rsa.ImportParameters(parameters); certificate = RSACertificateExtensions.CopyWithPrivateKey(certificate, rsa); return(certificate); }
public string GenerateToken(User user) { var tokenHandler = new JwtSecurityTokenHandler(); RsaSecurityKey securityKey = new RsaSecurityKey(RSACertificateExtensions.GetRSAPrivateKey(_certificate)); securityKey.KeyId = _tenantData.KeyID; var signingCredentials = new SigningCredentials(securityKey, SecurityAlgorithms.RsaSha256); var tokenDescriptor = new SecurityTokenDescriptor { Subject = new ClaimsIdentity(new Claim[] { new Claim("sub", user.Subject), new Claim("subType", "user"), new Claim("name", user.DisplayName), new Claim("email", user.Email), new Claim("email_verified", "true", ClaimValueTypes.Boolean) }), Expires = DateTime.UtcNow.AddHours(3), Issuer = _tenantData.Issuer, Audience = "qlik.api/login/jwt-session", SigningCredentials = signingCredentials }; if (user.HasImageURL()) { tokenDescriptor.Subject.AddClaim(new Claim("picture", user.ImageURL)); } for (int i = 0; i < user.Groups.Length; i++) { tokenDescriptor.Subject.AddClaim(new Claim("groups", user.Groups[i])); } var token = tokenHandler.CreateToken(tokenDescriptor); string jwtToken = tokenHandler.WriteToken(token); return(jwtToken); }
static void Main(string[] args) { // openssl req -newkey rsa:2048 -nodes -keyout key.pem -x509 -days 365 -out crt.pem string certificateText = File.ReadAllText("crt.pem"); string privateKeyText = File.ReadAllText("key.pem"); ServicePointManager.Expect100Continue = true; ServicePointManager.SecurityProtocol = (SecurityProtocolType)3072; ServicePointManager.DefaultConnectionLimit = 9999; // Ignore Server Certificate validation ServicePointManager.ServerCertificateValidationCallback += (sender, cert, chain, sslPolicyErrors) => true; HttpWebRequest req = (HttpWebRequest)WebRequest.Create(@"https://server.cryptomix.com/secure/"); req.PreAuthenticate = true; ICertificateProvider provider = new CertificateFromFileProvider(certificateText, privateKeyText, true); #if NETCOREAPP2_0 // https://docs.microsoft.com/en-us/dotnet/api/system.security.cryptography.x509certificates.rsacertificateextensions.copywithprivatekey?redirectedfrom=MSDN&view=netcore-2.0#System_Security_Cryptography_X509Certificates_RSACertificateExtensions_CopyWithPrivateKey_System_Security_Cryptography_X509Certificates_X509Certificate2_System_Security_Cryptography_RSA_ X509Certificate2 certificate = RSACertificateExtensions.CopyWithPrivateKey(provider.Certificate, provider.PrivateKey); #else X509Certificate2 certificate = provider.Certificate; #endif req.ClientCertificates.Add(certificate); HttpWebResponse response = (HttpWebResponse)req.GetResponse(); var encoding = Encoding.ASCII; using (var reader = new StreamReader(response.GetResponseStream(), encoding)) { string responseText = reader.ReadToEnd(); Console.WriteLine(responseText); } }