KeyGenerator异常

时间:2018-04-14 01:31:35

标签: java key-generator

我试图实现IDEA算法。这是我在谷歌上找到的代码:

package ideaalgoritam;

import java.security.SecureRandom;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;

public class IDEAalgoritam {

   public static void main(String []args) throws Exception {
      String toEncrypt = "The shorter you live, the longer you're dead!";

      System.out.println("Encrypting...");
      byte[] encrypted = encrypt(toEncrypt, "password");

      System.out.println("Decrypting...");
      String decrypted = decrypt(encrypted, "password");

      System.out.println("Decrypted text: " + decrypted);
   }

   public static byte[] encrypt(String toEncrypt, String key) throws Exception {
      // create a binary key from the argument key (seed)
      SecureRandom sr = new SecureRandom(key.getBytes());
      KeyGenerator kg = KeyGenerator.getInstance("IDEA");
      kg.init(sr);
      SecretKey sk = kg.generateKey();

      // create an instance of cipher
      Cipher cipher = Cipher.getInstance("IDEA");

      // initialize the cipher with the key
      cipher.init(Cipher.ENCRYPT_MODE, sk);

      // enctypt!
      byte[] encrypted = cipher.doFinal(toEncrypt.getBytes());

      return encrypted;
   }

   public static String decrypt(byte[] toDecrypt, String key) throws Exception {
      // create a binary key from the argument key (seed)
      SecureRandom sr = new SecureRandom(key.getBytes());
      KeyGenerator kg = KeyGenerator.getInstance("IDEA");
      kg.init(sr);
      SecretKey sk = kg.generateKey();

      // do the decryption with that key
      Cipher cipher = Cipher.getInstance("IDEA");
      cipher.init(Cipher.DECRYPT_MODE, sk);
      byte[] decrypted = cipher.doFinal(toDecrypt);

      return new String(decrypted);
   }

}

但是当我运行代码时,我得到了这个例外:

Exception in thread "main" java.security.NoSuchAlgorithmException: IDEA KeyGenerator not available
    at javax.crypto.KeyGenerator.<init>(KeyGenerator.java:169)
    at javax.crypto.KeyGenerator.getInstance(KeyGenerator.java:223)
    at ideaalgoritam.IDEAalgoritam.encrypt(IDEAalgoritam.java:27)
    at ideaalgoritam.IDEAalgoritam.main(IDEAalgoritam.java:16)

在jdk和jre security lib文件夹中,我添加了安全提供程序bouncy castle http://prntscr.com/j516zx。但我仍然得到这个例外。 有谁知道我怎么能解决这个问题,以便我可以运行此代码?

0 个答案:

没有答案