采用Oracle的dbms_obfuscation_toolkit的加密和解密详解

lookFuture 2010-01-04

前一两天研究了一下Oracle的加密算法,结合自己的实践经历和 Oracle9i Supplied PL/SQL Packages and Types Reference. 加密(encrypt)解密(decrypt)是采用 Oracle DBMS_OBFUSCATION_TOOLKIT package.
利用这个包,我们可以对数据进行DES,Triple DES或者MD5加密.
DESGETKEY   -- 产生密钥,用于DES算法
   DES3GETKEY  -- 产生密钥,用于Triple DES算法
   DESENCRYPT  -- 用DES算法加密数据
   DESDECRYPT  -- 用DES算法解密数据
   DES3ENCRYPT -- 用Triple DES算法加密数据
   DES3DECRYPT -- 用DES算法解密数据
   MD5         -- 用MD5算法加密数据


Triple DES (3DES) is a far stronger cipher than DES; the resulting ciphertext (encrypted data) is much harder to break using an exhaustive search: 2**112 or 2**168 attempts instead of 2**56 attempts  这是怎么样的一个概念呢? 以现在的计算机计算能力来说吧,
uppose you build a computer capable of making 1000 attempts each second. How long would it take to exhaust 2 to the 56 (256) attempts?   it will go supernova many billions of years before you'll finish.
下面看看对字符串: password 加密的过程:

DECLARE
input_string        VARCHAR2(16) := 'password';
key_string          VARCHAR2(8)  := 'oracle9i';
  
encrypted_string    VARCHAR2(2048);
decrypted_string    VARCHAR2(2048);

error_in_input_buffer_length EXCEPTION;

PRAGMA EXCEPTION_INIT(error_in_input_buffer_length, -28232);
   INPUT_BUFFER_LENGTH_ERR_MSG VARCHAR2(100) :=
    '*** DES INPUT BUFFER NOT A MULTIPLE OF 8 BYTES ***';

BEGIN
   dbms_output.put_line('> ========= BEGIN TEST =========');
   dbms_output.put_line('> Input string                 : ' ||
input_string);
   --BEGIN <-- ignore this, typo in Oracle's documentation
      dbms_obfuscation_toolkit.DESEncrypt(
                   input_string => input_string,
                   key_string => key_string,
                   encrypted_string => encrypted_string );
      dbms_output.put_line('> Encrypted string             : ' ||
                   encrypted_string);
-- Add DESDecrypt as shown, change raw to key_string
      dbms_obfuscation_toolkit.DESDecrypt(
                   input_string => encrypted_string,
                   key_string => key_string,
                   decrypted_string => decrypted_string);
      dbms_output.put_line('> Decrypted output             : ' ||
                   decrypted_string);
      dbms_output.put_line('>  ');     
      if input_string =
                   decrypted_string THEN
         dbms_output.put_line('> DES Encryption and Decryption successful');
      END IF;
EXCEPTION
     
   WHEN error_in_input_buffer_length THEN
      dbms_output.put_line('> ' || INPUT_BUFFER_LENGTH_ERR_MSG);
END;


运行的结果:
> ========= BEGIN TEST =========
> Input string                 : password
> Encrypted string             : .]%.?—I
> Decrypted output             : password

> DES Encryption and Decryption successful


这里的encrypted string不同的sql/plus版本是不同的结果的,因为字符集不同,这里必段要注意:加密的字符串(input_string)必须是8的倍数哦,其实加密后的字符串也是8的倍数,如果不是的话,结果就是:
> ========= BEGIN TEST =========
> Input string                 : passwo1rd
> *** DES INPUT BUFFER NOT A MULTIPLE OF 8 BYTES ***

相关推荐