如何解决AES-256 ||中的非法密钥大小或默认参数已安装JCE文件

时间:2017-11-15 08:04:52

标签: java encryption cryptography

我正在尝试编写一个代码,它将进行AES 256加密和解密。我已经在Jre / lib下的安全文件夹中安装了JCE jar。但后来我也得到了非法的密钥大小或默认参数,我已经尝试了所有的解决方案,但我不能使它工作。请原谅我,如果这个问题是一个愚蠢的,我是这个密码学的新手。

我正在给我的代码

这是我的密码

public  Cipher getCipher(int mode) throws Exception {

      Cipher c = Cipher.getInstance("AES/CBC/PKCS5Padding", new SunJCE());
      //a random Init. Vector. just for testing
      byte[] iv = listOfDecodedkeys.get(0).getBytes(AbstractSecurity.UTF_ENCODING);
      c.init(mode, generateKey(), new IvParameterSpec(iv));
      return c;
  }

这是密钥生成方法

 private   Key generateKey() throws Exception {
      //PBKDF2WithHmacSHA256
      //SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
      SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA512");
      char[] password = listOfDecodedkeys.get(1).toCharArray();
      byte[] salt = listOfDecodedkeys.get(2).getBytes(AbstractSecurity.UTF_ENCODING);
      KeySpec spec = new PBEKeySpec(password, salt, 65536, 256);
      SecretKey tmp = factory.generateSecret(spec);
      byte[] encoded = tmp.getEncoded();
      return new SecretKeySpec(encoded, "AES");

  }

这是我的加密器

@Override
public String encrypt(String strToDecrypt) throws Exception{
    Cipher c = getCipher(Cipher.ENCRYPT_MODE);
    byte[] encryptedVal = c.doFinal(strToDecrypt.getBytes(AbstractSecurity.UTF_ENCODING));
    return new sun.misc.BASE64Encoder().encode(encryptedVal);
}

这是我的解密者

 public  String decrypt(String encrypted) throws Exception {
      Cipher c = super.getCipher(Cipher.DECRYPT_MODE);
      byte[] decodedValue = new sun.misc.BASE64Decoder().decodeBuffer(encrypted);
      byte[] decValue = c.doFinal(decodedValue);
      return new String(decValue);
  }

现在我正处于异常

之下
Exception in thread "main" java.security.NoSuchAlgorithmException: PBKDF2WithHmacSHA512 SecretKeyFactory not available
at javax.crypto.SecretKeyFactory.<init>(Unknown Source)
at javax.crypto.SecretKeyFactory.getInstance(Unknown Source)
at com.aes.security.AbstractSecurity.generateKey(AbstractSecurity.java:198)
at com.aes.security.AbstractSecurity.getCipher(AbstractSecurity.java:187)
at com.aes.security.SecurityService.encrypt(SecurityService.java:76)
at com.aes.security.SecurityService.main(SecurityService.java:165)

如果我将SecretKeyFactory更改为PBKDF2WithHmacSHA1我正在

Exception in thread "main" java.security.InvalidKeyException: Illegal key size
at javax.crypto.Cipher.a(Unknown Source)
at javax.crypto.Cipher.init(Unknown Source)
at javax.crypto.Cipher.init(Unknown Source)
at com.aes.security.AbstractSecurity.getCipher(AbstractSecurity.java:184)
at com.aes.security.SecurityService.encrypt(SecurityService.java:76)
at com.aes.security.SecurityService.main(SecurityService.java:165)

如何解决这个问题

0 个答案:

没有答案