-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathEncryptedCredential_ImportFunction.ps1
More file actions
77 lines (64 loc) · 2.57 KB
/
EncryptedCredential_ImportFunction.ps1
File metadata and controls
77 lines (64 loc) · 2.57 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
#region Encrypted Credential Import
<#
ENCRYPTED CREDENTIAL IMPORT TEMPLATE
Copy this section into any script that needs to use encrypted credentials.
Requirements:
1. Credential file must be created using Manage-EncryptedCredentials.ps1
2. Script must run as the SAME USER who created the credential file
3. Script must run on the SAME MACHINE where credential was created
To create a credential file, run:
.\Manage-EncryptedCredentials.ps1 -Action Create -ConfigName "YourCredName"
#>
function Import-EncryptedCredential {
[CmdletBinding()]
param(
[Parameter(Mandatory)]
[string]$CredentialName,
[Parameter()]
[string]$CredentialPath = "C:\Config\Credentials"
)
$FilePath = Join-Path $CredentialPath "$CredentialName.xml"
try {
if (-not (Test-Path $FilePath)) {
throw "Credential file not found: $FilePath"
}
Write-Verbose "Loading encrypted credential: $CredentialName"
$Config = Import-Clixml -Path $FilePath
# Decrypt credentials
$DecryptedCreds = @{}
foreach ($Key in $Config.Credentials.Keys) {
if ($Config.Credentials[$Key] -is [string] -and $Config.Credentials[$Key] -match '^[0-9a-f]+$') {
# Encrypted SecureString
try {
$DecryptedCreds[$Key] = $Config.Credentials[$Key] | ConvertTo-SecureString -ErrorAction Stop
}
catch {
throw "Failed to decrypt credential field '$Key'. Ensure you're running as user '$($Config.CreatedBy)' on machine '$($Config.MachineName)'."
}
}
else {
# Plain text value
$DecryptedCreds[$Key] = $Config.Credentials[$Key]
}
}
Write-Verbose "Successfully loaded $($DecryptedCreds.Count) credential fields"
return $DecryptedCreds
}
catch {
Write-Error "Failed to import encrypted credential '$CredentialName': $($_.Exception.Message)"
throw
}
}
# Quick helper to convert SecureString to plain text (use sparingly!)
function ConvertFrom-SecureStringToPlainText {
param([SecureString]$SecureString)
try {
$BSTR = [System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($SecureString)
return [System.Runtime.InteropServices.Marshal]::PtrToStringAuto($BSTR)
}
finally {
if ($BSTR) {
[System.Runtime.InteropServices.Marshal]::ZeroFreeBSTR($BSTR)
}
}
}