我想添加一个自我实现的提供程序(java.security.provider)并对其进行测试。我遵循了oracle docs的指示(但?),但我陷入了步骤3:
Exception in thread "main" java.security.NoSuchAlgorithmException: Cannot find any provider supporting MyCipher
at javax.crypto.Cipher.getInstance(Cipher.java:539)
at Test.main(Test.java:16)
这是我的代码:
-MyProvider:
public final class MyProvider extends Provider{
/**
*
*/
private static final long serialVersionUID = 1L;
public MyProvider() {
super("MyProvider", 0.1, "test");
//put("Cipher.MyCipher","MyCipher");
putService(new ProviderService(this, "Cipher", "MyCipher", "p.MyCipher"));
}
private static final class ProviderService extends Provider.Service {
ProviderService(Provider p, String type, String algo, String cn) {
super(p, type, algo, cn, null, null);
}
@Override
public Object newInstance(Object ctrParamObj) throws NoSuchAlgorithmException {
String type = getType();
String algo = getAlgorithm();
try {
if (type.equals("Cipher")) {
if (algo.equals("MyCipher")) {
return new MyCipher();
}
}
} catch (Exception ex) {
throw new NoSuchAlgorithmException(
"Error constructing " + type + " for "
+ algo + " using SunMSCAPI", ex);
}
throw new ProviderException("No impl for " + algo + " " + type);
}
}
}
-MyCipher:
package p;
public class MyCipher extends CipherSpi{
.....//just default functions need to be overrided.
}
-测试:
public class Test {
public static void main (String[] args) throws NoSuchAlgorithmException, NoSuchPaddingException {
Provider mp = new MyProvider();
Security.addProvider(mp);
System.out.println(Security.getProvider("MyProvider").getInfo());
System.out.println(Security.getProvider("MyProvider").getServices().toString());
Cipher c = Cipher.getInstance("MyCipher"); //exception here
}
}
我真的不明白为什么会出现这种异常。我有误会吗?预先非常感谢。