下面列出了java.security.Provider#Service ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
static SecureRandom getSecureRandom() throws KeyManagementException {
if (cryptoProvider == null) {
return new SecureRandom();
}
// Try "PKCS11" first. If that is not supported, iterate through
// the provider and return the first working implementation.
try {
return SecureRandom.getInstance("PKCS11", cryptoProvider);
} catch (NoSuchAlgorithmException e) {
// ignore
}
for (Provider.Service s : cryptoProvider.getServices()) {
if (s.getType().equals("SecureRandom")) {
try {
return SecureRandom.getInstance(s.getAlgorithm(), cryptoProvider);
} catch (NoSuchAlgorithmException ee) {
// ignore
}
}
}
throw new KeyManagementException("FIPS mode: no SecureRandom "
+ " implementation found in provider " + cryptoProvider.getName());
}
/**
* Determine the classes that make up the provider and its services
*
* @param providerName - JCA provider name
* @return class names that make up the provider and its services
*/
private List<String> registerProvider(String providerName) {
ArrayList<String> providerClasses = new ArrayList<>();
Provider provider = Security.getProvider(providerName);
providerClasses.add(provider.getClass().getName());
Set<Provider.Service> services = provider.getServices();
for (Provider.Service service : services) {
String serviceClass = service.getClassName();
providerClasses.add(serviceClass);
// Need to pull in the key classes
String supportedKeyClasses = service.getAttribute("SupportedKeyClasses");
if (supportedKeyClasses != null) {
String[] keyClasses = supportedKeyClasses.split("\\|");
providerClasses.addAll(Arrays.asList(keyClasses));
}
}
return providerClasses;
}
static SecureRandom getSecureRandom() throws KeyManagementException {
if (cryptoProvider == null) {
return new SecureRandom();
}
// Try "PKCS11" first. If that is not supported, iterate through
// the provider and return the first working implementation.
try {
return SecureRandom.getInstance("PKCS11", cryptoProvider);
} catch (NoSuchAlgorithmException e) {
// ignore
}
for (Provider.Service s : cryptoProvider.getServices()) {
if (s.getType().equals("SecureRandom")) {
try {
return SecureRandom.getInstance(s.getAlgorithm(), cryptoProvider);
} catch (NoSuchAlgorithmException ee) {
// ignore
}
}
}
throw new KeyManagementException("FIPS mode: no SecureRandom "
+ " implementation found in provider " + cryptoProvider.getName());
}
static SecureRandom getSecureRandom() throws KeyManagementException {
if (cryptoProvider == null) {
return new SecureRandom();
}
// Try "PKCS11" first. If that is not supported, iterate through
// the provider and return the first working implementation.
try {
return SecureRandom.getInstance("PKCS11", cryptoProvider);
} catch (NoSuchAlgorithmException e) {
// ignore
}
for (Provider.Service s : cryptoProvider.getServices()) {
if (s.getType().equals("SecureRandom")) {
try {
return SecureRandom.getInstance(s.getAlgorithm(), cryptoProvider);
} catch (NoSuchAlgorithmException ee) {
// ignore
}
}
}
throw new KeyManagementException("FIPS mode: no SecureRandom "
+ " implementation found in provider " + cryptoProvider.getName());
}
public void testNewInstance() throws Exception {
String type = "SecureRandom";
String algorithm = "algorithm";
MyProvider p = new MyProvider();
Provider.Service s = new Provider.Service(p, type,
algorithm,
"org.apache.harmony.security.tests.support.RandomImpl",
null, null);
p.putService(s);
// Check success and correct type.
Object o = s.newInstance(null);
assertTrue("new service instance is of incorrect class " + o.getClass().getName(),
o instanceof RandomImpl);
}
static SecureRandom getSecureRandom() throws KeyManagementException {
if (cryptoProvider == null) {
return new SecureRandom();
}
// Try "PKCS11" first. If that is not supported, iterate through
// the provider and return the first working implementation.
try {
return SecureRandom.getInstance("PKCS11", cryptoProvider);
} catch (NoSuchAlgorithmException e) {
// ignore
}
for (Provider.Service s : cryptoProvider.getServices()) {
if (s.getType().equals("SecureRandom")) {
try {
return SecureRandom.getInstance(s.getAlgorithm(), cryptoProvider);
} catch (NoSuchAlgorithmException ee) {
// ignore
}
}
}
throw new KeyManagementException("FIPS mode: no SecureRandom "
+ " implementation found in provider " + cryptoProvider.getName());
}
static SecureRandom getSecureRandom() throws KeyManagementException {
if (cryptoProvider == null) {
return new SecureRandom();
}
// Try "PKCS11" first. If that is not supported, iterate through
// the provider and return the first working implementation.
try {
return SecureRandom.getInstance("PKCS11", cryptoProvider);
} catch (NoSuchAlgorithmException e) {
// ignore
}
for (Provider.Service s : cryptoProvider.getServices()) {
if (s.getType().equals("SecureRandom")) {
try {
return SecureRandom.getInstance(s.getAlgorithm(), cryptoProvider);
} catch (NoSuchAlgorithmException ee) {
// ignore
}
}
}
throw new KeyManagementException("FIPS mode: no SecureRandom "
+ " implementation found in provider " + cryptoProvider.getName());
}
/**
* Calling setSeed directly after the initialization may result in deterministic
* results.
*
* The test expects that a SecureRandom instance is either completely deterministic if
* seeded or non-deterministic and unpredictable (though the test is much too simple
* to give any meaningful result).
*
* For example the provider "SUN" has the following behaviour:
* <pre>
* Seeding SHA1PRNG from SUN results in deterministic output.
* Seeding NativePRNG from SUN results in non-deterministic output.
* Seeding NativePRNGBlocking from SUN results in non-deterministic output.
* Seeding NativePRNGNonBlocking from SUN results in non-deterministic output.
* </pre>
*
* jdk9 adds a class java.security.DrbgParameter, which allows to better specify the expected
* behaviour of SecureRandom instances. Tests with these parameters are not included here.
*/
@Test
public void testSetSeedAfterConstruction() throws Exception {
final int samples = 10; // the number of samples per SecureRandom.
// The size of the generated pseudorandom bytes. An output size of 8 bytes
// means that the probability of false positives is about
// 2^{-65}*(samples * (#secure random instances))^2.
// Hence a random failure of this function is unlikely.
final int outputsize = 8;
final byte[] seed = new byte[32];
for (Provider.Service service : secureRandomServices()) {
Provider provider = service.getProvider();
Set<String> seen = new TreeSet<String>();
for (int i = 0; i < samples; i++) {
SecureRandom random = SecureRandom.getInstance(service.getAlgorithm(), provider);
random.setSeed(seed);
byte[] bytes = new byte[outputsize];
random.nextBytes(bytes);
String hex = TestUtil.bytesToHex(bytes);
seen.add(hex);
}
if (seen.size() == 1) {
System.out.println("Seeding " + service.getAlgorithm() + " from " + provider.getName()
+ " results in deterministic output.");
} else {
System.out.println("Seeding " + service.getAlgorithm() + " from " + provider.getName()
+ " results in non-deterministic output.");
// ... and if the implementation is non-determinstic, there should be no repetitions.
assertEquals(samples, seen.size());
}
}
}
static ResourceDefinition getProviderHttpServerMechanismFactoryDefinition() {
AttributeDefinition[] attributes = new AttributeDefinition[] { PROVIDERS };
AbstractAddStepHandler add = new TrivialAddHandler<HttpServerAuthenticationMechanismFactory>(HttpServerAuthenticationMechanismFactory.class, attributes, HTTP_SERVER_MECHANISM_FACTORY_RUNTIME_CAPABILITY) {
@Override
protected ValueSupplier<HttpServerAuthenticationMechanismFactory> getValueSupplier(
ServiceBuilder<HttpServerAuthenticationMechanismFactory> serviceBuilder, OperationContext context,
ModelNode model) throws OperationFailedException {
String providers = PROVIDERS.resolveModelAttribute(context, model).asStringOrNull();
final Supplier<Provider[]> providerSupplier;
if (providers != null) {
final InjectedValue<Provider[]> providersInjector = new InjectedValue<Provider[]>();
serviceBuilder.addDependency(context.getCapabilityServiceName(
buildDynamicCapabilityName(PROVIDERS_CAPABILITY, providers), Provider[].class),
Provider[].class, providersInjector);
providerSupplier = providersInjector::getValue;
} else {
providerSupplier = Security::getProviders;
}
Predicate<Provider.Service> serviceFilter = (Provider.Service s) -> HttpServerAuthenticationMechanismFactory.class.getSimpleName().equals(s.getType());
return () -> {
final Provider[] actualProviders = providerSupplier.get();
if ( findProviderService(actualProviders, serviceFilter) == null ) {
throw ROOT_LOGGER.noSuitableProvider(HttpServerAuthenticationMechanismFactory.class.getSimpleName());
}
return new SetMechanismInformationMechanismFactory(new SecurityProviderServerMechanismFactory(actualProviders));
};
}
};
return wrapFactory(new TrivialResourceDefinition(ElytronDescriptionConstants.PROVIDER_HTTP_SERVER_MECHANISM_FACTORY, add,
attributes, HTTP_SERVER_MECHANISM_FACTORY_RUNTIME_CAPABILITY));
}
public static void main(String args[])
{
Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
Provider[] p_a = Security.getProviders();
for(Provider p : p_a)
{
System.out.println("Provider: " + p.toString());
System.out.println("-----------------------------------");
for(Provider.Service ps : p.getServices())
{
System.out.println(" " + ps.toString());
}
}
}
public void testGetProvider() {
Provider p = new MyProvider();
Provider.Service s1 = new Provider.Service(p, "type", "algorithm",
"className", null, null);
assertTrue(s1.getProvider() == p);
Provider.Service s2 = new Provider.Service(p, "SecureRandom",
"algorithm", "tests.java.security.support.RandomImpl", null,
null);
assertTrue(s2.getProvider() == p);
}
public void testGetAttribute() {
Provider p = new MyProvider();
Provider.Service s = new Provider.Service(p, "type", "algorithm",
"className", null, null);
try {
s.getAttribute(null);
fail("No expected NullPointerException");
} catch (NullPointerException e) {
}
if (s.getAttribute("aaa") != null) {
fail("getAttribute(aaa) failed");
}
HashMap<String, String> hm = new HashMap<String, String>();
hm.put("attribute", "value");
hm.put("KeySize", "1024");
hm.put("AAA", "BBB");
s = new Provider.Service(p, "type", "algorithm", "className", null, hm);
if (s.getAttribute("bbb") != null) {
fail("getAttribute(bbb) failed");
}
if (!s.getAttribute("attribute").equals("value")) {
fail("getAttribute(attribute) failed");
}
if (!s.getAttribute("KeySize").equals("1024")) {
fail("getAttribute(KeySize) failed");
}
}
public void testGetAlgorithm() {
Provider p = new MyProvider();
Provider.Service s1 = new Provider.Service(p, "type", "algorithm",
"className", null, null);
assertTrue(s1.getAlgorithm().equals("algorithm"));
Provider.Service s2 = new Provider.Service(p, "SecureRandom",
"algorithm", "tests.java.security.support.RandomImpl", null,
null);
assertTrue(s2.getAlgorithm().equals("algorithm"));
}
/**
* Calling setSeed after use adds the seed to the current state. It must never replace it.
*/
@Test
public void testSetSeedAfterUse() throws Exception {
final int samples = 10; // the number of samples per SecureRandom.
// The size of the generated pseudorandom bytes. An output size of 8 bytes
// means that the probability of false positives is about
// 2^{-65}*(samples * (#secure random instances))^2.
// Hence a random failure of this function is unlikely.
final int outputsize = 8;
Set<String> seen = new TreeSet<String>();
final byte[] seed = new byte[32];
for (Provider.Service service : secureRandomServices()) {
for (int i = 0; i < samples; i++) {
SecureRandom random = SecureRandom.getInstance(service.getAlgorithm(),
service.getProvider());
// Calling nextBytes() self-seeds the instance.
byte[] dummy = new byte[0];
random.nextBytes(dummy);
// Calling setSeed() adds the seed to the instance. It would be wrong to
// replace the current state of the instance with the new seed.
random.setSeed(seed);
byte[] bytes = new byte[outputsize];
// Hence it would be an error (or an unlikely false positive) if the generated
// bytes are already known.
random.nextBytes(bytes);
String hex = TestUtil.bytesToHex(bytes);
assertFalse("Repeated output from " + service.getAlgorithm(), seen.contains(hex));
seen.add(hex);
}
}
}
public static void main(String[] args) throws Exception {
for (Provider p : Security.getProviders()) {
for (Provider.Service s : p.getServices()) {
if (s.getType().equals("SecureRandom") &&
!s.getAlgorithm().contains("Block")) {
test(SecureRandom.getInstance(s.getAlgorithm(), p));
}
}
}
Security.setProperty("securerandom.drbg.config", "HMAC_DRBG");
test(SecureRandom.getInstance("DRBG"));
Security.setProperty("securerandom.drbg.config", "CTR_DRBG");
test(SecureRandom.getInstance("DRBG"));
}
/**
* Test server properties
* @throws P4JavaException
*/
@Test
public void testServerProperties() {
String[] serverUris = {
"p4java://eng-p4java-vm.das.perforce.com:20121?socketPoolSize=10&testKey1=testVal1",
"p4javassl://eng-p4java-vm.das.perforce.com:30121?socketPoolSize=10&testKey1=testVal1",
"p4jrpc://eng-p4java-vm.das.perforce.com:20121?socketPoolSize=10&testKey1=testVal1",
"p4jrpcssl://eng-p4java-vm.das.perforce.com:30121?socketPoolSize=10&testKey1=testVal1",
"p4jrpcnts://eng-p4java-vm.das.perforce.com:20121?socketPoolSize=10&testKey1=testVal1",
"p4jrpcntsssl://eng-p4java-vm.das.perforce.com:30121?socketPoolSize=10&testKey1=testVal1" };
try {
// List all the providers and the algorithms supporter
for (Provider provider : Security.getProviders()) {
debugPrint("Provider: " + provider.getName());
for (Provider.Service service : provider.getServices()) {
debugPrint(" Algorithm: " + service.getAlgorithm());
}
}
// List supported protocol versions for this connection
Socket socket = SSLSocketFactory.getDefault().createSocket();
String[] supportedProtocols = ((SSLSocket) socket)
.getSupportedProtocols();
for (String supportedProtocol : supportedProtocols) {
debugPrint("Supported Protocol Version: "
+ supportedProtocol);
}
// List enabled protocol versions for this connection
String[] enabledProtocols = ((SSLSocket) socket)
.getEnabledProtocols();
for (String enabledProtocol : enabledProtocols) {
debugPrint("Enabled Protocol Version: "
+ enabledProtocol);
}
Properties props = new Properties();
// props.put("secureSocketTrustAll", "false");
// props.put("secureSocketProtocol", "TLS");
props.put("secureSocketProtocol", "SSL");
// props.put("secureSocketSetEnabledProptocols", "false");
// props.put("secureSocketEnabledProtocols", "SSLv3, TLSv1");
props.put("secureSocketEnabledProtocols", "TLSv1, SSLv3");
// props.put("secureSocketEnabledProtocols", "TLSv1");
for (String serverUri : serverUris) {
server = ServerFactory.getOptionsServer(serverUri, props);
assertNotNull(server);
// Register callback
server.registerCallback(new MockCommandCallback());
setupServer(p4d.getRSHURL(), userName, password, true, props);
client = server.getClient("p4TestUserWS20112");
assertNotNull(client);
server.setCurrentClient(client);
IServerInfo serverInfo = server.getServerInfo();
assertNotNull(serverInfo);
}
} catch (Exception e) {
StringWriter sw = new StringWriter();
e.printStackTrace(new PrintWriter(sw));
fail("Unexpected exception: " + e.getLocalizedMessage() +
"\n" + sw.toString() );
}
}
public void removeService(Provider.Service service) {
super.removeService(service);
}
public TestProvider(String name, double version, String info) {
super(name, version, info);
serv = new Provider.Service(this, "CertificateFactory", "X.509",
TestFactorySpi.class.getName(), new ArrayList<String>(), null);
}
public Iterator<Provider.Service> iterator() {
return services.iterator();
}
@Override
public int compare(Provider.Service object1, Provider.Service object2) {
String s1 = object1.getType() + object1.getAlgorithm();
String s2 = object2.getType() + object2.getAlgorithm();
return s1.compareTo(s2);
}