下面列出了java.security.cert.CertPathValidatorResult#java.security.NoSuchProviderException 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
public static byte[] keyGen(int keySize, String password, String filePathString, int icount)
throws InvalidKeySpecException, NoSuchAlgorithmException, NoSuchProviderException {
File f = new File(filePathString);
byte[] salt = null;
if (f.exists() && !f.isDirectory()) {
salt = CryptoPrimitives.readAlternateImpl(filePathString);
} else {
salt = CryptoPrimitives.randomBytes(8);
CryptoPrimitives.write(salt, "saltInvIX", "salt");
}
byte[] key = CryptoPrimitives.keyGenSetM(password, salt, icount, keySize);
return key;
}
public final void verify(
PublicKey key)
throws CertificateException, NoSuchAlgorithmException,
InvalidKeyException, NoSuchProviderException, SignatureException
{
Signature signature;
String sigName = X509SignatureUtil.getSignatureName(c.getSignatureAlgorithm());
try
{
signature = Signature.getInstance(sigName, BouncyCastleProvider.PROVIDER_NAME);
}
catch (Exception e)
{
signature = Signature.getInstance(sigName);
}
checkSignature(key, signature);
}
private boolean run(byte[] buf) {
if (cf == null) {
try {
cf = CertificateFactory.getInstance("X.509", "SUN");
} catch (CertificateException e) {
throw new SecurityException("Cannot get CertificateFactory");
} catch (NoSuchProviderException npe) {
throw new SecurityException("Cannot get CertificateFactory");
}
}
try {
cf.generateCRL(new ByteArrayInputStream(buf));
} catch (CRLException ce) {
System.out.println("NPE checking passed");
return true;
}
System.out.println("CRLException has not been thrown");
return false;
}
/**
* Creates and initializes an empty KeyStore using the specified keyStoreType.
*
* @param keyStoreType type of key store to initialize, or null to use the system default
* @param provider JCA provider to use, or null to use the system default
* @return a new KeyStore
*/
public static KeyStore createEmptyKeyStore(String keyStoreType, String provider) {
if (keyStoreType == null) {
keyStoreType = KeyStore.getDefaultType();
}
KeyStore keyStore;
try {
if (provider == null) {
keyStore = KeyStore.getInstance(keyStoreType);
} else {
keyStore = KeyStore.getInstance(keyStoreType, provider);
}
keyStore.load(null, null);
} catch (KeyStoreException | CertificateException | NoSuchAlgorithmException | NoSuchProviderException | IOException e) {
throw new KeyStoreAccessException("Error creating or initializing new KeyStore of type: " + keyStoreType, e);
}
return keyStore;
}
public static MessageDigest getDigestInstance(String algorithmURI) throws NoSuchAlgorithmException {
String algorithmID = JCEMapper.translateURItoJCEID(algorithmURI);
if (algorithmID == null) {
throw new NoSuchAlgorithmException("Could not translate algorithmURI [" + algorithmURI + "]");
} else {
String provider = JCEMapper.getProviderId();
try {
MessageDigest md;
if (provider == null) {
md = MessageDigest.getInstance(algorithmID);
} else {
md = MessageDigest.getInstance(algorithmID, provider);
}
return md;
} catch (NoSuchProviderException var5) {
throw new NoSuchAlgorithmException("Could not find provider for [" + algorithmID + "]", var5);
}
}
}
@Test
public void testKID() throws
NoSuchAlgorithmException, NoSuchProviderException, java.security.spec.InvalidKeySpecException {
String serialized = "-----BEGIN PUBLIC KEY-----\n"
+ "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEApgviDRUN1Z6hIOBg5uj1k\n"
+ "KSJjfJjayEJeJR7A06sm5K4QjYKYMve55LaD8CMqf98l/gnZ0vIaCuf4G9mkphc/y\n"
+ "V0cgFY65wQmecPxv3IZ77wbJ+g5lL5vuCVTbh55nD++cj/hSBznXecQTXQNV9d51r\n"
+ "Ca65+PQ+YL1oRnrpUuLNPbdnc8kT/ZUq5Ic0WJM+NprN1tbbn2LafBY+igqbRQVox\n"
+ "It75B8cd+35iQAUm8B4sw8zGs1bFpBy3A8rhCYcBAOdK2iSSudK2WEfW1E7RWnnNv\n"
+ "w3ykMoVh1pq7zwL4P0IHXevvPnja+PmAT9zTwgU8WhiiIKl7YtJzkR9pEWtTwIDAQ\n"
+ "AB\n"
+ "-----END PUBLIC KEY-----";
Key publicKey = LTI13Util.string2PublicKey(serialized);
// Cast
RSAPublicKey rsaPublic = (RSAPublicKey) publicKey;
String keySetKID = LTI13KeySetUtil.getPublicKID(rsaPublic);
assertEquals("1171207714", keySetKID);
}
@Test
public void createAndDecryptSecretKeyElementTest()
throws PGPException, NoSuchAlgorithmException, NoSuchProviderException, InvalidAlgorithmParameterException,
IOException, MissingUserIdOnKeyException, MissingOpenPgpKeyException, InvalidBackupCodeException {
// Prepare store and provider and so on...
FileBasedOpenPgpStore store = new FileBasedOpenPgpStore(basePath);
PainlessOpenPgpProvider provider = new PainlessOpenPgpProvider(store);
// Generate and import key
PGPKeyRing keyRing = PGPainless.generateKeyRing().simpleEcKeyRing("xmpp:[email protected]");
BareJid jid = JidCreate.bareFrom("[email protected]");
provider.getStore().importSecretKey(jid, keyRing.getSecretKeys());
// Create encrypted backup
String backupCode = SecretKeyBackupHelper.generateBackupPassword();
SecretkeyElement element = SecretKeyBackupHelper.createSecretkeyElement(provider, jid, Collections.singleton(new OpenPgpV4Fingerprint(keyRing.getSecretKeys())), backupCode);
// Decrypt backup and compare
PGPSecretKeyRing secretKeyRing = SecretKeyBackupHelper.restoreSecretKeyBackup(element, backupCode);
assertTrue(Arrays.equals(keyRing.getSecretKeys().getEncoded(), secretKeyRing.getEncoded()));
}
public void verify(JWT jwt) throws CertificateException, NoSuchProviderException, UnsupportedEncodingException {
Set<TrustAnchor> trustAnchor = new HashSet<>();
trustAnchor.add(new TrustAnchor(rootCert, null));
List<Certificate> certchain = getCertificatesFromJsonArray(jwt.getHeader().getJsonArray("x5c"));
if(certchain == null){
throw new IllegalArgumentException("MDS JWT returned null certificate chain");
}
CertPath certPath = CertificateFactory.getInstance("X.509", "BCFIPS").generateCertPath(certchain);
if (certchain.isEmpty()) {
throw new IllegalArgumentException("MDS JWT certificate chain missing");
}
if (!PKIXChainValidation.pkixvalidate(certPath, trustAnchor, true, true)) {
throw new IllegalArgumentException("MDS JWT certificate could not be validated");
}
System.out.println("Certificate checked:" + certchain.get(0).toString());
if (!jwt.verifySignature(certchain.get(0).getPublicKey())) {
throw new IllegalArgumentException("MDS JWT signature cannot be verified");
}
}
public TestData(PublicKey pubArg, PrivateKey privArg)
throws NoSuchAlgorithmException, InvalidKeySpecException,
NoSuchProviderException, InvalidKeyException, SignatureException,
UnsupportedEncodingException, InvalidAlgorithmParameterException {
pub = pubArg;
priv = privArg;
int signedDataId = TagsEnum.TAG_UAFV1_SIGNED_DATA.id;
int signedDataLength = 200;
dataForSigning[0] = (byte) (signedDataId & 0x00ff);
dataForSigning[1] = (byte) (signedDataId & 0xff00);
dataForSigning[2] = (byte) (signedDataLength & 0x00ff);
dataForSigning[3] = (byte) (signedDataLength & 0xff00);
//signature = NamedCurve.sign(priv, dataForSigning);
rsSignature = NamedCurve.signAndFromatToRS(priv,
SHA.sha(dataForSigning, "SHA-1"));
}
private static void testDSAGenParameterSpec(DataTuple dataTuple)
throws NoSuchAlgorithmException, NoSuchProviderException,
InvalidParameterSpecException, InvalidAlgorithmParameterException {
System.out.printf("Test case: primePLen=%d, " + "subprimeQLen=%d%n",
dataTuple.primePLen, dataTuple.subprimeQLen);
AlgorithmParameterGenerator apg
= AlgorithmParameterGenerator.getInstance(ALGORITHM_NAME,
PROVIDER_NAME);
DSAGenParameterSpec genParamSpec = createGenParameterSpec(dataTuple);
// genParamSpec will be null if IllegalAE is thrown when expected.
if (genParamSpec == null) {
return;
}
try {
apg.init(genParamSpec, null);
AlgorithmParameters param = apg.generateParameters();
checkParam(param, genParamSpec);
System.out.println("Test case passed");
} catch (InvalidParameterException ipe) {
throw new RuntimeException("Test case failed.", ipe);
}
}
/**
* generate an X509 certificate, based on the current issuer and subject,
* using the passed in provider for the signing, and the passed in source
* of randomness (if required).
*/
public X509Certificate generate(
PrivateKey key,
String provider,
SecureRandom random)
throws CertificateEncodingException, IllegalStateException, NoSuchProviderException, NoSuchAlgorithmException, SignatureException, InvalidKeyException
{
TBSCertificate tbsCert = tbsGen.generateTBSCertificate();
byte[] signature;
try
{
signature = X509Util.calculateSignature(sigOID, signatureAlgorithm, provider, key, random, tbsCert);
}
catch (IOException e)
{
throw new ExtCertificateEncodingException("exception encoding TBS cert", e);
}
return generateJcaObject(tbsCert, signature);
}
public static String createToken(KeyPair keyPair, String issuer, Date issuedAt, Date expiresAt, String level)
throws NoSuchAlgorithmException,
NoSuchProviderException,
DynamicLogLevelException {
Algorithm rsa256 = Algorithm.RSA256((RSAPublicKey) keyPair.getPublic(), (RSAPrivateKey) keyPair.getPrivate());
if (ALLOWED_DYNAMIC_LOGLEVELS.contains(level)) {
return JWT.create().withIssuer(issuer).//
withIssuedAt(issuedAt). //
withExpiresAt(expiresAt).//
withClaim("level", level).sign(rsa256);
} else {
throw new DynamicLogLevelException("Dynamic Log-Level [" + level +
"] provided in header is not valid. Allowed Values are " +
ALLOWED_DYNAMIC_LOGLEVELS.toString());
}
}
public X509Certificate createSelfSignedCertificate(KeyPair keyPair) throws NoSuchAlgorithmException, NoSuchProviderException, CertIOException, OperatorCreationException, CertificateException {
long serial = System.currentTimeMillis();
SubjectPublicKeyInfo keyInfo = SubjectPublicKeyInfo.getInstance(keyPair.getPublic().getEncoded());
X500Name name = new X500Name(createX500NameString());
X509v3CertificateBuilder certBuilder = new X509v3CertificateBuilder(name,
BigInteger.valueOf(serial),
new Date(System.currentTimeMillis() - 1000000000),
new Date(System.currentTimeMillis() + 1000000000),
name,
keyInfo
);
certBuilder.addExtension(Extension.basicConstraints, true, new BasicConstraints(true));
certBuilder.addExtension(Extension.keyUsage, true, new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyEncipherment));
certBuilder.addExtension(Extension.extendedKeyUsage, true, new ExtendedKeyUsage(KeyPurposeId.id_kp_clientAuth));
JcaContentSignerBuilder csBuilder = new JcaContentSignerBuilder("SHA256withRSA");
ContentSigner signer = csBuilder.build(keyPair.getPrivate());
X509CertificateHolder certHolder = certBuilder.build(signer);
X509Certificate cert = new JcaX509CertificateConverter().getCertificate(certHolder);
return cert;
}
/**
* Retrieve the KeyManagers for the specified KeyStore.
*
* @param keyStore the KeyStore to retrieve KeyManagers from
* @param keyStorePassword the KeyStore password
* @param keyManagerAlgorithm key manager algorithm to use, or null to use the system default
* @param provider JCA provider to use, or null to use the system default
* @return KeyManagers for the specified KeyStore
*/
public static KeyManager[] getKeyManagers(KeyStore keyStore, String keyStorePassword, String keyManagerAlgorithm, String provider) {
if (keyManagerAlgorithm == null) {
keyManagerAlgorithm = KeyManagerFactory.getDefaultAlgorithm();
}
try {
KeyManagerFactory kmf;
if (provider == null) {
kmf = KeyManagerFactory.getInstance(keyManagerAlgorithm);
} else {
kmf = KeyManagerFactory.getInstance(keyManagerAlgorithm, provider);
}
kmf.init(keyStore, keyStorePassword.toCharArray());
return kmf.getKeyManagers();
} catch (NoSuchAlgorithmException | UnrecoverableKeyException | KeyStoreException | NoSuchProviderException e) {
throw new KeyStoreAccessException("Unable to get KeyManagers for KeyStore", e);
}
}
/**
* openssl i2d_ECPrivateKey函数生成的DER编码的ecc私钥是:PKCS1标准的、带有EC_GROUP、带有公钥的,
* 这个工具函数的主要目的就是为了使Java程序能够“识别”openssl生成的ECC私钥
*
* @param encodedKey
* @return
* @throws NoSuchAlgorithmException
* @throws NoSuchProviderException
* @throws InvalidKeySpecException
*/
public static ECPrivateKeyParameters convertPkcs1DerToEcPriKey(byte[] encodedKey)
throws NoSuchAlgorithmException, NoSuchProviderException, InvalidKeySpecException {
PKCS8EncodedKeySpec peks = new PKCS8EncodedKeySpec(encodedKey);
KeyFactory kf = KeyFactory.getInstance(ALGO_NAME_EC, BouncyCastleProvider.PROVIDER_NAME);
BCECPrivateKey privateKey = (BCECPrivateKey) kf.generatePrivate(peks);
ECParameterSpec ecParameterSpec = privateKey.getParameters();
ECDomainParameters ecDomainParameters = new ECDomainParameters(ecParameterSpec.getCurve(),
ecParameterSpec.getG(), ecParameterSpec.getN(), ecParameterSpec.getH());
ECPrivateKeyParameters priKey = new ECPrivateKeyParameters(privateKey.getD(),
ecDomainParameters);
return priKey;
}
public void testGetInstance05() throws NoSuchAlgorithmException,
NoSuchProviderException, IllegalArgumentException,
InvalidAlgorithmParameterException {
KeyPairGeneratorProviderClass = KeyPairGeneratorProviderClass2;
resAlg = MyKeyPairGenerator2.getResAlgorithm();
post = "_2";
setProv();
GetInstance02(2);
}
public static void main(String[] args) throws FileNotFoundException, IOException, NoSuchAlgorithmException, NoSuchProviderException {
Security.addProvider(new BouncyCastleProvider());
LOGGER.info("BouncyCastle provider added.");
KeyPair keyPair = generateRSAKeyPair();
RSAPrivateKey priv = (RSAPrivateKey) keyPair.getPrivate();
RSAPublicKey pub = (RSAPublicKey) keyPair.getPublic();
writePemFile(priv, "RSA PRIVATE KEY", "id_rsa");
writePemFile(pub, "RSA PUBLIC KEY", "id_rsa.pub");
}
public static String signObject(String input, String privateKeyS) throws NoSuchAlgorithmException, NoSuchProviderException, InvalidKeyException, SignatureException, InvalidKeySpecException {
////put decrypted private key in a BCPrivate key object
byte[] prk = Base64.decodeBase64(privateKeyS);
//get private key into BC understandable form
ECPrivateKeySpec ecpks = new ECPrivateKeySpec(new BigInteger(privateKeyS), null);
KeyFactory kf = KeyFactory.getInstance("ECDSA", "BCFIPS");
PrivateKey pvk = kf.generatePrivate(ecpks);
//Base64 decode input
byte[] inputbytes = Base64.decodeBase64(input);
//sign
Signature sig = Signature.getInstance("SHA256withECDSA", "BCFIPS");
sig.initSign(pvk, new SecureRandom());
sig.update(inputbytes);
byte[] signedBytes = sig.sign();
// //verify locally FIXME -- local verification is required // not sure how to get the public key
// PublicKey pkey = userKeyPair.getPublic();
// sig.initVerify(pkey);
// sig.update(inputbytes);
// if (sig.verify(signedBytes)) {
// return Base64.encodeBase64String(signedBytes);
// } else {
// return null;
// }
return Base64.encodeBase64String(signedBytes);
}
public static SSLContext newClientContext(KeyManager[] keyManagers,
TrustManager[] trustManagers) throws NoSuchAlgorithmException,
KeyManagementException, NoSuchProviderException {
SSLContext result = newSSLContext();
result.init(keyManagers, trustManagers, null);
return result;
}
/**
* Returns a <code>TransformService</code> that supports the specified
* algorithm URI (ex: {@link Transform#XPATH2}) and mechanism type
* (ex: DOM) as supplied by the specified provider. The specified provider
* must be registered in the security provider list.
*
* <p>Note that the list of registered providers may be retrieved via
* the {@link Security#getProviders() Security.getProviders()} method.
*
* @param algorithm the URI of the algorithm
* @param mechanismType the type of the XML processing mechanism and
* representation
* @param provider the string name of the provider
* @return a new <code>TransformService</code>
* @throws NoSuchProviderException if the specified provider is not
* registered in the security provider list
* @throws NullPointerException if <code>provider</code>,
* <code>mechanismType</code>, or <code>algorithm</code> is
* <code>null</code>
* @throws NoSuchAlgorithmException if a <code>TransformService</code>
* implementation for the specified algorithm and mechanism type is not
* available from the specified provider
* @see Provider
*/
public static TransformService getInstance
(String algorithm, String mechanismType, String provider)
throws NoSuchAlgorithmException, NoSuchProviderException {
if (mechanismType == null || algorithm == null || provider == null) {
throw new NullPointerException();
} else if (provider.length() == 0) {
throw new NoSuchProviderException();
}
boolean dom = false;
if (mechanismType.equals("DOM")) {
dom = true;
}
Service s = GetInstance.getService
("TransformService", algorithm, provider);
String value = s.getAttribute("MechanismType");
if ((value == null && dom) ||
(value != null && value.equals(mechanismType))) {
Instance instance = GetInstance.getInstance(s, null);
TransformService ts = (TransformService) instance.impl;
ts.algorithm = algorithm;
ts.mechanism = mechanismType;
ts.provider = instance.provider;
return ts;
}
throw new NoSuchAlgorithmException
(algorithm + " algorithm and " + mechanismType
+ " mechanism not available");
}
private Cipher createCipher(int mode, AlgorithmParameters params)
throws NoSuchAlgorithmException, NoSuchProviderException,
NoSuchPaddingException, InvalidKeyException,
InvalidAlgorithmParameterException {
Cipher cipher = Cipher.getInstance(TRANSFORMATION, PROVIDER);
if (params != null) {
cipher.init(mode, key, params);
} else {
cipher.init(mode, key);
}
return cipher;
}
public static String getDigestRawInput(byte[] Input, String algorithm) throws NoSuchAlgorithmException, NoSuchProviderException, UnsupportedEncodingException {
MessageDigest digest;
digest = MessageDigest.getInstance(algorithm, "BCFIPS");
byte[] digestbytes = digest.digest(Input);
String dig = Base64.encodeBase64String(digestbytes);
return dig;
}
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).");
}
public static SM2X509CertMaker buildCertMaker() throws InvalidAlgorithmParameterException,
NoSuchAlgorithmException, NoSuchProviderException, InvalidX500NameException {
X500Name issuerName = buildRootCADN();
KeyPair issKP = SM2Util.generateKeyPair();
long certExpire = 20L * 365 * 24 * 60 * 60 * 1000; // 20年
CertSNAllocator snAllocator = new RandomSNAllocator(); // 实际应用中可能需要使用数据库来保证证书序列号的唯一性。
return new SM2X509CertMaker(issKP, certExpire, issuerName, snAllocator);
}
private static void runTest(DataTuple dataTuple)
throws NoSuchAlgorithmException, NoSuchProviderException {
MessageDigest mdAlgorithm = MessageDigest.getInstance(
dataTuple.algorithm, PROVIDER_NAME);
MessageDigest mdOid = MessageDigest.getInstance(dataTuple.oid,
PROVIDER_NAME);
if (mdAlgorithm == null) {
throw new RuntimeException(String.format(
"Test failed: algorithm string %s getInstance failed.%n",
dataTuple.algorithm));
}
if (mdOid == null) {
throw new RuntimeException(
String.format("Test failed: OID %s getInstance failed.%n",
dataTuple.oid));
}
if (!mdAlgorithm.getAlgorithm().equals(dataTuple.algorithm)) {
throw new RuntimeException(String.format(
"Test failed: algorithm string %s getInstance doesn't "
+ "generate expected algorithm.%n",
dataTuple.algorithm));
}
mdAlgorithm.update(INPUT);
mdOid.update(INPUT);
// Comparison
if (!Arrays.equals(mdAlgorithm.digest(), mdOid.digest())) {
throw new RuntimeException("Digest comparison failed: "
+ "the two digests are not the same");
}
}
public synchronized KeyPair generateKeyPair(final int keyLength)
throws NoSuchProviderException, NoSuchAlgorithmException {
final BouncyCastleFipsProvider bouncyCastleProvider = new BouncyCastleFipsProvider();
Security.addProvider(bouncyCastleProvider);
final KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA", BouncyCastleFipsProvider.PROVIDER_NAME);
generator.initialize(keyLength);
return generator.generateKeyPair();
}
/**
* generate an X509 certificate, based on the current issuer and subject,
* using the passed in provider for the signing, and the passed in source
* of randomness (if required).
*/
public X509Certificate generateX509Certificate(
PrivateKey key,
String provider)
throws NoSuchProviderException, SecurityException, SignatureException, InvalidKeyException
{
return generateX509Certificate(key, provider, null);
}
public AESSensitivePropertyProvider(String keyHex) throws NoSuchPaddingException, NoSuchAlgorithmException, NoSuchProviderException {
byte[] key = validateKey(keyHex);
try {
cipher = Cipher.getInstance(ALGORITHM, PROVIDER);
// Only store the key if the cipher was initialized successfully
this.key = new SecretKeySpec(key, "AES");
} catch (NoSuchAlgorithmException | NoSuchProviderException | NoSuchPaddingException e) {
logger.error("Encountered an error initializing the {}: {}", IMPLEMENTATION_NAME, e.getMessage());
throw new SensitivePropertyProtectionException("Error initializing the protection cipher", e);
}
}
public JSONObject getUserInfo(String accessToken) throws IOException, KeyManagementException, NoSuchAlgorithmException, NoSuchProviderException {
Map<String, String> params = new HashMap<>();
params.put("Authorization", "Bearer " + accessToken);
String userInfo = super.doGetWithHeaders("https://api.douban.com/v2/user/~me", params);
JSONObject dataMap = JSON.parseObject(userInfo);
LOGGER.debug(dataMap.toJSONString());
return dataMap;
}
public static void main(String[] args) throws NoSuchAlgorithmException {
try {
TransformService ts = TransformService.getInstance(
Transform.BASE64, "DOM", "SomeProviderThatDoesNotExist");
}
catch(NoSuchProviderException e) {
// this is expected
}
}