简体   繁体   中英

How to encrypt nvarchar column in oracle?

I have a table containing nvarchar datatype columns (contains text in different languages). I want to encrypt data before inserting into table and decrypt the same while fetching records.

Please suggest how i can achieve this.

Encryption and decryption should be done through a private key.

Hoping, my question is clear. Please confirm if i need to provide more information.

Note that it is probably wiser to crypt and decrypt your data directly in your application rather than in the database.

You can use Oracle's DBMS_CRYPTO package. There is an example in the middle of the documentation page.

First you need to make a package to access the cipher type from SQL expression. Let's say you want AES256 in CBC mode with padding:

CREATE PACKAGE pkg_so_42979606
AS
    FUNCTION cipher_type RETURN PLS_INTEGER;
END pkg_so_42979606;
/
CREATE PACKAGE BODY pkg_so_42979606
AS
    ctype CONSTANT PLS_INTEGER := DBMS_CRYPTO.ENCRYPT_AES256
                                  + DBMS_CRYPTO.CHAIN_CBC
                                  + DBMS_CRYPTO.PAD_PKCS5;
    FUNCTION cipher_type RETURN PLS_INTEGER
    IS
    BEGIN
        RETURN ctype;
    END;
END pkg_so_42979606;
/

Then you will need a key. You can ask Oracle to generate one. To easily handle it I'll move it in Base64. Let's draw one:

DECLARE
    key_bytes_raw RAW(32);
    key_char NVARCHAR2(64);
BEGIN
    key_bytes_raw := DBMS_CRYPTO.RANDOMBYTES(32);
    key_char := UTL_I18N.RAW_TO_CHAR(UTL_ENCODE.BASE64_ENCODE(key_bytes_raw), 'AL32UTF8');
    DBMS_OUTPUT.PUT_LINE('Key: ' || key_char);
END;
/
Key: pMV3D4xhyfNxp3YyfLWzAErGcKkIjK3X6uc/WIeVTls=

Thus the cipher key I'll use is pMV3D4xhyfNxp3YyfLWzAErGcKkIjK3X6uc/WIeVTls= .

Now I'll use a test table

CREATE TABLE so_42979606 (
    id NUMBER PRIMARY KEY,
    data NVARCHAR2(2000));

You can insert encrypted data:

INSERT INTO so_42979606
    VALUES (1,
            DBMS_CRYPTO.ENCRYPT(UTL_I18N.STRING_TO_RAW('My clear data', 'AL32UTF8'),
                                pkg_so_42979606.cipher_type(),
                                UTL_ENCODE.BASE64_DECODE(UTL_I18N.STRING_TO_RAW('pMV3D4xhyfNxp3YyfLWzAErGcKkIjK3X6uc/WIeVTls=', 'AL32UTF8'))));

And retrieve the encrypted data in clear.

SELECT id, UTL_I18N.RAW_TO_NCHAR(DBMS_CRYPTO.DECRYPT(data,
                                    pkg_so_42979606.cipher_type(),
                                    UTL_ENCODE.BASE64_DECODE(UTL_I18N.STRING_TO_RAW('pMV3D4xhyfNxp3YyfLWzAErGcKkIjK3X6uc/WIeVTls=', 'AL32UTF8'))),
                                 'AL32UTF8') data
    FROM so_42979606;

ID DATA
-- ----------------------
 1 My clear data

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM