My goal is to provide AES encryption of a string in PowerShell, send it to UNIX with python available, and decrypt the string back to plain text. I would also like to be able to do the reverse. I'm not a PowerShell / python programmer or programmer, but this is what I was able to do with the code:
function Create-AesManagedObject($key, $IV) { $aesManaged = New-Object "System.Security.Cryptography.AesManaged" $aesManaged.Mode = [System.Security.Cryptography.CipherMode]::CBC $aesManaged.Padding = [System.Security.Cryptography.PaddingMode]::Zeros $aesManaged.BlockSize = 128 $aesManaged.KeySize = 256 if ($IV) { if ($IV.getType().Name -eq "String") { $aesManaged.IV = [System.Convert]::FromBase64String($IV) } else { $aesManaged.IV = $IV } } if ($key) { if ($key.getType().Name -eq "String") { $aesManaged.Key = [System.Convert]::FromBase64String($key) } else { $aesManaged.Key = $key } } $aesManaged } function Encrypt-String($key, $unencryptedString) { $bytes = [System.Text.Encoding]::UTF8.GetBytes($unencryptedString) $aesManaged = Create-AesManagedObject $key $IV $encryptor = $aesManaged.CreateEncryptor() $encryptedData = $encryptor.TransformFinalBlock($bytes, 0, $bytes.Length); [byte[]] $fullData = $aesManaged.IV + $encryptedData $aesManaged.Dispose() [System.Convert]::ToBase64String($fullData) } function Decrypt-String($key, $encryptedStringWithIV) { $bytes = [System.Convert]::FromBase64String($encryptedStringWithIV) $IV = $bytes[0..15] $aesManaged = Create-AesManagedObject $key $IV $decryptor = $aesManaged.CreateDecryptor(); $unencryptedData = $decryptor.TransformFinalBlock($bytes, 16, $bytes.Length - 16); $aesManaged.Dispose() [System.Text.Encoding]::UTF8.GetString($unencryptedData).Trim([char]0) }
The PowerShell script seems to work just fine for encryption and decryption. For the python side, I can define the same AES key value as it is just base64 encoded in my passphrase. However, I do not get the encrypted string value at runtime (for example, PowerShell outputs UXKWIhtaUgFOvN13bvA4tx4 + 2Hjkv4v6I1G3Xfl6zp0 = and Python outputs BOJ3Ox4fJxR + jFZ0CBQ25Q ==). I believe that they will need to comply in order to be able to decrypt, but I could be wrong. I know that installing a static IV and a key makes it unsafe, but I am ready to do this in order to be able to encrypt and decrypt different platforms (unless there is a better method using AES). Any help would be appreciated.
Python code
import base64, array import Crypto import Crypto.Random from Crypto.Cipher import AES def pad_data(data): if len(data) % 16 == 0: return data databytes = bytearray(data) padding_required = 15 - (len(databytes) % 16) databytes.extend(b'\x80') databytes.extend(b'\x00' * padding_required) return bytes(databytes) def unpad_data(data): if not data: return data data = data.rstrip(b'\x00') if data[-1] == 128:
source share