one way encryption oracle - oracle

is there a way to do one way encryption for password in oracle? i'm passing in password from a textfield and would like to call a stored procedure in oralce and inside that stored procedure, it would encrypt the password. Thank you

Encryption is, by definition, two-way. You would never encrypt a password. I expect that you really want to hash the password. And you wouldn't want to just hash the password, you'd really want to combine the password with some sort of random salt and hash that.
You'd use the dbms_crypto.hash function to compute the hash and the dbms_random.string function to generate the salt. Something like
DECLARE
l_salt varchar2(50);
l_user varchar2(50);
l_pwd varchar2(50);
l_string_to_hash varchar2(150);
l_hash raw(150);
BEGIN
l_salt := dbms_random.string( 'P', 50 );
l_string_to_hash := l_user || l_pwd || l_salt;
l_hash := dbms_crypto.hash( utl_i18n.string_to_raw( l_string_to_hash, 'AL32UTF8' ),
dbms_crypto.hash_sh1 );
END;
See also this askTom discussion (which starts off using the older dbms_obfuscation_toolkit package rather than the dbms_crypto package) for more background on why you'd use a hash, the benefits of salting the password, etc.

Related

Automaticaly creating users in Oracle Apex based on table values

Is there a way to automatically create a user in my application based on values in a table?
So I have a table named EMP as employee in that table I have attributes name, surname, username and password. What do I need to do to automatically create a user account in my application when a new employee is inserted into the database?
I have no idea where to start, is that done in processes or is there a pre-built feature that covers this?
Is there a sample code that everyone just uses and adapts to their needs?
In such a case, maybe it would be better to use custom authentication scheme instead of default, built-in Apex authentication.
How to create new users? Just insert them into the table. It would be a good idea to create a package which contains procedures used to manipulate with users' data.
You shouldn't store passwords as text for security reasons.
For example:
procedure p_create_user (p_name in varchar2, p_surname in varchar2,
p_username in varchar2, p_password in varchar2)
is
l_hash raw (2000);
begin
l_hash :=
dbms_crypto.hash (
utl_i18n.string_to_raw (p_password, 'AL32UTF8'),
dbms_crypto.hash_sh1);
insert into emp (name, surname, username, password)
values
(p_name, p_surname, p_username, l_hash);
end;
In Apex, authentication scheme requires you to create your own function (and set its name into the "Authentication Function Name" property) which accepts username/password combination and returns Boolean: TRUE (if credentials are valid) or FALSE (if not). Note that parameters' names MUST be p_username and p_password.
Use code similar to that in previous procedure:
function f_auth (p_username in varchar2, p_password in varchar2)
return boolean
is
l_pwd emp.password%type;
begin
select password
into l_pwd
from emp
where username = p_username;
return l_pwd = dbms_crypto.hash (
utl_i18n.string_to_raw (p_password, 'AL32UTF8'),
dbms_crypto.hash_sh1);
end;
That's all you need for basic functionality. You can add another procedure to let users change their password etc.

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

How to use PBKDF2 in Oracle 12c?

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 to use PBKDF2 in Oracle 12c?
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.
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.

Execute a stored procedure in oracle

I need to get the output in uu in accordance with value passed through the prompt
create or replace procedure chklg( uu out logn.username%TYPE
, pass in logn.password%TYPE)
is
begin
select username into uu from logn where password=pass;
end;
I tried executing the above procedure this way:
begin
chklg(:pass);
end
By definition a procedure doesn't return anything. You're looking for a function.
create or replace function chklg ( p_pass in logn.password%TYPE
) return varchar2 is -- assuming that logn.username%TYP is a varchar2
l_uu logn.username%type;
begin
select username into l_uu from logn where password = p_pass;
return l_uu;
-- If there-s no username that matches the password return null.
exception when no_data_found then
return null;
end;
I'm slightly worried by this as it appears as though you're storing a password as plain text. This is not best practice.
You should be storing a salted and peppered hash of your password next to the username, then apply the same salting, peppering and hashing to the password and select the hash from the database.
You can execute the function either of the following two ways:
select chklg(:pass) from dual
or
declare
l_pass logn.password%type;
begin
l_pass := chklg(:pass);
end;
/
To be complete Frank Schmitt has raised a very valid point in the comments. In addition to you storing the passwords in a very dangerous manner what happens if two users have the same password?
You will get a TOO_MANY_ROWS exception raised in your SELECT INTO .... This means that too many rows are returned to the variable. It would be better if you passed the username in as well.
This could make your function look something like the following
create or replace function chklg (
p_password_hash in logn.password%type
, p_username in logn.username%type
) return number
/* Authenticate a user, return 1/0 depending on whether they have
entered the correct password.
*/
l_yes number := 0;
begin
-- Assumes that username is unique.
select 1 into l_yes
from logn
where password_hash = p_password_hash
and username = p_username;
return l_yes;
-- If there-s no username that matches the password return 0.
exception when no_data_found then
return 0;
end;
If you're looking to only use a procedure (there's no real reason to do this at all as it unnecessarily restricts you; you're not doing any DML) then you can get the output parameter but you have to give the procedure a parameter that it can populate.
In your case it would look something like this.
declare
l_uu logn.username%type;
begin
chklg(l_uu, :pass);
dbms_output.put_line(l_uu);
end;

