-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGet-SecureStringPassword.ps1
More file actions
73 lines (61 loc) · 2.69 KB
/
Get-SecureStringPassword.ps1
File metadata and controls
73 lines (61 loc) · 2.69 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
Function Get-SecureStringPassword {
param(
[String] $Prefix = ""
,[String] $Filename = ''
,[String] $Username = $env:UserName
,[String] $Message
)
If ($Prefix -ne "") {
$Prefix = ($Prefix+"_")
}
If ($Filename -eq '') {
$HostUser = $Env:ComputerName + $env:UserName
# Write-Output ('$HostUser: '+$HostUser)
$MD5 = new-object -TypeName System.Security.Cryptography.MD5CryptoServiceProvider
$UTF8 = new-object -TypeName System.Text.UTF8Encoding
$Hash = ([System.BitConverter]::ToString($MD5.ComputeHash($UTF8.GetBytes($HostUser)))).Replace("-","")
# Write-Output ('$Hash: '+$Hash)
$Filename = ($Prefix+$Hash+".txt")
Write-Host ('Retrieving credentials from: '+$Filename)
}
if ($Username -eq "") {
$Username = $env:UserName
# Write-Output ('Username empty, $Username: '+$Username)
}
if (Test-Path $Filename) {
# Write-Output ('$Filename exists')
$pwdTxt = Get-Content $Filename
$securePwd = $pwdTxt | ConvertTo-SecureString
$Credentials = New-Object System.Management.Automation.PSCredential -ArgumentList $UserName, $securePwd
} else {
# Write-Output ('File does not exist, requesting credential interactively')
# Write-Log('Requesting Credentials...')
# $Credentials = Get-Credential -UserName $Username -Message $Message
Write-Host ("Username: "+$Username)
$Password = Read-Host 'Password' -AsSecureString
Set-SecureStringPassword -Password $Password -Prefix $Prefix
$Credentials = New-Object System.Management.Automation.PSCredential -ArgumentList $UserName, $Password
}
# Write-Output ('Object Type: '+$Credentials.GetType().Name)
Return $Credentials
}
Function Set-SecureStringPassword {
param(
[Parameter(Mandatory=$True)][Security.SecureString] $Password
, [String] $Prefix = ""
,[String] $Filename = ''
)
If ($Prefix -ne "" -and $Prefix.Substring($Prefix.Length-1,1) -ne '_') {
$Prefix = ($Prefix+"_")
}
If ($Filename -eq '') {
$HostUser = $Env:ComputerName + $env:UserName
$MD5 = new-object -TypeName System.Security.Cryptography.MD5CryptoServiceProvider
$UTF8 = new-object -TypeName System.Text.UTF8Encoding
$Hash = ([System.BitConverter]::ToString($MD5.ComputeHash($UTF8.GetBytes($HostUser)))).Replace("-","")
$Filename = ($Prefix+$Hash+".txt")
}
$SecureStringText = $Password | ConvertFrom-SecureString
Set-Content $Filename $SecureStringText
#Write-Host ('Wrote SecureString to '+$filename+', Done')
}