DBMS_CRYPTO, before decrypting is it possible to check if the string is decryptable?

I want to check if a string can be de-crypted using DBMS_CRYPTO, as if we pass stings which can’t be decrypted,the decrypt function throws exception, I used exception to catch it but this makes my system slow. I need to use a normalize function which check and if required decrypts the input.

A code sample with handling exception which throws error if we don’t pass a string that can be decrypted.

OPENSSL decrypt returns a null value if the input string is not decryptable. I am looking something like that but without catching exception.

set serveroutput on ;
set feedback on ;

DECLARE
input_string       VARCHAR2 (200) :=  'AMIT';
output_string      VARCHAR2 (200);
encrypted_raw      RAW (2000);             -- stores encrypted binary text 
decrypted_raw      RAW (2000);             -- stores decrypted binary text
num_key_bytes      NUMBER := 128/8;        -- key length 256 bits (32 bytes)
key_bytes_raw      RAW (2048);               -- stores 256-bit encryption key
iv_bytes_raw      RAW (2048);               -- stores 256-bit encryption key
another_string    VARCHAR2(200) ;
encryption_type    PLS_INTEGER := DBMS_CRYPTO.ENCRYPT_AES128 + DBMS_CRYPTO.CHAIN_CBC + 
DBMS_CRYPTO.PAD_PKCS5;
BEGIN
DBMS_OUTPUT.PUT_LINE ( 'Original string: ' || input_string);
iv_bytes_raw := UTL_I18N.STRING_TO_RAW ( utl_raw.cast_to_varchar2(hextoraw('96ff9997eefd8c2d47c3d1c303f617bc')) ) ;
key_bytes_raw := UTL_I18N.STRING_TO_RAW ( utl_raw.cast_to_varchar2(hextoraw('537b70597e5b2588cbfb91dc8312a4d6')) ) ;
encrypted_raw := DBMS_CRYPTO.ENCRYPT
   (
      src => UTL_I18N.STRING_TO_RAW (input_string,  'AL32UTF8'),
      typ => encryption_type,
      key => key_bytes_raw,
              iv => iv_bytes_raw
   );
 DBMS_OUTPUT.PUT_LINE ( 'Encrypted string: ' || encrypted_raw);
    decrypted_raw := DBMS_CRYPTO.DECRYPT
   (
      src => encrypted_raw,
      typ => encryption_type,
      key => key_bytes_raw,
        iv => iv_bytes_raw
   );
output_string := UTL_I18N.RAW_TO_CHAR (decrypted_raw, 'AL32UTF8');
DBMS_OUTPUT.PUT_LINE ('Decrypted string: ' || output_string);

another_string := 'asdf' ;
begin
decrypted_raw := DBMS_CRYPTO.DECRYPT
(
   src => UTL_I18N.STRING_TO_RAW(another_string, 'AL32UTF8'),
   typ => encryption_type,
   key => key_bytes_raw,
    iv => iv_bytes_raw
);

output_string := UTL_I18N.RAW_TO_CHAR (decrypted_raw, 'AL32UTF8');
DBMS_OUTPUT.PUT_LINE ('Decrypted string: ' || output_string);
 exception 
when OTHERS
    then
    DBMS_OUTPUT.PUT_LINE ('String cannot be decrypted.');
end ;

END;
/


Source: oracle

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.