2016-04-27 160 views
0

使用java AES/CBC/PKCS7Padding进行加密时出现问题。我已经搜索并遵循通过使用BouncyCastle供应商。但我仍然无法得到正确的加密使用AES/CBC/PKCS7Padding进行JAVA加密

咱们说的要求是:

加密类型:对称
算法:AES
块大小= 128位(16个字节)
加密模式:CBC
填充模式:PKCS7
加密密钥长度:256位(32个字节)
向量初始化长度(IV):128位(16个字节)

样本:

纯文本数据= ABC123
加密数据(base64编码)= CtGtW4hJfXxilSfNR1xmrg ==

和我的代码是...

public final class StringFunc { 
    final static String key = "jb2a19ou79rws6zknjlr803fvfgiyp1k"; 
    final static String algorithm = "AES/CBC/PKCS7Padding"; 
    final static String iv = "hod74ty97wr97g83"; 
    private static Cipher cipher = null; 
    private static SecretKeySpec skeySpec = null; 
    private static IvParameterSpec ivSpec = null; 

    private static void setUp(){ 
     try{ 
      Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider()); 
      skeySpec = new SecretKeySpec(key.getBytes(), "AES"); 
      ivSpec = new IvParameterSpec(iv.getBytes()); 
      cipher = Cipher.getInstance(algorithm); 
     }catch(NoSuchAlgorithmException | NoSuchPaddingException ex){ 
     } 
    } 

    public static String encrypt(String str){ 
     try{ 
      Integer strL = (int) Math.ceil(str.length()/8.0); 
      Integer strB = strL*8; 
      str = padRight(str, '', strB); 
      setUp(); 
      try { 
       cipher.init(Cipher.ENCRYPT_MODE, skeySpec, ivSpec); 
      } catch (InvalidAlgorithmParameterException ex) { 
       return ""; 
      } 
      byte[] enc = cipher.doFinal(str.getBytes()); 
      return new String(Base64.encodeBase64(enc)); 
     }catch(InvalidKeyException | IllegalBlockSizeException | BadPaddingException ex){ 
      return "";    
     } 
    } 

    public static String padRight(String msg, char x, int l) { 
     String result = ""; 
     if (!msg.isEmpty()) { 
      for (int i=0; i<(l-msg.length()); i++) { 
       result = result + x; 
      } 
      result = msg + result; 
     } 
     return result; 
    } 
} 

我仍然无法得到正确的加密。任何人都可以提供帮助或给出建议?

+0

什么问题? –

+0

我测试了你的代码,我有个例外。你测试了你的代码?没有例外 ? –

+0

的问题,我只是不能得到正确的结果,就像给我的例子。由于原因,代码已经被删除,因此您不能仅仅复制粘贴来运行它。 – lendir

回答

0

从给定输入猜测,您应该遇到密钥长度的Java限制: 由于美国不允许使用硬安全密钥,因此Java被限制为每个默认密钥长度为128位。

要启用键>你必须改变你的Java版本与官方“无限”的政策(here for SE8

替换已LIB当前策略的策略的128bit /与下载安全应该是足够的。

+0

我会研究它先生,谢谢,我会尽快更新进度。 – lendir

相关问题