Create PFX/Cer Self Signed Certificates using PowerShell

Create PFX/Cer Self Signed Certificates using PowerShell


In today’s digital landscape, securing communications and data is more critical than ever. Certificates play a vital role in this process by enabling encrypted connections and verifying the identity of servers and clients. While certificates from trusted Certificate Authorities (CAs) are commonly used, there are many scenarios where creating self-signed certificates is both practical and necessary.


This article will guide you through the process of creating PFX and CER self-signed certificates using PowerShell. Whether you’re setting up a development environment, testing applications, or securing internal communications, self-signed certificates offer a flexible and cost-effective solution.


Remember :

  • I strongly recommand to buy certificate from trusted Certificate Authorities (CAs).
  • This alternative is for test environments.


Here is PowerShell script :


You need to change this settings :

  • Certificate Name
  • Password to export certificate
  • Validity period in years



# Certificate Name
$CertificateName = "SSC-TEST1"

# Password to export certificate (You can change it with yours)
$CertPasswd =  "DFggdf456AAdfGT4ererT4"

# Validity period in years
$Years = 5

#  Create Certificate
$certificate = New-SelfSignedCertificate `
    -Subject localhost `
    -DnsName localhost `
    -KeyAlgorithm RSA `
    -KeyLength 2048 `
    -NotBefore (Get-Date) `
    -NotAfter (Get-Date).AddYears($Years) `
    -CertStoreLocation "cert:CurrentUser\My" `
    -FriendlyName $CertificateName `
    -HashAlgorithm SHA256 `
    -KeyUsage DigitalSignature, KeyEncipherment, DataEncipherment `
    -TextExtension @("2.5.29.37={text}1.3.6.1.5.5.7.3.1")

# Get Certificate Path    
$certificatePath = 'Cert:\CurrentUser\My\' + ($certificate.ThumbPrint)

# Prepare parameters to export certificates
$pfxPassword = ConvertTo-SecureString ($CertPasswd) -Force -AsPlainText
$pfxFilePath = "C:\Temp\$($CertificateName).pfx"
$cerFilePath = "C:\Temp\$($CertificateName).cer"

# Create C:\Temp if it doesnt exist
if(!(test-path("C:\Temp")))
{
    New-Item -Path "C:\Temp" -ItemType Directory
}

# Export the certificate to CER and PFX (PKCS #12). 
Export-PfxCertificate -Cert $certificatePath -FilePath $pfxFilePath -Password $pfxPassword
Export-Certificate -Cert $certificatePath -FilePath $cerFilePath
 
# Now that the certificate has been exported, delete the cert.
Remove-Item $certificatePath        

Here is Print screen :

And here is two certificates :

Thanks


Aymen EL JAZIRI

System Administrator

JEREMIE DELTHIL

Admin M365 | SysAdmin | Chef de projet - chez Conseil départemental de la Haute-Garonne

1 周

Very nice , as usual. Never in prod ??

要查看或添加评论,请登录

Aymen E.的更多文章