This commit is contained in:
vanzue
2025-04-22 09:56:41 +08:00
parent def90e6c1b
commit 302e1398ed

View File

@@ -1,8 +1,4 @@
param (
[string]$certSubject = "CN=Microsoft Corporation, O=Microsoft Corporation, L=Redmond, S=Washington, C=US"
)
function Import-And-VerifyCertificate {
function ImportAndVerifyCertificate {
param (
[string]$cerPath,
[string]$storePath
@@ -33,40 +29,44 @@ function Import-And-VerifyCertificate {
}
}
$cert = Get-ChildItem -Path Cert:\CurrentUser\My |
Where-Object { $_.Subject -eq $certSubject } |
Sort-Object NotAfter -Descending |
Select-Object -First 1
function EnsureCertificate {
param (
[string]$certSubject = "CN=Microsoft Corporation, O=Microsoft Corporation, L=Redmond, S=Washington, C=US"
)
if (-not $cert) {
Write-Host "📜 Certificate not found. Creating a new one..."
$cert = New-SelfSignedCertificate -Subject $certSubject `
-CertStoreLocation "Cert:\CurrentUser\My" `
-KeyAlgorithm RSA `
-Type CodeSigningCert `
-HashAlgorithm SHA256
$cert = Get-ChildItem -Path Cert:\CurrentUser\My |
Where-Object { $_.Subject -eq $certSubject } |
Sort-Object NotAfter -Descending |
Select-Object -First 1
if (-not $cert) {
Write-Error "❌ Failed to create a new certificate."
exit 1
Write-Host "📜 Certificate not found. Creating a new one..."
$cert = New-SelfSignedCertificate -Subject $certSubject `
-CertStoreLocation "Cert:\CurrentUser\My" `
-KeyAlgorithm RSA `
-Type CodeSigningCert `
-HashAlgorithm SHA256
if (-not $cert) {
Write-Error "❌ Failed to create a new certificate."
return $null
}
Write-Host "✔️ New certificate created with thumbprint: $($cert.Thumbprint)"
}
else {
Write-Host "📌 Using existing certificate with thumbprint: $($cert.Thumbprint)"
}
Write-Host "✔️ New certificate created with thumbprint: $($cert.Thumbprint)"
}
else {
Write-Host "📌 Using existing certificate with thumbprint: $($cert.Thumbprint)"
}
$cerPath = "$env:TEMP\temp_cert.cer"
Export-Certificate -Cert $cert -FilePath $cerPath -Force
# Step 2: Export and trust it in necessary stores
$cerPath = "$env:TEMP\temp_cert.cer"
Export-Certificate -Cert $cert -FilePath $cerPath -Force
if (-not (ImportAndVerifyCertificate -cerPath $cerPath -storePath "Cert:\CurrentUser\TrustedPeople")) { return $null }
if (-not (ImportAndVerifyCertificate -cerPath $cerPath -storePath "Cert:\CurrentUser\Root")) { return $null }
if (-not (ImportAndVerifyCertificate -cerPath $cerPath -storePath "Cert:\LocalMachine\Root")) {
Write-Warning "⚠️ Failed to import to LocalMachine\Root (admin may be required)"
}
if (-not (Import-And-VerifyCertificate -cerPath $cerPath -storePath "Cert:\CurrentUser\TrustedPeople")) { exit 1 }
if (-not (Import-And-VerifyCertificate -cerPath $cerPath -storePath "Cert:\CurrentUser\Root")) { exit 1 }
if (-not (Import-And-VerifyCertificate -cerPath $cerPath -storePath "Cert:\LocalMachine\Root")) {
Write-Warning "⚠️ Failed to import to LocalMachine\Root (admin may be required)"
}
# Return the certificate object
return $cert
return $cert
}