-1

我的代码是

import java.security.Key;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

public class apiKeyGenerate {
  public static void main(String[] args) throws Exception {
   // Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());

    byte[] input = "input".getBytes();
    byte[] ivBytes = "1234567812345678".getBytes();

    Cipher cipher =  Cipher.getInstance("DES/CBC/PKCS5Padding");
    KeyGenerator generator = KeyGenerator.getInstance("AES", "BC");
    generator.init(128);
    Key encryptionKey = generator.generateKey();
    System.out.println("key : " + new String(encryptionKey.getEncoded()));
   }
}

在上面的代码中,火异常是:- java.security.NoSuchProviderException:即

Exception in thread "main" java.security.NoSuchProviderException: no such provider: BC
    at sun.security.jca.GetInstance.getService(Unknown Source)
    at javax.crypto.SunJCE_b.a(DashoA13*..)
    at javax.crypto.KeyGenerator.getInstance(DashoA13*..)
    at apiKeyGenerate.main(apiKeyGenerate.java:17)

我怎样才能做到这一点 ??提前致谢

4

2 回答 2

1

在行

KeyGenerator generator = KeyGenerator.getInstance("AES", "BC");

BC表明BouncyCastle?为什么评论出来了Security.addProvider( new BouncyCastleProvider() )?然后,您需要将该提供程序添加到 Java 安全policy文件中。

看一下getInstance JavaDoc - 在NoSuchProviderException未配置提供程序时准确抛出。您是否尝试过getInstance(...)没有提供者参数的方法?

干杯,

于 2012-10-16T11:58:08.197 回答
0
import java.security.Key;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

public class Test1 {
  public static void main(String[] args) throws Exception {
   // Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());

      byte[] input = "input".getBytes();
        byte[] ivBytes = "1234567812345678".getBytes();

        Cipher cipher =  Cipher.getInstance("DES/CBC/PKCS5Padding");
        **KeyGenerator generator = KeyGenerator.getInstance("AES");**
        generator.init(128);
        Key encryptionKey = generator.generateKey();
        System.out.println("key : " + new String(encryptionKey.getEncoded()));
       }

}

代替

KeyGenerator generator = KeyGenerator.getInstance("AES", "BC");

这条线你可以试试这个

KeyGenerator generator = KeyGenerator.getInstance("AES");

我认为这很好用。

于 2012-10-16T12:04:25.590 回答