0

有人可以帮我编写代码来加密 Oracle 中的字符串并使用 powershell 解密吗?AES,DES,任何一个都可以。我觉得我很接近,但我错过了一些东西......

另请参阅这篇文章:将 PowerShell 中的加密/解密函数转换为 PHP (openssl_)

使用该 Powershell 加密,我可以将“它的秘密”变成“AEe2LSdmwi79UYduDZS7Mg =”。下面将其解密。但是如何在 Oracle 中进行加密呢?

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;     
    }
    $enc = [system.Text.Encoding]::UTF8
    $string1 = "PeShVmYq" 
    $data1 = $enc.GetBytes($string1) 
    
    $dec = DecryptDES -encrypted 'AEe2LSdmwi79UYduDZS7Mg==' -Key $data1 -Iv $data1
    Write-Host $dec

到目前为止,我有这个 Oracle SQL:

select           
       dbms_crypto.Encrypt(
       src => UTL_RAW.CAST_TO_RAW('Its a secret'),
       typ => 4353,
       key => UTL_ENCODE.BASE64_DECODE(UTL_RAW.CAST_TO_RAW('PeShVmYq')),
       iv => UTL_ENCODE.BASE64_DECODE(UTL_RAW.CAST_TO_RAW('PeShVmYq')))
from dual

哪个输出:

F480D03A9564CAAD0CD815EA1524B6B7

4

1 回答 1

2

您需要将密钥和 IV 保留为 RAW,而不是 base64 编码;然后base64编码加密调用的结果;最后将该 RAW 转换回字符串:

select
       utl_raw.cast_to_varchar2(
         utl_encode.base64_encode(
           dbms_crypto.encrypt(
             src => utl_raw.cast_to_raw('Its a secret'),
             typ => 4353,
             key => utl_raw.cast_to_raw('PeShVmYq'),
             iv => utl_raw.cast_to_raw('PeShVmYq')
           )
         )
       ) as encrypted
from dual;

ENCRYPTED                                                       
----------------------------------------------------------------
AEe2LSdmwi79UYduDZS7Mg==

正如您在 PowerShell 脚本中指定的 UTF-8 一样,通常情况下,使用特定字符集进行 RAW/字符串转换可能会更好:

select
       utl_i18n.raw_to_char(
         utl_encode.base64_encode(
           dbms_crypto.encrypt(
             src => utl_i18n.string_to_raw(data => 'Its a secret', dst_charset => 'AL32UTF8'),
             typ => 4353,
             key => utl_i18n.string_to_raw(data => 'PeShVmYq', dst_charset => 'AL32UTF8'),
             iv => utl_i18n.string_to_raw(data => 'PeShVmYq', dst_charset => 'AL32UTF8')
           )
         ),
         src_charset => 'AL32UTF8'
       ) as encrypted
from dual;

得到相同的结果。


仅供参考,typ值 4353 (0x1101) 来自:

dbms_crypto.encrypt_des + dbms_crypto.chain_cbc + dbms_crypto.pad_pkcs5

AES256 等效值为 4360;但是您还需要更长的密钥。

于 2021-08-26T18:08:16.813 回答