전원 셸 및 오류 ConvertTo-SecureString : 키가 지정된 상태에서 사용할 수 없도록 유효하지 않음을 사용하여 재사용을 위한 자격 증명 저장
Invoke-command: http://blogs.technet.com/b/robcost/archive/2008/05/01/powershell-tip-storing-and-using-password-credentials.aspx 을 통해 원격 PS 스크립트를 실행하기 위해 자동화된 프로세스가 사용할 수 있도록 보안 파일에 자격 증명을 저장하기 위해 이 게시물에 설명된 것과 같은 작업을 수행하고 있었습니다.
암호화된 파일에서 암호가 읽혀지고 Invoke-command로 전달되며 모든 것이 정상입니다.
스크립트가 황금 시간대에 준비되었을 때, 자동화된 프로세스에서 사용할 Windows 계정으로 스크립트를 실행하려고 시도했지만 스크립트가 파일에서 보안 암호를 읽으려고 하는 동안 아래와 같은 오류가 발생했습니다.
ConvertTo-SecureString : Key not valid for use in specified state.
At \\remoted\script.ps1:210 char:87
+ $password = get-content $PathToFolderWithCredentials\pass.txt | convertto-sec
urestring <<<<
+ CategoryInfo : InvalidArgument: (:) [ConvertTo-SecureString], C
ryptographicException
+ FullyQualifiedErrorId : ImportSecureString_InvalidArgument_Cryptographic
Error,Microsoft.PowerShell.Commands.ConvertToSecureStringCommand
제 동료에게 계정으로 실행해달라고 요청했는데도 같은 오류가 발생했습니다.
자격 증명을 저장하기 위해 사용하는 코드입니다.
$PathToFolderWithCredentials = "\\path\removed"
write-host "Enter login as domain\login:"
read-host | out-file $PathToFolderWithCredentials\login.txt
write-host "Enter password:"
read-host -assecurestring | convertfrom-securestring | out-file $PathToFolderWithCredentials\pass.txt
write-host "*** Credentials have been saved to $pathtofolder ***"
Invoke-command에서 사용할 스크립트를 읽기 위해 자동화된 프로세스에 의해 실행되는 스크립트의 코드는 다음과 같습니다.
$login= get-content $PathToFolderWithCredentials\login.txt
$password = get-content $PathToFolderWithCredentials\pass.txt | convertto-securestring
$credentials = new-object -typename System.Management.Automation.PSCredential -argumentlist $login,$password
$password = get-content $PathToFolderWithCredentials\pass에서 오류가 발생합니다.txt | 보안 문자열로 변환
무슨 생각 있어요?
동일한 컴퓨터에 암호 문자열을 만들고 이 문자열을 실행하는 데 사용할 로그인을 사용해야 합니다.
ConvertFrom-SecureString
가.Key
(그리고SecureKey
) 파라미터.암호화된 표준 문자열을 저장할 키를 지정한 다음 키를 다시 사용할 수 있습니다.ConvertTo-SecureString
사용자 계정에 관계없이 보안 문자열을 반환합니다.
http://technet.microsoft.com/en-us/library/dd315356.aspx
프로젝트에서, 나는 사람들이 공개 키를 사용하여 비밀번호를 암호화하고 자동화 프로세스는 비밀번호를 해독하는 개인 키를 가지는 비대칭 암호화를 구현했습니다: 자동 배포를 위해 프로덕션 구성에서 비밀번호 처리
아래에서는 자격 증명을 파일로 저장한 다음 다른 사용자가 원격으로 실행 중인 다른 스크립트에서 해당 자격 증명을 사용할 수 있습니다.
이 코드는 데이비드 리가 제작한 훌륭한 기사에서 가져온 것으로, 제 자신으로부터 약간의 수정만 받은 것입니다. https://blog.kloud.com.au/2016/04/21/using-saved-credentials-securely-in-powershell-scripts/
첫 번째 단계는 AES를 사용하여 파일에 보안 암호를 저장하는 것입니다.다음은 독립 실행형 스크립트로 실행됩니다.
# Prompt you to enter the username and password
$credObject = Get-Credential
# The credObject now holds the password in a ‘securestring’ format
$passwordSecureString = $credObject.password
# Define a location to store the AESKey
$AESKeyFilePath = “aeskey.txt”
# Define a location to store the file that hosts the encrypted password
$credentialFilePath = “credpassword.txt”
# Generate a random AES Encryption Key.
$AESKey = New-Object Byte[] 32
[Security.Cryptography.RNGCryptoServiceProvider]::Create().GetBytes($AESKey)
# Store the AESKey into a file. This file should be protected! (e.g. ACL on the file to allow only select people to read)
Set-Content $AESKeyFilePath $AESKey # Any existing AES Key file will be overwritten
$password = $passwordSecureString | ConvertFrom-SecureString -Key $AESKey
Add-Content $credentialFilePath $password
그런 다음 자격 증명을 사용해야 하는 스크립트에서 다음을 사용합니다.
#set up path and user variables
$AESKeyFilePath = “aeskey.txt” # location of the AESKey
$SecurePwdFilePath = “credpassword.txt” # location of the file that hosts the encrypted password
$userUPN = "domain\userName" # User account login
#use key and password to create local secure password
$AESKey = Get-Content -Path $AESKeyFilePath
$pwdTxt = Get-Content -Path $SecurePwdFilePath
$securePass = $pwdTxt | ConvertTo-SecureString -Key $AESKey
#crete a new psCredential object with required username and password
$adminCreds = New-Object System.Management.Automation.PSCredential($userUPN, $securePass)
#use the $adminCreds for some task
some-Task-that-needs-credentials -Credential $adminCreds
사용자가 비밀번호 파일과 키 파일에 접근할 수 있다면 사용자의 비밀번호를 해독할 수 있습니다.
또 다른 접근 방식은 ConvertFrom-SecureString에서 사용되는 'CurrentUser' 대신 스코프 'LocalMachine'을 사용하여 데이터를 보호하는 것입니다.
public static string Protect(SecureString input, DataProtectionScope dataProtectionScope = DataProtectionScope.CurrentUser, byte[] optionalEntropy = null)
{
byte[] data = SecureStringToByteArray(input);
byte[] data2 = ProtectedData.Protect(data, optionalEntropy, dataProtectionScope);
for (int i = 0; i < data.Length; i++)
{
data[i] = 0;
}
return ByteArrayToString(data2);
}
private static byte[] SecureStringToByteArray(SecureString s)
{
var array = new byte[s.Length * 2];
if (s.Length > 0)
{
IntPtr intPtr = Marshal.SecureStringToGlobalAllocUnicode(s);
try
{
Marshal.Copy(intPtr, array, 0, array.Length);
}
finally
{
Marshal.FreeHGlobal(intPtr);
}
}
return array;
}
private static string ByteArrayToString(byte[] data)
{
var stringBuilder = new StringBuilder();
for (int i = 0; i < data.Length; i++)
{
stringBuilder.Append(data[i].ToString("x2", CultureInfo.InvariantCulture));
}
return stringBuilder.ToString();
}
암호화된 문자열은 스코프 'CurrentUser'를 사용하는 ConvertTo-SecureString에서 사용할 수 있습니다.
자격 증명을 사용할 N명의 사용자(예: 한 개발자)의 알려진 목록이 있다고 가정합니다.userMe
시스템/서비스 사용자userSys
(해당 사용자에게) N개의 복사본을 만들 수 있습니다.pass.txt
파일: 각 사용자마다 하나씩.
그래서 비밀번호가.userX
를 들어 2어 2가 합니다.*.pass.txt
일:
userX.userMe.pass.txt
userX.userSys.pass.txt
userMe가 읽은 크레딧을 원할 때userX.userMe.pass.txt
타
언급URL : https://stackoverflow.com/questions/7109958/saving-credentials-for-reuse-by-powershell-and-error-convertto-securestring-ke
'sourcecode' 카테고리의 다른 글
C에서 런타임에 매크로 변경 (0) | 2023.11.04 |
---|---|
"WARn Can't can't decision-length of response body"는 무엇을 의미하며 어떻게 제거해야 합니까? (0) | 2023.11.04 |
C의 함수명은 어떤 타입입니까? (0) | 2023.10.30 |
jQuery에서 숫자에 쉼표를 더합니다. (0) | 2023.10.30 |
각 행의 결측/NaN 수 계산 (0) | 2023.10.30 |