IdentityServer3 Invalid provider type specified when using Self-Signed Certificate - identityserver3

I'm trying to secure asp.net web api using IdentityServer3 library.
I created a self-signed certificate for signing the security tokes as following:
Then I got the following exception when I call my Authorization Server
http://localhost:53180/connect/token
"InnerException": {
"Message": "An error has occurred.",
"ExceptionMessage": "Invalid provider type specified.\r\n",
"ExceptionType": "System.Security.Cryptography.CryptographicException",
"StackTrace": " at System.Security.Cryptography.Utils.CreateProvHandle(CspParameters parameters, Boolean randomKeyContainer)\r\n at System.Security.Cryptography.Utils.GetKeyPairHelper(CspAlgorithmType keyType, CspParameters parameters, Boolean randomKeyContainer, Int32 dwKeySize, SafeProvHandle& safeProvHandle, SafeKeyHandle& safeKeyHandle)\r\n at System.Security.Cryptography.RSACryptoServiceProvider.GetKeyPair()\r\n at System.Security.Cryptography.RSACryptoServiceProvider..ctor(Int32 dwKeySize, CspParameters parameters, Boolean useDefaultKeySize)\r\n at System.Security.Cryptography.X509Certificates.X509Certificate2.get_PrivateKey()\r\n at System.IdentityModel.Tokens.X509AsymmetricSecurityKey.get_PrivateKey()\r\n at System.IdentityModel.Tokens.X509AsymmetricSecurityKey.GetSignatureFormatter(String algorithm)\r\n at System.IdentityModel.Tokens.AsymmetricSignatureProvider..ctor(AsymmetricSecurityKey key, String algorithm, Boolean willCreateSignatures) in c:\\workspace\\WilsonForDotNet45Release\\src\\System.IdentityModel.Tokens.Jwt\\AsymmetricSignatureProvider.cs:line 147"
It seems there is a problem with certificate private key:
Please help!

See: https://github.com/IdentityServer/IdentityServer3/issues/2859
You need a certificate with a private key managed by a legacy CSP, not CNG.
If you're running on Windows Server 2016 or Windows 10, the New-SelfSignedCertificate commandlet has been extended substantially and now includes all the options you need. The following command will generate a certificate suitable for token signing, with the private key managed by a legacy CSP:
New-SelfSignedCertificate -CertStoreLocation cert:\localmachine\my `
-FriendlyName "Token Signing" -TextExtension #("2.5.29.37={text}1.3.6.1.5.5.7.3.3") `
-KeyUsage DigitalSignature -KeyAlgorithm RSA -KeyLength 2048 -KeySpec Signature `
-DnsName ([System.Net.Dns]::GetHostByName($env:computerName).HostName)
The key part is the -KeySpec Signature which forces the use of a legacy CSP for the private key.

Related

How to create a self-signed certificate using PRINTABLE_STRING, IA5STRING or BMPSTRING as certificate fields?

I need to know how I can make sure certificate fields of my self-signed certificate, like subject common name and issuer common name, is encoded as PRINTABLE_STRING, IA5STRING or BMPSTRING, but not UTF-8 encoding.
I'm trying to create it using PowerShell cmdlet.
I'm trying to create a self-signed certificate that conforms to these rules.
These are the parameters I found that I think comply with those rules.
New-SelfSignedCertificate -DnsName 'wdac' -CertStoreLocation Cert:\CurrentUser\My\ -Type Codesigning -HashAlgorithm "SHA512" -KeyLength 4096 -KeyAlgorithm RSA

How can I generate self-signed certificate with these standards?

Without using Windows Server or purchasing a certificate, how can I generate a self-signed certificate that meets these criteria?
All policies, including base and supplemental, must be signed
according to the PKCS 7 Standard.
Use RSA SHA-256 only. ECDSA isn't supported.
Don't use UTF-8 encoding for certificate fields, like 'subject common
name' and 'issuer common name'. These strings must be encoded as
PRINTABLE_STRING, IA5STRING or BMPSTRING.
Keys must be less than or equal to 4K key size
Certificate criteria screenshot
https://learn.microsoft.com/en-us/windows/security/threat-protection/windows-defender-application-control/use-signed-policies-to-protect-windows-defender-application-control-against-tampering
This is how far I got with Powershell:
New-SelfSignedCertificate -DnsName "WDACPolicy" -CertStoreLocation Cert:\CurrentUser\My\ -Type Codesigning -KeyLength 2048 -KeyAlgorithm RSA
but it's not right yet, I don't know about other rules mentioned there.

Sign a file with certificate using Powershell

I have a question, basically I have a file one txt and another one xml, I would like to sign those files with self signed certificate using Powershell.
Is there a way to do it?
My steps would be like that?
First create a self signed certificate with powershell
Then use that certificate in Powershell to sign the documents
Is that correct?
Any idea how to do that?
After the document is signed do I have to provide to another party this self sigend certificate to be able to open the files right? Or how will it work?
Accidentally, all my scripts are signed with an issued certificate, and it's my cmdlets to sign:
$cert = Get-ChildItem Cert:\CurrentUser\My -CodeSigningCert
Set-AuthenticodeSignature _path_to_my_script_ $cert -HashAlgorithm `
sha256 -TimestampServer "http://timestamp.digicert.com"
As to certificate, an issued one is recommended, rather than a self-signed one, it's not very expensive.
 If you want to use a self-signed certificate, I think this cmdlet helps you:
New-SelfSignedCertificate -FriendlyName "My Cert" -KeyUsage DigitalSignature -KeyUsageProperty Sign -KeyLength 2018 -KeyAlgorithm sha256 -Type CodeSigningCert -Subject "CN=System Error,e=mymail#mail.com"
I never created self-signed certificate on a personal computer, so this cmdlet is not verified. :(
If you have further questions, please let me know. :)

PowerShell: New-SelfSignedCertificate : CertEnroll::CX509Enrollment::_CreateRequest: Invalid flags specified. 0x80090009

I'm trying to create a certificate that I will later use for signing other certificates in development. I'm using the Powershell New-SelfSignedCertificate cmdlet.
Below is the command:
New-SelfSignedCertificate -CertStoreLocation Cert:\CurrentUser\My -Container In4mRootCATest* -DnsName in4monline-test.com -FriendlyName "In4m Test Root CA Cert" -KeyExportPolicy Exportable -KeyFriendlyName "In4m Test Root CA Cert Private Key" -KeyLocation "C:\scratch" -KeyProtection None -KeySpec Signature -KeyUsage CertSign,CRLSign,DigitalSignature -KeyUsageProperty All -NotAfter (Get-Date).AddMonths(72) -Provider "Microsoft Base DSS Cryptographic Provider" -Type Custom
The error I get is:
New-SelfSignedCertificate : CertEnroll::CX509Enrollment::_CreateRequest: Invalid flags specified. 0x80090009 (-2146893815 NTE_BAD_FLAGS)
At line:1 char:1
+ New-SelfSignedCertificate -CertStoreLocation Cert:\CurrentUser\My -Co ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [New-SelfSignedCertificate], Exception
+ FullyQualifiedErrorId : System.Exception,Microsoft.CertificateServices.Commands.NewSelfSignedCertificateCommand
Can anyone help me to understand what values I may be combining/submitting in error?
I'm on Windows 10.
Help is appreciated.
Remove the -provider argument, then use the Certificates MMC snap-in to see if the certificate is what you require.
I'm not an expert on certificates, but this might move you forward.
I'd suggest trying with another provider from the list you'll get with:
certutil -csplist
https://social.technet.microsoft.com/wiki/contents/articles/7573.active-directory-certificate-services-pki-key-archival-and-management.aspx
Client CSP Does Not Permit Key Export
For the client enrollment process to generate and send a private key to the CA, the key must be marked as exportable when the key is generated. If the certificate template is not set to allow key exportable or if the third-party CSP (if applicable) does not support exportable keys, enrollment will fail and the enrollment wizard will return an error that the key is not exportable. Third-party CSPs may report varying errors, such as “catastrophic failure”, when this occurs. If a Windows 2000 or Windows Millennium Edition client performs enrollment with key archival, the following error may appear if the key is not marked for export.
0x80090009 - NTE_BAD_FLAGS
Note: If the CSP supports the one-time flag for key archival, known as (CRYPT_ARCHIVABLE), the key export flag is not required. The Microsoft default software CSPs support this flag. However, Windows 2000 and Windows Millennium Edition clients do not support this flag and must allow the key to be exported for enrollment to work with key archival.

How to create the code signing certificate through the New-SelfSignedCertificate cmdlet

PowerShell 4.0
makecert tool has the -eku option for describing the enhanced key usage object identifiers (OIDs) into the certificate. It allows to make the certificates for code signing and for other purposes. But it is not a cmdlet.
New PowerShell versions have the New-SelfSignedCertificate cmdlet for local testing of the scripts. But it creates the certificate that can't be used for code signing:
New-SelfSignedCertificate -DnsName www.SomeSite.com -CertStoreLocation Cert:\CurrentUser\My
I don't see an option which is similar of -eku.
How can I set the destination of my new Self-Signed Certificate (created through New-SelfSignedCertificate cmdlet) for possibility of its use for code signing? Or is it possible to do the same via other cmdlet?
The version of New-SelfSignedCertificate on PS 4 is rather basic.
However Powershell v5 has the parameters that you would require to create specific keys.
Specifically a Keyusage parameter that takes
-- CertSign
-- CRLSign
-- DataEncipherment
-- DecipherOnly
-- DigitalSiganture
-- EncipherOnly
-- KeyAgreement
-- KeyEncipherment
-- None (default)
-- NonRepudiation
and a KeyUsageProperty taking
-- All
-- Decrypt
-- KeyAgreement
-- None (default)
-- Sign
Are you specifically tied to v4? If you can upgrade to v5 you should be able to achieve what you need.
Reviving this question as I was also looking for an answer to set Enhanced Key Usage (EKU) field for code signing using PowerShell New-SelfSignedCertificate command.
It can be done using the -TextExtension parameter to set EKU value. As an example, the following PowerShell (tested on PowerShell 5.1) script allows to create a 3-years self signed code signing certificate with extended key usage (and export it from the current user's certificates store to pfx file format):
# Enhanced Key Usage
$EKU = "2.5.29.37"
$EKU_CODE_SIGNING = "1.3.6.1.5.5.7.3.3"
$certificate = New-SelfSignedCertificate -Subject "CN=Testing Code Signing,E=info#mycompany.com,O=My Company" `
-FriendlyName "My Code Signing Certificate" `
-NotAfter (Get-Date).AddYears(3) `
-CertStoreLocation Cert:\CurrentUser\My `
-TextExtension #("$EKU={text}$EKU_CODE_SIGNING")
$password = ConvertTo-SecureString -String "mypassword" -Force -AsPlainText
Export-PfxCertificate -Cert "Cert:\CurrentUser\My\$($certificate.Thumbprint)" -FilePath "codesigning.pfx" -Password $password
Note: As a shortcut, the -Type CodeSigningCert parameter can be specified with the New-SelfSignedCertificate command instead of explicitly adding the EKU_CODE_SIGNING string to the -TextExtension parameter.
You can use PS' cert provider to access different cert stores (user vs machine), but that won't help with your OID problem. I suggest you look at .NET support for X509 certs. Google ".net x509 certificate" and you'll find the X509Certificate class on MSDN. From there read the class documentation and any overview documentation to see if creation of OIDs is supported. If .NET doesn't support it then you'd have to use P/Invoke to invoke native Windows CNG (cryptography next generation) APIs