Making a sha1-hash of a row in Oracle

I'm having a problem with making a sha1-hash of a row in a select on an Oracle database. I've done it in MSSQL as follows:
SELECT *,HASHBYTES('SHA1',CAST(ID as varchar(10)+
TextEntry1+TextEntry2+CAST(Timestamp as varchar(10)) as Hash
FROM dbo.ExampleTable
WHERE ID = [foo]
However, I can't seem to find a similar function to use when working with Oracle.
As far as my googling has brought me, I'm guessing dbms_crypto.hash_sh1 has something to do with it, but I haven't been able to wrap my brain around it yet...
Any pointers would be greatly appreciated.
The package DBMS_CRYPTO is the correct package to generate hashes. It is not granted to PUBLIC by default, you will have to grant it specifically (GRANT EXECUTE ON SYS.DBMS_CRYPTO TO user1).
The result of this function is of datatype RAW. You can store it in a RAW column or convert it to VARCHAR2 using the RAWTOHEX or UTL_ENCODE.BASE64_ENCODE functions.
The HASH function is overloaded to accept three datatypes as input: RAW, CLOB and BLOB. Due to the rules of implicit conversion, if you use a VARCHAR2 as input, Oracle will try to convert it to RAW and will most likely fail since this conversion only works with hexadecimal strings.
If you use VARCHAR2 then, you need to convert the input to a binary datatype or a CLOB, for instance :
DECLARE
x RAW(20);
BEGIN
SELECT sys.dbms_crypto.hash(utl_raw.cast_to_raw(col1||col2||to_char(col3)),
sys.dbms_crypto.hash_sh1)
INTO x
FROM t;
END;
you will find additional information in the documentation of DBMS_CRYPTO.hash
The DBMS_crypto package does not support varchar2. It works with raw type so if you need a varchar2 you have to convert it. Here is a sample function showing how to do this :
declare
p_string varchar2(2000) := 'Hello world !';
lv_hash_value_md5 raw (100);
lv_hash_value_sh1 raw (100);
lv_varchar_key_md5 varchar2 (32);
lv_varchar_key_sh1 varchar2 (40);
begin
lv_hash_value_md5 :=
dbms_crypto.hash (src => utl_raw.cast_to_raw (p_string),
typ => dbms_crypto.hash_md5);
-- convert into varchar2
select lower (to_char (rawtohex (lv_hash_value_md5)))
into lv_varchar_key_md5
from dual;
lv_hash_value_sh1 :=
dbms_crypto.hash (src => utl_raw.cast_to_raw (p_string),
typ => dbms_crypto.hash_sh1);
-- convert into varchar2
select lower (to_char (rawtohex (lv_hash_value_sh1)))
into lv_varchar_key_sh1
from dual;
--
dbms_output.put_line('String to encrypt : '||p_string);
dbms_output.put_line('MD5 encryption : '||lv_varchar_key_md5);
dbms_output.put_line('SHA1 encryption : '||lv_varchar_key_sh1);
end;
Just to put it here, if someone will search for.
In Oracle 12 you can use standard_hash(<your_value>, <algorythm>) function.
With no parameter <algorythm> defined, it will generate SHA-1 hash (output datatype raw(20))
You can define this function in your favorite package, I defined in utils_pkg.
FUNCTION SHA1(STRING_TO_ENCRIPT VARCHAR2) RETURN VARCHAR2 AS
BEGIN
RETURN LOWER(TO_CHAR(RAWTOHEX(SYS.DBMS_CRYPTO.HASH(UTL_RAW.CAST_TO_RAW(STRING_TO_ENCRIPT), SYS.DBMS_CRYPTO.HASH_SH1))));
END SHA1;
Now to call it
SELECT UTILS_PKG.SHA1('My Text') AS SHA1 FROM DUAL;
The response is
SHA1
--------------------------------------------
5411d08baddc1ad09fa3329f9920814c33ea10c0
You can select a column from some table:
SELECT UTILS_PKG.SHA1(myTextColumn) FROM myTable;
Enjoy!
Oracle 19c:
select LOWER(standard_hash('1234')) from dual;
which is equivalent to
select LOWER(standard_hash('1234','SHA1')) from dual;
will return an SHA1 hash.
For alternative algorithms see: https://docs.oracle.com/en/database/oracle/oracle-database/19/sqlrf/STANDARD_HASH.html

Resources