Encrypt from powershell and decrypt from python

Viewed 453

I was writing my own collectd package for windows as it is not available out of box an I needed to encrypt all my metrics data from powershell and decrypt on my Unix box using python when it is transferred over the network. This was a requirement from my security team to approve my solution. I was looking for solution everywhere but didn't find one.

Just posting what i wrote just in case someone ends up here with the same scenario

My scenario:

  • My AES key will be an ASCII password
  • MY IV will be auto generated from the system
  • My data is json and a huge block of text (I used simple text for this testing)

powershell :


$plainText  = 'Testing my encrypting'
$encoding   = New-Object System.Text.ASCIIEncoding
$key        = $encoding.GetBytes("P0Shell Encrypt 2 Pyth0n D3crypt")
$InitializationVector = [System.Byte[]]::new(16)

$AESCipher  = New-Object System.Security.Cryptography.AesCryptoServiceProvider
$AESCipher.Key  = $key
$AESCipher.IV   = $InitializationVector

$Text2Bytes     = [System.Text.Encoding]::UTF8.GetBytes($plainText)
$Encryptor      = $AESCipher.CreateEncryptor()
$EncryptedBytes = $Encryptor.TransformFinalBlock($Text2Bytes, 0, $Text2Bytes.Length)

[byte[]] $FullData    = $AESCipher.IV + $EncryptedBytes
$CipherText     = [System.Convert]::ToBase64String($FullData)
$CipherText

$AESCipher.Dispose()

Run the program on powershell:

PS C:\Users\pkkatta\Documents> .\encrypt2.ps1 AAAAAAAAAAAAAAAAAAAAAF8fl8OpJQZv4x8lNeJ6CZdDwIyDGHMVcnCqx32tV9kZ

Python Code:


#!/usr/bin/env python3

from Crypto.Cipher import AES
import base64

key = b"P0Shell Encrypt 2 Pyth0n D3crypt"
enc_String = 'AAAAAAAAAAAAAAAAAAAAAF8fl8OpJQZv4x8lNeJ6CZdDwIyDGHMVcnCqx32tV9kZ'

Enc_bytes = base64.b64decode(enc_String)
iv = Enc_bytes[:16]
aes = AES.new(key, AES.MODE_CBC, iv)
print (aes.decrypt(Enc_bytes[16:]).decode("utf-8"))

On execution of python code:

bash-4.2# ./decrypt.py

Testing my encrypting

Hope someone finds this useful

0 Answers
Related