0

何らかの理由で、同じ暗号化キーDMBS_CRYPTOを使用した Oracle および .NET 実装とは異なるエンコード結果が得られます。DESCryptoServiceProvider

DB の場合DBMS_CRYPTO.ENCRYPT、次の暗号化タイプの関数を使用しています。

   encryption_type    PLS_INTEGER := DBMS_CRYPTO.ENCRYPT_DES
                                + DBMS_CRYPTO.CHAIN_CBC
                                +DBMS_CRYPTO.PAD_PKCS5;

DB機能

 FUNCTION encrypt (p_plainText VARCHAR2) RETURN RAW DETERMINISTIC
 IS
    encrypted_raw      RAW (2000);
 BEGIN
    encrypted_raw := DBMS_CRYPTO.ENCRYPT
    (
       src => UTL_RAW.CAST_TO_RAW (p_plainText),
       typ => encryption_type,
       key => encryption_key
    );
   RETURN encrypted_raw;
 END encrypt;

そして、ここにC#の部分があります:

            DESCryptoServiceProvider cryptoProvider = new DESCryptoServiceProvider();
        MemoryStream memoryStream = new MemoryStream();
        CryptoStream cryptoStream = new CryptoStream(memoryStream,
            cryptoProvider.CreateEncryptor(bytes, bytes), CryptoStreamMode.Write);
        StreamWriter writer = new StreamWriter(cryptoStream);
        writer.Write(originalString);
        writer.Flush();
        cryptoStream.FlushFinalBlock();
        writer.Flush();
        return Convert.ToBase64String(memoryStream.GetBuffer(), 0, (int)memoryStream.Length);

暗号化の結果が異なる理由は何ですか?

4

3 に答える 3

2

.NET と Oracle の暗号化には基本的な違いがあります。

たとえば、Oracle のデフォルトの初期化値 (IV) は 16 進数で "0123456789ABCDEF" です。.NET のデフォルトの初期化値 (IV) は 16 進数で "C992C3154997E0FB" です。また、.NET のパディング モードにはいくつかのオプションがあります: ANSIX923、Zeros、ISO10126、PKCS7、および None。

以下のサンプル コードでは、カスタム パディングに使用する 2 行のコードを省略でき、パディング モードに ANSIX923 を指定できます。文字列にチルダ "~" 文字を埋め込むことを決定した DBA の失敗に対応する必要があったため、同様の状況で他の人を助ける可能性がある例としてコードを含めました。

以下は、私たちのソリューションで機能した簡単な一連のメソッドです。

    private static string EncryptForOracle(string message, string key)
    {

        string iv = "0123456789ABCDEF";

        int lengthOfPaddedString;
        message = PadMessageWithCustomChar(message, out lengthOfPaddedString);

        byte[] textBytes = new byte[lengthOfPaddedString];
        textBytes = ASCIIEncoding.ASCII.GetBytes(message);

        byte[] keyBytes = new byte[key.Length];
        keyBytes = ASCIIEncoding.ASCII.GetBytes(key);

        byte[] ivBytes = new byte[iv.Length];
        ivBytes = StringUtilities.HexStringToByteArray(iv);
        byte[] encrptedBytes = Encrypt(textBytes, keyBytes, ivBytes);

        return StringUtilities.ByteArrayToHexString(encrptedBytes);
    }

    /// <summary>
    // On the Oracle side, our DBAs wrapped the call to the toolkit encrytion function to pad with a ~, I don't recommend
    // doing down this path, it is prone to error.
    // we are working with blocks of size 8 bytes, this method pads the last block with ~ characters.
    /// </summary>
    /// <param name="message"></param>
    /// <param name="lengthOfPaddedString"></param>
    /// <returns></returns>
    private static string PadMessageWithCustomChar(string message, out int lengthOfPaddedString)
    {
        int lengthOfData = message.Length;
        int units;
        if ((lengthOfData % 8) != 0)
        {
            units = (lengthOfData / 8) + 1;
        }
        else
        {
            units = lengthOfData / 8;
        }

        lengthOfPaddedString = units * 8;

        message = message.PadRight(lengthOfPaddedString, '~');
        return message;
    }


    public static byte[] Encrypt(byte[] clearData, byte[] Key, byte[] IV)
    {
        MemoryStream ms = new MemoryStream();
        // Create a symmetric algorithm.
        TripleDES alg = TripleDES.Create();
        alg.Padding = PaddingMode.None;
        // You should be able to specify ANSIX923 in a normal implementation 
        // We have to use none because of the DBA's wrapper
        //alg.Padding = PaddingMode.ANSIX923;

        alg.Key = Key;
        alg.IV = IV;

        CryptoStream cs = new CryptoStream(ms, alg.CreateEncryptor(), CryptoStreamMode.Write);
        cs.Write(clearData, 0, clearData.Length);
        cs.Close();

        byte[] encryptedData = ms.ToArray();
        return encryptedData;
    }

これらのメソッドを静的な StringUtilities クラスに配置します。

    /// <summary>
    /// Method to convert a string of hexadecimal character pairs
    /// to a byte array.
    /// </summary>
    /// <param name="hexValue">Hexadecimal character pair string.</param>
    /// <returns>A byte array </returns>
    /// <exception cref="System.ArgumentNullException">Thrown when argument is null.</exception>
    /// <exception cref="System.ArgumentException">Thrown when argument contains an odd number of characters.</exception>
    /// <exception cref="System.FormatException">Thrown when argument contains non-hexadecimal characters.</exception>
    public static byte[] HexStringToByteArray(string hexValue)
    {
        ArgumentValidation.CheckNullReference(hexValue, "hexValue");

        if (hexValue.Length % 2 == 1)
            throw new ArgumentException("ERROR: String must have an even number of characters.", "hexValue");

        byte[] values = new byte[hexValue.Length / 2];

        for (int i = 0; i < values.Length; i++)
            values[i] = byte.Parse(hexValue.Substring(i * 2, 2), System.Globalization.NumberStyles.HexNumber);

        return values;
    }   // HexStringToByteArray()


    /// <summary>
    /// Method to convert a byte array to a hexadecimal string.
    /// </summary>
    /// <param name="values">Byte array.</param>
    /// <returns>A hexadecimal string.</returns>
    /// <exception cref="System.ArgumentNullException">Thrown when argument is null.</exception>
    public static string ByteArrayToHexString(byte[] values)
    {
        ArgumentValidation.CheckNullReference(values, "values");

        StringBuilder hexValue = new StringBuilder();

        foreach (byte value in values)
        {
            hexValue.Append(value.ToString("X2"));
        }

        return hexValue.ToString();
    }   // ByteArrayToHexString()

    public static byte[] GetStringToBytes(string value)
    {
        SoapHexBinary shb = SoapHexBinary.Parse(value);
        return shb.Value;
    }

    public static string GetBytesToString(byte[] value)
    {
        SoapHexBinary shb = new SoapHexBinary(value);
        return shb.ToString();
    } 

.NET 側から ANSIX923 パディング モードを使用している場合、PL/SQL コードは次のようになります。最後の 2 バイトを読み取って、パディングされたバイト数を特定し、それらを文字列から削除して、オリジナル弦。

create or replace FUNCTION DecryptPassword(EncryptedText IN VARCHAR2,EncKey IN VARCHAR2) RETURN VARCHAR2
IS
encdata RAW(2000);
numpad NUMBER;
result VARCHAR2(100);
BEGIN
  encdata:=dbms_obfuscation_toolkit.DES3Decrypt(input=&amp;gt;hextoraw(EncryptedText),key=&amp;gt;UTL_RAW.CAST_TO_RAW(EncKey));

  result :=rawtohex(encdata);
  numpad:=substr(result,length(result)-1);
  result:= substr(result,1,length(result)-(numpad*2));
  result := hextoraw(result);
  result := utl_raw.cast_to_varchar2(result);
  return result;

END DecryptPassword;
于 2012-11-16T11:29:55.860 に答える
1

MSDNのドキュメントによると、OracleコードがPKCS5を使用しているように見えますが、C#コードはPKCS7のデフォルトのパディングを使用しています。それはおそらく始めるのに良い場所でしょう。その間、ブロックチェーンモードも明示的に設定する必要があります。

編集:申し訳ありませんが、PKCS5とPKCS7は、同じ長さの同じバイトで平文を埋める必要があります。それではないかもしれません。エンコーディングの問題を排除するためにプレーンテキストのrawバイトを試してみるというVincentMalgratの提案は、開始するのに適した場所のように思えます。C#コードは、文字列をUnicodeとして扱います。Oracleでは、データベースのエンコーディングが設定されているものは何でも使用すると思います。

于 2012-10-02T16:01:41.293 に答える
0

問題は、使用したキーのパディングにある可能性があります。別のキー/別のパディングで確認してください

于 2012-10-02T15:53:59.407 に答える