3DES加密-java.security.InvalidKeyException:无效的密钥长度:16个字节

时间:2019-05-14 20:27:22

标签: java oracle algorithm 3des

我使用3DES算法同时使用java代码和oracle数据库对String进行加密,oracle数据库的结果正确无误,需要java代码生成相同的oracle数据库结果,但是java代码抛出异常(java.security.InvalidKeyException:无效的密钥长度:16个字节)

--------------------- Oracle script-----------------------
SET SERVEROUTPUT ON;

declare
l_mod_ofb pls_integer;  
 l_mod_ecb pls_integer;
  v_key raw(32);   
  v_iv  raw(16);
  v_test_in raw(16);   v_ciphertext raw(16);

begin
  l_mod_ecb := dbms_crypto.ENCRYPT_3DES_2KEY + dbms_crypto.CHAIN_CBC  + DBMS_CRYPTO.PAD_NONE ;
  v_key      :=   hextoraw  ('1FB3F48A6D51832CE91C1C734554086D');
  v_iv       :=   hextoraw  ('041234FFFFFFFFFF');                
  v_test_in  :=   hextoraw  ('0000211111111110');                

  v_ciphertext := dbms_crypto.encrypt(src => v_test_in,
                                      TYP => l_mod_ecb,
                                      key => v_key,
                                      iv => v_iv);

  dbms_output.put_line(' Ciphertext  : '||rawtohex(v_ciphertext));

end;

脚本输出结果:63CA0F38548CC8B5

以下Java,3DES加密算法代码:

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import org.apache.commons.codec.DecoderException;
import org.apache.commons.codec.binary.Hex;

public class TripleDes {

    private static String SHARED_KEY = "1FB3F48A6D51832CE91C1C734554086D";
    private static String ivString = "041234FFFFFFFFFF";
    private static String valueStr = "0000211111111110";
    static final String HEXES = "041217DB6AEFF7CF";

    public static void main(String[] args) throws DecoderException, Exception {

        TripleDes tr = new TripleDes();
        byte[] plain = Hex.decodeHex(valueStr.toCharArray());
        byte[] codedtext = tr.encrypt(plain);
        System.out.println("Encrypted Result = " + getHex(codedtext));

    }

    public byte[] encrypt(byte[] plainTextBytes) throws Exception {

        byte[] keyValue = Hex.decodeHex(SHARED_KEY.toCharArray());

        IvParameterSpec iv = new IvParameterSpec(ivString.getBytes());
        //DESede
        final SecretKey key = new SecretKeySpec(keyValue, "DESede");
        final Cipher cipher = Cipher.getInstance("DESede/CBC/NoPadding");
        cipher.init(Cipher.ENCRYPT_MODE, key, iv);
        final byte[] cipherText = cipher.doFinal(plainTextBytes);
        return cipherText;
    }

    public static String getHex(byte[] raw) {
        if (raw == null) {
            return null;
        }
        final StringBuilder hex = new StringBuilder(2 * raw.length);
        for (final byte b : raw) {
            hex.append(HEXES.charAt((b & 0xF0) >> 4))
                    .append(HEXES.charAt((b & 0x0F)));
        }
        return hex.toString();
    }

}
  • Java代码异常为(java.security.InvalidKeyException:无效的密钥长度:16个字节)

0 个答案:

没有答案