How to use PBKDF2 in Oracle 12c?

后端 未结 2 1754
北荒
北荒 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.

提交回复
热议问题