Skip to Main Content

SQL & PL/SQL

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

How to encrypt in AES256 + CBC + PKCS7

680983Feb 14 2012 — edited Feb 16 2012
Hi,

I'm using Oracle Database 10.2 on Windows 2003.

I need to encrypt string before transmitting it. Encryption should be AES256 with Cipher mode CBC and Padding mode PKCS7. I have given a 64 character long string to use it as key.

I went to http://docs.oracle.com/cd/B19306_01/appdev.102/b14258/d_crypto.htm and tried the example given there
declare
   input_string       VARCHAR2 (200) := 'testing1234567890|20120214-12:00:00:001';
   output_string      VARCHAR2 (200);
   encrypted_raw      RAW (2000);             -- stores encrypted binary text
   decrypted_raw      RAW (2000);             -- stores decrypted binary text
   key_bytes_raw      RAW (32);               -- stores 256-bit encryption key 
   encryption_type    PLS_INTEGER;            -- total encryption type
begin

   DBMS_OUTPUT.PUT_LINE ('Original string: ' || input_string);
   encryption_type :=   DBMS_CRYPTO.ENCRYPT_AES256 + DBMS_CRYPTO.CHAIN_CBC + DBMS_CRYPTO.PAD_PKCS5;
   key_bytes_raw := UTL_I18N.STRING_TO_RAW('bc82bb2613bdf3ac4d093ea4fec8cf76f49af2175f397f0466a363948eeaf6fd', 'AL32UTF8');
   encrypted_raw := DBMS_CRYPTO.ENCRYPT
      (
         src => UTL_I18N.STRING_TO_RAW (input_string, 'AL32UTF8'),
         typ => encryption_type,
         key => key_bytes_raw
      );
    -- The encrypted value in the encrypted_raw variable can be used here
   DBMS_OUTPUT.PUT_LINE(encrypted_raw);
   DBMS_OUTPUT.PUT_LINE(UTL_ENCODE.base64_encode(encrypted_raw));
   decrypted_raw := DBMS_CRYPTO.DECRYPT
      (
         src => encrypted_raw,
         typ => encryption_type,
         key => key_bytes_raw
      );
   output_string := UTL_I18N.RAW_TO_CHAR (decrypted_raw, 'AL32UTF8');
   DBMS_OUTPUT.PUT_LINE ('Decrypted string: ' || output_string);
   
end;
This code was giving me ORA-06502: PL/SQL: numeric or value error: raw variable length too long. Then I changed the length as
   key_bytes_raw      RAW (64);               -- stores 256-bit encryption key 
I got ORA-28234: key length too short. I also noticed that DBMS_CRYPTO does not have PKCS7 padding.

Please let me know how to use 64 character long key given to me with PKCS7 padding in PL/SQL.

Thanks
-Smith
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Mar 15 2012
Added on Feb 14 2012
2 comments
2,107 views