簡體   English   中英

將PowerShell中的加密/解密功能轉換為PHP(openssl_)

[英]Convert encryption / decryption function in PowerShell to PHP (openssl_)

我正在嘗試使PowerShell中的以下功能適應PHP:

function EncryptDES
{
Param(
    [String] $plainText,
    [byte[]] $Key,
    [byte[]] $Iv
)

    $tdsAlg = New-Object System.Security.Cryptography.DESCryptoServiceProvider
    $tdsAlg.Key = $Key
    $tdsAlg.IV = $Iv
    $encrypt = $tdsAlg.CreateEncryptor($tdsAlg.Key, $tdsAlg.IV)
    $msEncrypt = New-Object System.IO.MemoryStream
    $csEncrypt = New-Object System.Security.Cryptography.CryptoStream $msEncrypt, $encrypt, "Write"
    $swEncrypt = New-Object System.IO.StreamWriter $csEncrypt
    $swEncrypt.Write($plainText)
    $swEncrypt.Close()
    $csEncrypt.Close()
    $msEncrypt.Close()
    $encrypt.Clear()
    $encrypted = $msEncrypt.ToArray()
    $result = [Convert]::ToBase64String($encrypted)
    return $result;        
}

function DecryptDES
{
Param(
    [String] $encrypted,
    [byte[]] $Key,
    [byte[]] $Iv
)
    [byte[]]$NewStr = [System.Convert]::FromBase64String($encrypted)
    $tdsAlg = New-Object System.Security.Cryptography.DESCryptoServiceProvider
    $tdsAlg.Key = $Key
    $tdsAlg.IV = $Iv
    $encrypt = $tdsAlg.CreateDecryptor($tdsAlg.Key, $tdsAlg.IV)
    $msEncrypt = New-Object System.IO.MemoryStream @(,$NewStr)
    $csEncrypt = New-Object System.Security.Cryptography.CryptoStream $msEncrypt, $encrypt, "Read"
    $swEncrypt = New-Object System.IO.StreamReader $csEncrypt
    [String]$result = $swEncrypt.ReadToEnd()
    $swEncrypt.Close()
    $csEncrypt.Close()
    $msEncrypt.Close()
    $encrypt.Clear()

    return $result;     
}

我正在嘗試使用openssl_decrypt和openssl_encrpyt函數將此代碼轉換為PHP中的等效代碼,我嘗試使用以下代碼,但未得到任何結果:

function encrypt_decrypt($action, $string) {
    $output = false;
    $encrypt_method = "AES-256-CBC";
    $secret_key = 'This is my secret key';
    $secret_iv = 'This is my secret iv';
    // hash
    $key = hash('sha256', $secret_key);

    // iv - encrypt method AES-256-CBC expects 16 bytes - else you will get a warning
    $iv = substr(hash('sha256', $secret_iv), 0, 16);
    if ( $action == 'encrypt' ) {
        $output = openssl_encrypt($string, $encrypt_method, $key, 0, $iv);
        $output = base64_encode($output);
    } else if( $action == 'decrypt' ) {
        $output = openssl_decrypt(base64_decode($string), $encrypt_method, $key, 0, $iv);
    }
    return $output;
}

如果有人可以指導我,我將感謝您的幫助,謝謝

這是我開發的解決方案,並且效果很好:

<?php
$txt = 'ciphertext';
$key = '12345678';
$iv = '12345678';
$method = 'des-cbc';
// cipher_text
$code = openssl_encrypt($txt, $method, $key, true, $iv);

// ciper_text with base64_encode();
echo base64_encode($code);

// decrypt method
$result = openssl_decrypt($code, $method, $key, 1, $iv);
echo $result;
?>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM