How to use PBKDF2 in Oracle 12c?

后端 未结 2 1749
北荒
北荒 2021-02-06 16:37

We want to save user passwords in Oracle 12c. I found the dbms_crypto-Package but there was no information about PBKDF2.

What\'s the current state in 2017 t

相关标签:
2条回答
  • 2021-02-06 17:18

    This is a late answer, but to the best of my knowledge Oracle's DBMS_CRYPTO package does not support PBKDF2 natively. That said, you can implement the algorithm yourself; here is one way to do it:

    CREATE OR REPLACE FUNCTION pbkdf2
      ( p_password IN VARCHAR2
      , p_salt IN VARCHAR2
      , p_count IN INTEGER
      , p_key_length IN INTEGER )
    RETURN VARCHAR2
    IS
        l_block_count INTEGER;
        l_last RAW(32767);
        l_xorsum RAW(32767);
        l_result RAW(32767);
    BEGIN
        l_block_count := CEIL(p_key_length / 20);  -- use 20 bytes for SHA1, 32 for SHA256, 64 for SHA512
    
        FOR i IN 1..l_block_count LOOP
            l_last := UTL_RAW.CONCAT(UTL_RAW.CAST_TO_RAW(p_salt), UTL_RAW.CAST_FROM_BINARY_INTEGER(i, UTL_RAW.BIG_ENDIAN));
            l_xorsum := NULL;
    
            FOR j IN 1..p_count LOOP
                l_last := DBMS_CRYPTO.MAC(l_last, DBMS_CRYPTO.HMAC_SH1, UTL_RAW.CAST_TO_RAW(p_password));
                -- use HMAC_SH256 for SHA256, HMAC_SH512 for SHA512
    
                IF l_xorsum IS NULL THEN
                    l_xorsum := l_last;
                ELSE
                    l_xorsum := UTL_RAW.BIT_XOR(l_xorsum, l_last);
                END IF;
            END LOOP;
    
            l_result := UTL_RAW.CONCAT(l_result, l_xorsum);
        END LOOP;
    
        RETURN RAWTOHEX(UTL_RAW.SUBSTR(l_result, 1, p_key_length));
    END pbkdf2;
    /
    

    This code was originally found here: PBKDF2 in Oracle; I've confirmed that it works on my own system in SHA-1, SHA-256, and SHA-512. Note that p_count is the number of iterations and p_key_length is the length of the key. See this question for more information on the recommended number of iterations and recommended key length for PBKDF2.

    Hope this helps.

    0 讨论(0)
  • 2021-02-06 17:28

    Your application server should be doing the PBKDF2 before it gets to the database - don't spend your precious, limited Oracle resources on that.

    And don't let your DBA's see the passwords in plaintext, either, as they'd have to if Oracle is the one doing the hashing!

    I have a variety of PBKDF2 examples in My github repository, including test vectors and, if you absolutely insist on doing it in Oracle, one pure SQL Server implementation that shouldn't be difficult to convert to PL/SQL.

    0 讨论(0)
提交回复
热议问题