2022-07-15

在 PowerShell 與 PHP 之間交換加密訊息

Powershell:

#----------------

Function myEncrypt {

param (
[String]$Data,
[String]$EncryptKey
);

PROCESS {

$Encode = [System.Text.Encoding]::UTF8;
$DataBytes = $Encode.GetBytes($Data);

$AES = New-Object System.Security.Cryptography.AESManaged;
$AES.BlockSize = 128;
$AES.KeySize = 256;
$AES.Mode = [System.Security.Cryptography.CipherMode]::CBC;
$iv = RandomPassword(($AES.BlockSize / 8));
$AES.IV = $Encode.GetBytes($iv);
$AES.Key = $Encode.GetBytes($EncryptKey);

$Encryptor = $AES.CreateEncryptor();
$EncryptedBytes = $Encryptor.TransformFinalBlock($DataBytes, 0, $DataBytes.length);

return ([Convert]::ToBase64String($Encode.GetBytes($iv + ([Convert]::ToBase64String($EncryptedBytes)))));
};
};

#----------------

Function myDecrypt {

param (
[String]$Data,
[String]$EncryptKey
);

PROCESS {

$Encode = [System.Text.Encoding]::UTF8;
$DataString = $Encode.GetString([Convert]::FromBase64String($Data));

$AES = New-Object System.Security.Cryptography.AESManaged;
$AES.BlockSize = 128;
$AES.KeySize = 256;
$AES.Mode = [System.Security.Cryptography.CipherMode]::CBC;
$iv = $DataString.SubString(0,($AES.BlockSize / 8));
$AES.IV = $Encode.GetBytes($iv);
$AES.Key = $Encode.GetBytes($EncryptKey);

$Decryptor = $AES.CreateDecryptor();
$DataBytes = [Convert]::FromBase64String($DataString.SubString(($AES.BlockSize / 8)));

return $Encode.GetString($Decryptor.TransformFinalBlock($DataBytes, 0, $DataBytes.Length));
};
};

#----------------

Function RandomPassword {

param (
[int]$PasswordLength = 16
);

PROCESS {

return (("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz".tochararray() | sort {Get-Random})[0..($PasswordLength - 1)] -join '');
};
};

#----------------

PowerShell Test:

$KeySize = 256;
$EncryptKey= RandomPassword(($KeySize / 8));

myEncrypt "abcde" $EncryptKey

myDecrypt (myEncrypt "abcde" $EncryptKey) $EncryptKey


PHP:

#----------------

Function myEncrypt($Data, $EncryptKey) {
$AESBlockSize = 128;
$iv = RandomPassword(($AESBlockSize/8));
$Encrypted = openssl_encrypt($Data, 'aes-256-cbc', $EncryptKey, 0, $iv);
return base64_encode($iv.$Encrypted);
};

#----------------

Function myDecrypt($Data, $EncryptKey) {
$AESBlockSize = 128;
$DataDecode = base64_decode($Data);
$iv = substr($DataDecode,0,($AESBlockSize/8));
$Encrypted_data = substr($DataDecode,($AESBlockSize/8));
return openssl_decrypt($Encrypted_data, 'aes-256-cbc', $EncryptKey, 0, $iv);
};

#----------------

Function RandomPassword($PasswordLength=16) {
$Alphabet = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
$Password = Array();
$AlphaLength = strlen($Alphabet) - 1;
for ($i = 0; $i < $PasswordLength; $i++) {
$Password[] = $Alphabet[(rand(0, $AlphaLength))];
};
return implode($Password);
};

#----------------

PHP Test:

$KeySize = 256;
$EncryptKey= RandomPassword(($KeySize / 8));

echo myEncrypt("abcde",$EncryptKey);

echo myDecrypt(myEncrypt("abcde",$EncryptKey),$EncryptKey);


沒有留言:

張貼留言