I am writing a python script to decrypt password by calling Powershell functions:
import subprocess
keypwd = "BoFaTnpCv0XYrVxND8mi"
pwd= "76492d1116743f0423413b16050a5345MgB8AFUAMQA5AHEAWABvAFMAdwBHAEQASQAyAHcAVABJAHMAbwBKAHAASwBBAEEAPQA9AHwANAA4ADAANwA0ADAANQA5ADEAMgBlADkAZABjAGEAZQA5ADUAZQAyADcAZQBmADAAZAA1AGQAMAAxAGYAMAA0ADQAMQA5ADcAOAAxAGMAYgBlAGYAMwAwADcANwBhADMAMwA0AGMAOQAzAGYAOQA0AGQAMwAwAGMAYgA3ADMAMQA4AGQAYgBlAGUANAAyADQAOQAzADcAMABkADQAMABmADAAMABmADAAYwBkADQAMwBkADMAMABkAGUAOABjAGIA"
POWERSHELL = 'powershell -c "{0}"'
KEY_DECRYPT_CMD = '''Function KeySet {{
[CmdletBinding(SupportsShouldProcess,ConfirmImpact = 'None')]
param([string]$string)
$length = $string.length
$pad = 32-$length
$encoding = New-Object System.Text.ASCIIEncoding
$bytes = $encoding.GetBytes($string + "0" * $pad)
return $bytes
}}
Function DecryptData ($data, $key) {{
$data | ConvertTo-SecureString -key $key |
ForEach-Object {{[Runtime.InteropServices.Marshal]::PtrToStringAuto([Runtime.InteropServices.Marshal]::SecureStringToBSTR($_))}}
}}
$setkey = KeySet '{key}';
DecryptData -data '{pwd}' -key $setkey
'''
cmd1 = POWERSHELL.format(KEY_DECRYPT_CMD.format(pwd=pwd, key = keypwd))
p = subprocess.Popen(cmd1, stdout=subprocess.PIPE,stderr=subprocess.PIPE)
stdout,stderr = p.communicate()
If I run independently only first function (KeySet) in Python, I am getting the following output:
b'66\r\n111\r\n70\r\n97\r\n84\r\n110\r\n112\r\n67\r\n118\r\n48\r\n88\r\n89\r\n114\r\n86\r\n120\r\n78\r\n68\r\n56\r\n109\r\n105\r\n48\r\n'
which is the same output I get in Powershell (though without \r\n parts).
However, the second function (DecryptData) is not working when it is called from Python.
The error message I get is the following:
b'ConvertTo-SecureString :
The specified key is not valid. Valid key length settings are either 128 bits, 192 bits, or \r\n256 bits.
\r\nAt line:12 char:13\r\n+ $data | ConvertTo-SecureString -key $key |\r\n+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\r\n
+ CategoryInfo : InvalidArgument: (:) [ConvertTo-SecureString], PSArgumentException\r\n
+ FullyQualifiedErrorId : ImportSecureString_InvalidArgument,Microsoft.PowerShell.Commands.ConvertToSecureStringCo \r\n mmand\r\n \r\n'
The same script works without any problems in Powershell.
I think the issue occurs because the key is not passed in the correct form in the DecryptData function, but I am not able to find the solution.
Is there a way to make this code work?