“Invalid provider type specified” CryptographicException when trying to load private key of certificate

前端 未结 18 2945
盖世英雄少女心
盖世英雄少女心 2020-11-29 22:04

I\'m trying to read the private key of a certificate which has been shared with me by a third-party service provider, so I can use it to encrypt some XML before sending it t

18条回答
  •  臣服心动
    2020-11-29 22:57

    Powershell version of the answer from @berend-engelbrecht, assuming openssl installed via chocolatey

    function Fix-Certificates($certPasswordPlain)
    {
        $certs = Get-ChildItem -path "*.pfx" -Exclude "*.converted.pfx"
        $certs | ForEach-Object{
            $certFile = $_
    
            $shortName = [io.path]::GetFileNameWithoutExtension($certFile.Name)
            Write-Host "Importing $shortName"
            $finalPfx = "$shortName.converted.pfx"
    
    
            Set-Alias openssl "C:\Program Files\OpenSSL\bin\openssl.exe"
    
            # Extract public key
            OpenSSL pkcs12 -in $certFile.Fullname -nokeys -out "$shortName.cer" -passin "pass:$certPasswordPlain"
    
            # Extract private key
            OpenSSL pkcs12 -in $certFile.Fullname -nocerts -out "$shortName.pem" -passin "pass:$certPasswordPlain" -passout "pass:$certPasswordPlain"
    
            # Convert private key to RSA format
            OpenSSL rsa -inform PEM -in "$shortName.pem" -out "$shortName.rsa" -passin "pass:$certPasswordPlain" -passout "pass:$certPasswordPlain" 2>$null
    
            # Merge public keys with RSA private key to new PFX
            OpenSSL pkcs12 -export -in "$shortName.cer" -inkey "$shortName.rsa" -out $finalPfx -passin "pass:$certPasswordPlain" -passout "pass:$certPasswordPlain"
    
            # Clean up
            Remove-Item "$shortName.pem"
            Remove-Item "$shortName.cer"
            Remove-Item "$shortName.rsa"
    
            Write-Host "$finalPfx created"
        }
    }
    
    # Execute in cert folder
    Fix-Certificates password
    

提交回复
热议问题