以下 摘自IBM开发者论坛的PublicExample.java程序,在没有安装成功Bouncy Castle提供者时运行提示错误如下:
Exception in thread "main" java.security.NoSuchAlgorithmException: Cannot find any provider supporting RSA/ECB/PKCS1Padding
at javax.crypto.Cipher.getInstance(DashoA6275)
at PublicExample.main(PublicExample.java:24)
而在安装成功后就可以完好的执行。执行结果如下:
E:\security>java PublicExample "This is a test,这是一个测试!this is a test!"
Start generating RSA key
Finish generating RSA key
BouncyCastle Security Provider v1.19
Start encryption
Finish encryption:
This is a test,这是一个测试!this is a test!
源代码如下:
import java.security.*;
import javax.crypto.*;
//
// Public Key cryptography using the RSA algorithm.
public class PublicExample {
public static void main (String[] args) throws Exception {
//
// check args and get plaintext
if (args.length !=1) {
System.err.println("Usage: java PublicExample text");
System.exit(1);
}
byte[] plainText = args[0].getBytes("UTF8");
//
// generate an RSA key
System.out.println( "\nStart generating RSA key" );
KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
keyGen.initialize(1024);
KeyPair key = keyGen.generateKeyPair();
System.out.println( "Finish generating RSA key" );
//
// get an RSA cipher object and print the provider
Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
System.out.println( "\n" + cipher.getProvider().getInfo() );
//
// encrypt the plaintext using the public key
System.out.println( "\nStart encryption" );
cipher.init(Cipher.ENCRYPT_MODE, key.getPublic());
byte[] cipherText = cipher.doFinal(plainText);
System.out.println( "Finish encryption: " );
System.out.println( new String(cipherText, "UTF8") );
//
// decrypt the ciphertext using the private key
System.out.println( "\nStart decryption" );
cipher.init(Cipher.DECRYPT_MODE, key.getPrivate());
byte[] newPlainText = cipher.doFinal(cipherText);
System.out.println( "Finish decryption: " );
System.out.println( new String(newPlainText, "UTF8") );
}
}