下面列出了怎么用java.security.Provider的API类实例代码及写法,或者点击链接到github查看源代码。
public static boolean enableBouncyCastleProvider()
{
try
{
Class<Provider> bcProvider = (Class<Provider>) Class.forName(BC_PROVIDER_FQCN);
for (Provider provider : Security.getProviders())
{
if (bcProvider.isInstance(provider))
{
return true;
}
}
Security.addProvider(bcProvider.newInstance());
return true;
}
catch (Exception e)
{
// Not available...
return false;
}
}
public ProviderList(GSSCaller caller, boolean useNative) {
this.caller = caller;
Provider[] provList;
if (useNative) {
provList = new Provider[1];
provList[0] = new SunNativeProvider();
} else {
provList = Security.getProviders();
}
for (int i = 0; i < provList.length; i++) {
Provider prov = provList[i];
try {
addProviderAtEnd(prov, null);
} catch (GSSException ge) {
// Move on to the next provider
GSSUtil.debug("Error in adding provider " +
prov.getName() + ": " + ge);
}
} // End of for loop
}
public static void ensureProviderAtFirstPosition(Class<? extends Provider> providerClass) {
if (INSERTED_PROVIDERS_CACHE.containsKey(providerClass)) {
return;
}
Provider provider;
try {
provider = providerClass.getDeclaredConstructor().newInstance();
} catch (InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException
| NoSuchMethodException | SecurityException e) {
throw new IllegalArgumentException(e);
}
String providerName = provider.getName();
int installedPosition ;
synchronized (Security.class) {
Security.removeProvider(providerName);
installedPosition = Security.insertProviderAt(provider, 1);
}
assert installedPosition == 1;
INSERTED_PROVIDERS_CACHE.put(providerClass, null);
}
private void wrapperPBEKeyTest(Provider p) throws InvalidKeySpecException,
InvalidKeyException, NoSuchPaddingException,
IllegalBlockSizeException, InvalidAlgorithmParameterException,
NoSuchAlgorithmException {
for (String alg : PBE_ALGORITHM_AR) {
String baseAlgo = alg.split("/")[0].toUpperCase();
// only run the tests on longer key lengths if unlimited version
// of JCE jurisdiction policy files are installed
if (Cipher.getMaxAllowedKeyLength(alg) < Integer.MAX_VALUE
&& (baseAlgo.endsWith("TRIPLEDES") || alg
.endsWith("AES_256"))) {
out.println("keyStrength > 128 within " + alg
+ " will not run under global policy");
continue;
}
SecretKeyFactory skf = SecretKeyFactory.getInstance(baseAlgo, p);
SecretKey key = skf.generateSecret(new PBEKeySpec("Secret Lover"
.toCharArray()));
wrapTest(alg, alg, key, key, Cipher.SECRET_KEY, true);
}
}
public static void main(String arg[]) throws Exception{
boolean failure = false;
for (Provider p: Security.getProviders()) {
System.out.print(p.getName() + " ");
if (p.getVersion() != 9.0d) {
System.out.println("failed. " + "Version received was " +
p.getVersion());
failure = true;
} else {
System.out.println("passed.");
}
}
if (failure) {
throw new Exception("Provider(s) failed to have the expected " +
"version value.");
}
}
public boolean runAll(Provider p, PrintStream out) {
boolean finalResult = true;
for (String algorithm : PBEAlgorithms) {
out.println("Running test with " + algorithm + ":");
try {
if (!runTest(p, algorithm, out)) {
finalResult = false;
out.println("STATUS: Failed");
} else {
out.println("STATUS: Passed");
}
} catch (Exception ex) {
finalResult = false;
ex.printStackTrace(out);
out.println("STATUS:Failed");
}
}
return finalResult;
}
/**
* returns the available implementations for a service type
*/
private static Set getCryptoImpls( String serviceType){
Set result = new HashSet();
// All all providers
Provider[] providers = Security.getProviders();
for (int i = 0; i < providers.length; i++) {
// Get services provided by each provider
Set keys = providers[i].keySet();
for (Iterator it = keys.iterator(); it.hasNext();) {
String key = (String) it.next();
key = key.split(" ")[0];
if (key.startsWith(serviceType + ".")) {
result.add(key.substring(serviceType.length() + 1));
} else if (key.startsWith("Alg.Alias." + serviceType + ".")) {
// This is an alias
result.add(key.substring(serviceType.length() + 11));
}
}
}
return result;
}
@Override
public void main(Provider provider) throws Exception {
if (provider.getService("KeyPairGenerator", "DiffieHellman") == null) {
System.out.println("No support of DH KeyPairGenerator, skipping");
return;
}
for (SupportedKeySize keySize : SupportedKeySize.values()) {
System.out.println("Checking " + keySize.primeSize + " ...");
KeyPairGenerator kpg =
KeyPairGenerator.getInstance("DiffieHellman", provider);
kpg.initialize(keySize.primeSize);
KeyPair kp = kpg.generateKeyPair();
checkKeyPair(kp, keySize.primeSize, provider);
DHPublicKey publicKey = (DHPublicKey)kp.getPublic();
BigInteger p = publicKey.getParams().getP();
BigInteger g = publicKey.getParams().getG();
kpg.initialize(new DHParameterSpec(p, g));
kp = kpg.generateKeyPair();
checkKeyPair(kp, keySize.primeSize, provider);
}
}
private List<String> getDigestAlgorithms(Provider provider) {
if (provider == null) {
fail("No digest algorithms were found");
}
List<String> algs = new ArrayList<String>();
for (Object key : provider.keySet()) {
String algorithm = (String) key;
if (algorithm.startsWith(MESSAGEDIGEST_ID) && !algorithm.contains(" ")) {
algs.add(algorithm.substring(MESSAGEDIGEST_ID.length()));
}
}
if (algs.size() == 0) {
fail("No digest algorithms were found");
}
return algs;
}
public void testNewlyCreatedServiceDoesntGetsRegistered() 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);
assertSame(p, s.getProvider());
assertNull(p.getService(type, algorithm));
try {
Object o = s.newInstance(null);
fail("Expected " + NoSuchAlgorithmException.class.getName() + " as the service is not "
+ "registered with the provider");
} catch (NoSuchAlgorithmException e) {
// Expected.
}
}
public boolean runAll(Provider p, PrintStream out) {
boolean finalResult = true;
for (String algorithm : PBEAlgorithms) {
out.println("Running test with " + algorithm + ":");
try {
if (!runTest(p, algorithm, out)) {
finalResult = false;
out.println("STATUS: Failed");
} else {
out.println("STATUS: Passed");
}
} catch (Exception ex) {
finalResult = false;
ex.printStackTrace(out);
out.println("STATUS:Failed");
}
}
return finalResult;
}
/**
* Creates a <code>DOMCanonicalizationMethod</code> from an element. This
* ctor invokes the abstract {@link #unmarshalParams unmarshalParams}
* method to unmarshal any algorithm-specific input parameters.
*
* @param cmElem a CanonicalizationMethod element
*/
public DOMCanonicalizationMethod(Element cmElem, XMLCryptoContext context,
Provider provider)
throws MarshalException
{
super(cmElem, context, provider);
if (!(spi instanceof ApacheCanonicalizer) &&
!isC14Nalg(spi.getAlgorithm())) {
throw new MarshalException("Illegal CanonicalizationMethod");
}
}
/**
* Adds a security provider dynamically if it is not loaded already.
*
* @param providerName - name of the provider.
*/
private Provider initSecurityProvider(String providerName) {
switch (providerName) {
case "BC":
Security.addProvider(new BouncyCastleProvider());
return Security.getProvider(providerName);
default:
LOG.error("Security Provider:{} is unknown", provider);
throw new SecurityException("Unknown security provider:" + provider);
}
}
/**
* Returns a non-null content encryption material generated with the given kek material and
* security providers.
*
* @throws SdkClientException if no encryption material can be found from the given encryption
* material provider.
*/
private ContentCryptoMaterial newContentCryptoMaterial(
EncryptionMaterialsProvider kekMaterialProvider, Provider provider,
CosServiceRequest req) {
EncryptionMaterials kekMaterials = kekMaterialProvider.getEncryptionMaterials();
if (kekMaterials == null)
throw new CosClientException(
"No material available from the encryption material provider");
return buildContentCryptoMaterial(kekMaterials, provider, req);
}
private static GSSException createGSSException(Provider p,
String className,
String trailingMsg,
Exception cause) {
String errClassInfo = className + " configured by " +
p.getName() + " for GSS-API Mechanism Factory ";
return new GSSExceptionImpl(GSSException.BAD_MECH,
errClassInfo + trailingMsg,
cause);
}
public static void main0(String[] args) throws Exception {
Provider p = Security.getProvider("SunEC");
if (p == null) {
throw new NoSuchProviderException("Can't get SunEC provider");
}
System.out.println("Running tests with " + p.getName() +
" provider...\n");
long start = System.currentTimeMillis();
/*
* The entry point used for each test is its instance method
* called main (not its static method called main).
*/
new TestECDH().main(p);
new TestECDSA().main(p);
new TestCurves().main(p);
new TestKeyFactory().main(p);
new TestECGenSpec().main(p);
new ReadPKCS12().main(p);
new ReadCertificates().main(p);
// ClientJSSEServerJSSE fails on Solaris 11 when both SunEC and
// SunPKCS11-Solaris providers are enabled.
// Workaround:
// Security.removeProvider("SunPKCS11-Solaris");
new ClientJSSEServerJSSE().main(p);
long stop = System.currentTimeMillis();
System.out.println("\nCompleted tests with " + p.getName() +
" provider (" + ((stop - start) / 1000.0) + " seconds).");
}
/**
* Generate a key pair.
*
* @param keyPairType
* Key pair type to generate
* @param keySize
* Key size of key pair
* @return A keypair
* @param provider
* Crypto provider used for key generation
* @throws CryptoException
* If there was a problem generating the key pair
*/
public static KeyPair generateKeyPair(KeyPairType keyPairType, int keySize, Provider provider) throws CryptoException {
try {
// Get a key pair generator
KeyPairGenerator keyPairGen = null;
if (provider != null) {
keyPairGen = KeyPairGenerator.getInstance(keyPairType.jce(), provider);
} else {
// Always use BC provider for RSA
if (keyPairType == RSA) {
keyPairGen = KeyPairGenerator.getInstance(keyPairType.jce(), BOUNCY_CASTLE.jce());
} else {
// Use default provider for DSA
keyPairGen = KeyPairGenerator.getInstance(keyPairType.jce());
}
}
// Create a SecureRandom
SecureRandom rand = SecureRandom.getInstance("SHA1PRNG");
// Initialise key pair generator with key strength and randomness
keyPairGen.initialize(keySize, rand);
// Generate and return the key pair
KeyPair keyPair = keyPairGen.generateKeyPair();
return keyPair;
} catch (GeneralSecurityException ex) {
throw new CryptoException(MessageFormat.format(res.getString("NoGenerateKeypair.exception.message"),
keyPairType), ex);
}
}
/**
* Helper routine to go through all properties contined in a
* provider and add its mechanisms to the list of supported
* mechanisms. If no default mechanism has been assinged so far,
* it sets the default MechanismFactory and Oid as well.
* @param p the provider to query
* @return true if there is at least one mechanism that this
* provider contributed, false otherwise
*/
private boolean addAllMechsFromProvider(Provider p) {
String prop;
boolean retVal = false;
// Get all props for this provider
Enumeration<Object> props = p.keys();
// See if there are any GSS prop's
while (props.hasMoreElements()) {
prop = (String) props.nextElement();
if (isMechFactoryProperty(prop)) {
// Ok! This is a GSS provider!
try {
Oid mechOid = getOidFromMechFactoryProperty(prop);
mechs.add(mechOid);
retVal = true;
} catch (GSSException e) {
// Skip to next property
GSSUtil.debug("Ignore the invalid property " +
prop + " from provider " + p.getName());
}
} // Processed GSS property
} // while loop
return retVal;
}
private X509StreamParser(
Provider provider,
X509StreamParserSpi spi)
{
_provider = provider;
_spi = spi;
}
/**
* Creates a <code>DOMManifest</code> from an element.
*
* @param manElem a Manifest element
*/
public DOMManifest(Element manElem, XMLCryptoContext context,
Provider provider)
throws MarshalException
{
Attr attr = manElem.getAttributeNodeNS(null, "Id");
if (attr != null) {
this.id = attr.getValue();
manElem.setIdAttributeNode(attr, true);
} else {
this.id = null;
}
boolean secVal = Utils.secureValidation(context);
Element refElem = DOMUtils.getFirstChildElement(manElem, "Reference");
List<Reference> refs = new ArrayList<Reference>();
refs.add(new DOMReference(refElem, context, provider));
refElem = DOMUtils.getNextSiblingElement(refElem);
while (refElem != null) {
String localName = refElem.getLocalName();
if (!localName.equals("Reference")) {
throw new MarshalException("Invalid element name: " +
localName + ", expected Reference");
}
refs.add(new DOMReference(refElem, context, provider));
if (secVal && Policy.restrictNumReferences(refs.size())) {
String error = "A maximum of " + Policy.maxReferences()
+ " references per Manifest are allowed when"
+ " secure validation is enabled";
throw new MarshalException(error);
}
refElem = DOMUtils.getNextSiblingElement(refElem);
}
this.references = Collections.unmodifiableList(refs);
}
public static void main(String[] args) {
PBESealedObject test = new PBESealedObject();
Provider sunjce = Security.getProvider("SunJCE");
if (!test.runAll(sunjce, System.out)) {
throw new RuntimeException("One or more tests have failed....");
}
}
/**
* Creates a <code>DOMManifest</code> from an element.
*
* @param manElem a Manifest element
*/
public DOMManifest(Element manElem, XMLCryptoContext context,
Provider provider)
throws MarshalException
{
Attr attr = manElem.getAttributeNodeNS(null, "Id");
if (attr != null) {
this.id = attr.getValue();
manElem.setIdAttributeNode(attr, true);
} else {
this.id = null;
}
boolean secVal = Utils.secureValidation(context);
Element refElem = DOMUtils.getFirstChildElement(manElem, "Reference");
List<Reference> refs = new ArrayList<Reference>();
refs.add(new DOMReference(refElem, context, provider));
refElem = DOMUtils.getNextSiblingElement(refElem);
while (refElem != null) {
String localName = refElem.getLocalName();
if (!localName.equals("Reference")) {
throw new MarshalException("Invalid element name: " +
localName + ", expected Reference");
}
refs.add(new DOMReference(refElem, context, provider));
if (secVal && (refs.size() > DOMSignedInfo.MAXIMUM_REFERENCE_COUNT)) {
String error = "A maxiumum of " + DOMSignedInfo.MAXIMUM_REFERENCE_COUNT + " "
+ "references per Manifest are allowed with secure validation";
throw new MarshalException(error);
}
refElem = DOMUtils.getNextSiblingElement(refElem);
}
this.references = Collections.unmodifiableList(refs);
}
private void test(Provider provider, String pub, String priv, byte[] sig) throws Exception {
KeyFactory kf = KeyFactory.getInstance("EC", provider);
X509EncodedKeySpec pubSpec = new X509EncodedKeySpec(parse(pub));
PKCS8EncodedKeySpec privSpec = new PKCS8EncodedKeySpec(parse(priv));
PrivateKey privateKey = kf.generatePrivate(privSpec);
PublicKey publicKey = kf.generatePublic(pubSpec);
if (false) {
sign(provider, "SHA1withECDSA", privateKey, data1Raw);
// sign(provider, "NONEwithECDSA", privateKey, data1SHA);
return;
}
// verify known-good and known-bad signatures using SHA1withECDSA and NONEwithECDSA
verify(provider, "SHA1withECDSA", publicKey, data1Raw, sig, true);
verify(provider, "SHA1withECDSA", publicKey, data2Raw, sig, false);
verify(provider, "NONEwithECDSA", publicKey, data1SHA, sig, true);
verify(provider, "NONEwithECDSA", publicKey, data2SHA, sig, false);
System.out.println("Testing with default signature format: ASN.1");
testSigning(provider, privateKey, publicKey, false);
System.out.println("Testing with IEEE P1363 signature format");
testSigning(provider, privateKey, publicKey, true);
}
GSSContextSpi getMechanismContext(GSSCredentialSpi myAcceptorCred,
Oid mech)
throws GSSException {
Provider p = null;
if (myAcceptorCred != null) {
p = myAcceptorCred.getProvider();
}
MechanismFactory factory = list.getMechFactory(mech, p);
return factory.getMechanismContext(myAcceptorCred);
}
/**
* Creates a <code>DOMCanonicalizationMethod</code> from an element. This
* ctor invokes the abstract {@link #unmarshalParams unmarshalParams}
* method to unmarshal any algorithm-specific input parameters.
*
* @param cmElem a CanonicalizationMethod element
*/
public DOMCanonicalizationMethod(Element cmElem, XMLCryptoContext context,
Provider provider)
throws MarshalException
{
super(cmElem, context, provider);
if (!(spi instanceof ApacheCanonicalizer) &&
!isC14Nalg(spi.getAlgorithm())) {
throw new MarshalException("Illegal CanonicalizationMethod");
}
}
/**
* Creates a <code>DOMCanonicalizationMethod</code> from an element. This
* ctor invokes the abstract {@link #unmarshalParams unmarshalParams}
* method to unmarshal any algorithm-specific input parameters.
*
* @param cmElem a CanonicalizationMethod element
*/
public DOMCanonicalizationMethod(Element cmElem, XMLCryptoContext context,
Provider provider)
throws MarshalException
{
super(cmElem, context, provider);
if (!(spi instanceof ApacheCanonicalizer) &&
!isC14Nalg(spi.getAlgorithm())) {
throw new MarshalException("Illegal CanonicalizationMethod");
}
}
/**
* Creates a {@code DOMTransform} from an element. This constructor
* invokes the abstract {@link #unmarshalParams unmarshalParams} method to
* unmarshal any algorithm-specific input parameters.
*
* @param transElem a Transform element
*/
public DOMTransform(Element transElem, XMLCryptoContext context,
Provider provider)
throws MarshalException
{
String algorithm = DOMUtils.getAttributeValue(transElem, "Algorithm");
if (provider == null) {
try {
spi = TransformService.getInstance(algorithm, "DOM");
} catch (NoSuchAlgorithmException e1) {
throw new MarshalException(e1);
}
} else {
try {
spi = TransformService.getInstance(algorithm, "DOM", provider);
} catch (NoSuchAlgorithmException nsae) {
try {
spi = TransformService.getInstance(algorithm, "DOM");
} catch (NoSuchAlgorithmException e2) {
throw new MarshalException(e2);
}
}
}
try {
spi.init(new javax.xml.crypto.dom.DOMStructure(transElem), context);
} catch (InvalidAlgorithmParameterException iape) {
throw new MarshalException(iape);
}
}
/**
* java.security.MessageDigest#getAlgorithm()
*/
public void test_getAlgorithm() throws Exception {
for (Entry<Provider, List<String>> e : digestAlgs.entrySet()) {
for (String algorithm : e.getValue()) {
MessageDigest md = MessageDigest.getInstance(algorithm, e.getKey().getName());
assertEquals(algorithm, md.getAlgorithm());
}
}
}
public static void main(String[] args) {
PBESealedObject test = new PBESealedObject();
Provider sunjce = Security.getProvider("SunJCE");
if (!test.runAll(sunjce, System.out)) {
throw new RuntimeException("One or more tests have failed....");
}
}
/**
* 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);
}
}
}