java加密KeyGenerator

时间:2012-10-16 11:46:45

标签: java security cryptography encryption

我的代码是

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()));
   }
}

在上面的代码中,fire异常是: - 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)

我该怎么做? 提前致谢

2 个答案:

答案 0 :(得分:1)

在第

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

BC表示BouncyCastle?你为什么评论Security.addProvider( new BouncyCastleProvider() )?您需要在Java安全policy文件中添加该提供程序。

查看getInstance JavaDoc - 在未配置提供程序时完全抛出NoSuchProviderException。您是否在没有提供者参数的情况下尝试了getInstance(...)方法?

干杯,

答案 1 :(得分: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");

我认为这很好。