下面列出了java.security.cert.PKIXCertPathValidatorResult#java.security.InvalidAlgorithmParameterException 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
public CanonicalizationMethod newCanonicalizationMethod(String algorithm,
XMLStructure params) throws NoSuchAlgorithmException,
InvalidAlgorithmParameterException {
TransformService spi;
if (getProvider() == null) {
spi = TransformService.getInstance(algorithm, "DOM");
} else {
try {
spi = TransformService.getInstance(algorithm, "DOM", getProvider());
} catch (NoSuchAlgorithmException nsae) {
spi = TransformService.getInstance(algorithm, "DOM");
}
}
if (params == null) {
spi.init(null);
} else {
spi.init(params, null);
}
return new DOMCanonicalizationMethod(spi);
}
@Test
public void test_builder() throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, UnsupportedEncodingException, IllegalBlockSizeException, BadPaddingException, InvalidAlgorithmParameterException, InvalidKeySpecException {
Encryption encryption = new Encryption.Builder()
.setKeyLength(128)
.setKeyAlgorithm("AES")
.setCharsetName("UTF8")
.setIterationCount(65536)
.setKey("mor€Z€cr€tKYss")
.setDigestAlgorithm("SHA1")
.setSalt("A beautiful salt")
.setBase64Mode(Base64.DEFAULT)
.setAlgorithm("AES/CBC/PKCS5Padding")
.setSecureRandomAlgorithm("SHA1PRNG")
.setSecretKeyType("PBKDF2WithHmacSHA1")
.setIv(new byte[] { 29, 88, -79, -101, -108, -38, -126, 90, 52, 101, -35, 114, 12, -48, -66, -30 })
.build();
assertNotNull(encryption);
String textToEncrypt = "A text to builder test.";
String encryptedText = encryption.encrypt(textToEncrypt);
assertNotNull(encryptedText);
String decryptedText = encryption.decrypt(encryptedText);
assertNotNull(decryptedText);
assertEquals(decryptedText, textToEncrypt);
}
public static byte[] aes256decrypt(byte[] ivBytes, byte[] keyBytes, byte[] textBytes)
throws java.io.UnsupportedEncodingException,
NoSuchAlgorithmException,
NoSuchPaddingException,
InvalidKeyException,
InvalidAlgorithmParameterException,
IllegalBlockSizeException,
BadPaddingException {
AlgorithmParameterSpec ivSpec = new IvParameterSpec(ivBytes);
SecretKeySpec newKey = new SecretKeySpec(keyBytes, "AES");
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE, newKey, ivSpec);
return cipher.doFinal(textBytes);
}
public void initialize(
int strength,
SecureRandom random)
{
this.strength = strength;
this.random = random;
ECGenParameterSpec ecParams = (ECGenParameterSpec)ecParameters.get(Integers.valueOf(strength));
if (ecParams == null)
{
throw new InvalidParameterException("unknown key size.");
}
try
{
initialize(ecParams, random);
}
catch (InvalidAlgorithmParameterException e)
{
throw new InvalidParameterException("key size not configurable.");
}
}
public Transform newTransform(String algorithm,
TransformParameterSpec params) throws NoSuchAlgorithmException,
InvalidAlgorithmParameterException {
TransformService spi;
if (getProvider() == null) {
spi = TransformService.getInstance(algorithm, "DOM");
} else {
try {
spi = TransformService.getInstance(algorithm, "DOM", getProvider());
} catch (NoSuchAlgorithmException nsae) {
spi = TransformService.getInstance(algorithm, "DOM");
}
}
spi.init(params);
return new DOMTransform(spi);
}
/**
* Check if given certificate is revoked looking on it's CRL (if exist).
* @param cert which is validated
* @return true if certificate is revoked, false if it isn't or CRL cannot be accessed (because it might not exist).
*/
public boolean checkRevocation(X509Certificate cert) {
boolean revoked = false;
try {
SparkTrustManager man = new SparkTrustManager();
Collection<X509CRL> crls = man.loadCRL(new X509Certificate[] { cert });
CertificateFactory cf = CertificateFactory.getInstance("X.509");
for (X509CRL crl : crls) {
if (crl.isRevoked(cert)) {
revoked = true;
break;
}
}
} catch (CRLException | CertificateException | IOException | InvalidAlgorithmParameterException
| NoSuchAlgorithmException | CertStoreException e) {
Log.warning("Cannot check validity", e);
}
return revoked;
}
public CanonicalizationMethod newCanonicalizationMethod(String algorithm,
XMLStructure params) throws NoSuchAlgorithmException,
InvalidAlgorithmParameterException {
TransformService spi;
if (getProvider() == null) {
spi = TransformService.getInstance(algorithm, "DOM");
} else {
try {
spi = TransformService.getInstance(algorithm, "DOM", getProvider());
} catch (NoSuchAlgorithmException nsae) {
spi = TransformService.getInstance(algorithm, "DOM");
}
}
if (params == null) {
spi.init(null);
} else {
spi.init(params, null);
}
return new DOMCanonicalizationMethod(spi);
}
public Transform newTransform(String algorithm,
XMLStructure params) throws NoSuchAlgorithmException,
InvalidAlgorithmParameterException {
TransformService spi;
if (getProvider() == null) {
spi = TransformService.getInstance(algorithm, "DOM");
} else {
try {
spi = TransformService.getInstance(algorithm, "DOM", getProvider());
} catch (NoSuchAlgorithmException nsae) {
spi = TransformService.getInstance(algorithm, "DOM");
}
}
if (params == null) {
spi.init(null);
} else {
spi.init(params, null);
}
return new DOMTransform(spi);
}
private static byte[] performCipherOperation(
int mode, byte[] iv, byte[] encryptKey, byte[] text) throws CipherException {
try {
IvParameterSpec ivParameterSpec = new IvParameterSpec(iv);
Cipher cipher = Cipher.getInstance("AES/CTR/NoPadding");
SecretKeySpec secretKeySpec = new SecretKeySpec(encryptKey, "AES");
cipher.init(mode, secretKeySpec, ivParameterSpec);
return cipher.doFinal(text);
} catch (NoSuchPaddingException | NoSuchAlgorithmException
| InvalidAlgorithmParameterException | InvalidKeyException
| BadPaddingException | IllegalBlockSizeException e) {
throw new CipherException("Error performing cipher operation", e);
}
}
public ClientTrustManager(KeyStore trustTrust) {
super();
this.trustStore = trustTrust;
//Note: A reference of the Collection is used in the CertStore, so we can add CRL's
// after creating the CertStore.
crls = new ArrayList<>();
CollectionCertStoreParameters params = new CollectionCertStoreParameters(crls);
try {
crlStore = CertStore.getInstance("Collection", params);
}
catch (InvalidAlgorithmParameterException | NoSuchAlgorithmException ex) {
Log.warn("ClientTrustManager: ",ex);
}
loadCRL();
}
/**
* Sets the {@code Set} of most-trusted CAs.
* <p>
* Note that the {@code Set} is copied to protect against
* subsequent modifications.
*
* @param trustAnchors a {@code Set} of {@code TrustAnchor}s
* @throws InvalidAlgorithmParameterException if the specified
* {@code Set} is empty {@code (trustAnchors.isEmpty() == true)}
* @throws NullPointerException if the specified {@code Set} is
* {@code null}
* @throws ClassCastException if any of the elements in the set
* are not of type {@code java.security.cert.TrustAnchor}
*
* @see #getTrustAnchors
*/
public void setTrustAnchors(Set<TrustAnchor> trustAnchors)
throws InvalidAlgorithmParameterException
{
if (trustAnchors == null) {
throw new NullPointerException("the trustAnchors parameters must" +
" be non-null");
}
if (trustAnchors.isEmpty()) {
throw new InvalidAlgorithmParameterException("the trustAnchors " +
"parameter must be non-empty");
}
for (Iterator<TrustAnchor> i = trustAnchors.iterator(); i.hasNext(); ) {
if (!(i.next() instanceof TrustAnchor)) {
throw new ClassCastException("all elements of set must be "
+ "of type java.security.cert.TrustAnchor");
}
}
this.unmodTrustAnchors = Collections.unmodifiableSet
(new HashSet<TrustAnchor>(trustAnchors));
}
@Test
public void testDeleteKeyPair()
throws KeyStoreException,
InvalidAlgorithmParameterException,
NoSuchAlgorithmException,
NoSuchProviderException,
NoSuchKeyException {
try {
AndroidKeyStoreRsaUtils.deleteKeyPair(keyStore, KEYCHAIN_ID, false);
fail("Did not throw NoSuchKeyException");
} catch (NoSuchKeyException e) {
// This is expected.
}
AndroidKeyStoreRsaUtils.generateKeyPair(context, KEYCHAIN_ID, false);
assertEquals(1, keyStore.size());
AndroidKeyStoreRsaUtils.deleteKeyPair(keyStore, KEYCHAIN_ID, false);
assertEquals(0, keyStore.size());
}
/**
* Sets the {@code Set} of most-trusted CAs.
* <p>
* Note that the {@code Set} is copied to protect against
* subsequent modifications.
*
* @param trustAnchors a {@code Set} of {@code TrustAnchor}s
* @throws InvalidAlgorithmParameterException if the specified
* {@code Set} is empty {@code (trustAnchors.isEmpty() == true)}
* @throws NullPointerException if the specified {@code Set} is
* {@code null}
* @throws ClassCastException if any of the elements in the set
* are not of type {@code java.security.cert.TrustAnchor}
*
* @see #getTrustAnchors
*/
public void setTrustAnchors(Set<TrustAnchor> trustAnchors)
throws InvalidAlgorithmParameterException
{
if (trustAnchors == null) {
throw new NullPointerException("the trustAnchors parameters must" +
" be non-null");
}
if (trustAnchors.isEmpty()) {
throw new InvalidAlgorithmParameterException("the trustAnchors " +
"parameter must be non-empty");
}
for (Iterator<TrustAnchor> i = trustAnchors.iterator(); i.hasNext(); ) {
if (!(i.next() instanceof TrustAnchor)) {
throw new ClassCastException("all elements of set must be "
+ "of type java.security.cert.TrustAnchor");
}
}
this.unmodTrustAnchors = Collections.unmodifiableSet
(new HashSet<TrustAnchor>(trustAnchors));
}
@Override
protected void initCipher(int mode) throws InvalidKeyException,
InvalidAlgorithmParameterException, InvalidParameterSpecException {
if (Cipher.ENCRYPT_MODE == mode) {
ci.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(key.getEncoded(),
KEY_ALGORITHM));
iv = ci.getParameters().getParameterSpec(IvParameterSpec.class)
.getIV();
} else {
ci.init(Cipher.DECRYPT_MODE, new SecretKeySpec(key.getEncoded(),
KEY_ALGORITHM), new IvParameterSpec(iv));
}
}
private byte[] encrypt(byte[] key, IvParameterSpec iv, byte[] payload) throws InvalidAlgorithmParameterException, InvalidKeyException,
IOException, NoSuchPaddingException, NoSuchAlgorithmException, BadPaddingException, IllegalBlockSizeException {
SecretKey secretKey = new SecretKeySpec(key, "AES");
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, secretKey, iv);
return cipher.doFinal(payload);
}
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 byte[] decrypt_CBC_NoPadding(byte[] key, byte[] iv, byte[] cipherText)
throws IllegalBlockSizeException, BadPaddingException, InvalidKeyException,
NoSuchAlgorithmException, NoSuchProviderException, NoSuchPaddingException,
InvalidAlgorithmParameterException {
Cipher cipher = generateCBCCipher(ALGORITHM_NAME_CBC_NOPADDING, Cipher.DECRYPT_MODE, key, iv);
return cipher.doFinal(cipherText);
}
public static KeyPair generateDSAKeypair(int plength, int qlength, SecureRandom random)
throws NoSuchAlgorithmException, NoSuchProviderException, InvalidAlgorithmParameterException {
DSAParameterSpec dsaParamSpec = DSAParameterCache.getDSAParameterSpec(plength, qlength,
random);
KeyPairGenerator kpGen = getKeyPairGenerator("DSA");
synchronized (kpGen) {
kpGen.initialize(dsaParamSpec, random);
return kpGen.generateKeyPair();
}
}
protected void engineInit(
AlgorithmParameterSpec genParamSpec,
SecureRandom random)
throws InvalidAlgorithmParameterException
{
throw new InvalidAlgorithmParameterException("No supported AlgorithmParameterSpec for GOST3410 parameter generation.");
}
private void initTrafoChannel() throws IOException {
try {
// create temp file in default temp directory
this.tmpFile = File.createTempFile("encfs-", ".dat");
this.tmpFile.deleteOnExit();
if (this.isReadingRequired) {
// encrypt/decrypt everything from persistentChannel if the
// persistent file content should be read
Cipher cipher = this
.getCipher(this.isReverse ? Cipher.ENCRYPT_MODE
: Cipher.DECRYPT_MODE);
this.persistentChannel.position(0);
// this is where encryption/decryption takes place in the
// beginning based on CipherOutputStream
this.copyStream(
Channels.newInputStream(this.persistentChannel),
new CipherOutputStream(new FileOutputStream(
this.tmpFile), cipher));
}
this.trafoFile = new RandomAccessFile(this.tmpFile, "rw");
this.trafoChannel = this.trafoFile.getChannel();
// read/write on trafoChannel now
} catch (InvalidKeyException | NoSuchAlgorithmException
| DigestException | NoSuchPaddingException
| InvalidAlgorithmParameterException e) {
throw new IOException(e.getMessage(), e);
}
}
@Test
public void testWithRealm() throws NoSuchAlgorithmException, InvalidAlgorithmParameterException, KeyException,
TransformerException, MarshalException, XMLSignatureException {
service.setIssuerBase("http://local.slidev.org:8082/simple-idp");
List<String> roles = Arrays.asList("role1", "role2");
Map<String, String> attributes = new HashMap<String, String>();
Mockito.when(
samlComposer.componseResponse("destUri", "http://local.slidev.org:8082/simple-idp?realm=realm",
"request_id", "unique_id", attributes, roles)).thenReturn("samlResponse");
Request request = Mockito.mock(AuthRequestService.Request.class);
Mockito.when(request.getRequestId()).thenReturn("request_id");
Mockito.when(request.getRealm()).thenReturn("realm");
Mockito.when(request.getDestination()).thenReturn("destUri");
User user = Mockito.mock(User.class);
Mockito.when(user.getUserId()).thenReturn("unique_id");
service.buildAssertion("unique_id", roles, attributes, request);
Mockito.verify(samlComposer).componseResponse("destUri", "http://local.slidev.org:8082/simple-idp?realm=realm",
"request_id", "unique_id", attributes, roles);
}
protected void engineInit(
Key key,
AlgorithmParameterSpec params,
SecureRandom random)
throws InvalidKeyException, InvalidAlgorithmParameterException
{
if (!(key instanceof DHPrivateKey))
{
throw new InvalidKeyException("DHKeyAgreement requires DHPrivateKey for initialisation");
}
DHPrivateKey privKey = (DHPrivateKey)key;
if (params != null)
{
if (!(params instanceof DHParameterSpec))
{
throw new InvalidAlgorithmParameterException("DHKeyAgreement only accepts DHParameterSpec");
}
DHParameterSpec p = (DHParameterSpec)params;
this.p = p.getP();
this.g = p.getG();
}
else
{
this.p = privKey.getParams().getP();
this.g = privKey.getParams().getG();
}
this.x = this.result = privKey.getX();
}
private static void checkParam(AlgorithmParameters param,
DSAGenParameterSpec genParam) throws InvalidParameterSpecException,
NoSuchAlgorithmException, NoSuchProviderException,
InvalidAlgorithmParameterException {
String algorithm = param.getAlgorithm();
if (!algorithm.equalsIgnoreCase(ALGORITHM_NAME)) {
throw new RuntimeException(
"Unexpected type of parameters: " + algorithm);
}
DSAParameterSpec spec = param.getParameterSpec(DSAParameterSpec.class);
int valueL = spec.getP().bitLength();
int strengthP = genParam.getPrimePLength();
if (strengthP != valueL) {
System.out.printf("P: Expected %d but actual %d%n", strengthP,
valueL);
throw new RuntimeException("Wrong P strength");
}
int valueN = spec.getQ().bitLength();
int strengthQ = genParam.getSubprimeQLength();
if (strengthQ != valueN) {
System.out.printf("Q: Expected %d but actual %d%n", strengthQ,
valueN);
throw new RuntimeException("Wrong Q strength");
}
if (genParam.getSubprimeQLength() != genParam.getSeedLength()) {
System.out.println("Defaut seed length should be the same as Q.");
throw new RuntimeException("Wrong seed length");
}
KeyPairGenerator keyGen = KeyPairGenerator.getInstance(ALGORITHM_NAME,
PROVIDER_NAME);
keyGen.initialize(spec);
}
private DecryptedState decrypt(char[] password) throws DatabaseImporterException {
try {
// WARNING: DON'T DO THIS IN YOUR OWN CODE
// this is not a secure way to derive a key from a password
MessageDigest hash = MessageDigest.getInstance("SHA-256");
byte[] keyBytes = hash.digest(CryptoUtils.toBytes(password));
SecretKey key = new SecretKeySpec(keyBytes, "AES");
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS7Padding");
IvParameterSpec spec = new IvParameterSpec(IV);
cipher.init(Cipher.DECRYPT_MODE, key, spec);
byte[] bytes = cipher.doFinal(_data);
JSONObject obj = new JSONObject(new String(bytes, StandardCharsets.UTF_8));
JSONArray keys = obj.names();
List<JSONObject> entries = new ArrayList<>();
if (keys != null && keys.length() > 0) {
entries = parse((String) keys.get(0));
}
return new DecryptedState(entries);
} catch (NoSuchAlgorithmException
| NoSuchPaddingException
| InvalidAlgorithmParameterException
| InvalidKeyException
| BadPaddingException
| IllegalBlockSizeException
| JSONException e) {
throw new DatabaseImporterException(e);
}
}
@Override
public VerifyCredentialResponse verifyTiedProfileChallenge(String credential, int type,
long challenge, int userId) throws RemoteException {
checkPasswordReadPermission(userId);
if (!isManagedProfileWithUnifiedLock(userId)) {
throw new RemoteException("User id must be managed profile with unified lock");
}
final int parentProfileId = mUserManager.getProfileParent(userId).id;
// Unlock parent by using parent's challenge
final VerifyCredentialResponse parentResponse = doVerifyCredential(
credential,
type,
true /* hasChallenge */,
challenge,
parentProfileId,
null /* progressCallback */);
if (parentResponse.getResponseCode() != VerifyCredentialResponse.RESPONSE_OK) {
// Failed, just return parent's response
return parentResponse;
}
try {
// Unlock work profile, and work profile with unified lock must use password only
return doVerifyCredential(getDecryptedPasswordForTiedProfile(userId),
LockPatternUtils.CREDENTIAL_TYPE_PASSWORD,
true,
challenge,
userId, null /* progressCallback */);
} catch (UnrecoverableKeyException | InvalidKeyException | KeyStoreException
| NoSuchAlgorithmException | NoSuchPaddingException
| InvalidAlgorithmParameterException | IllegalBlockSizeException
| BadPaddingException | CertificateException | IOException e) {
Slog.e(TAG, "Failed to decrypt child profile key", e);
throw new RemoteException("Unable to get tied profile token");
}
}
public void init(TransformParameterSpec params)
throws InvalidAlgorithmParameterException
{
if (params == null) {
throw new InvalidAlgorithmParameterException("params are required");
} else if (!(params instanceof XPathFilterParameterSpec)) {
throw new InvalidAlgorithmParameterException
("params must be of type XPathFilterParameterSpec");
}
this.params = params;
}
/**
* Creates a <code>CertStore</code> with the specified parameters.
* For this class, the parameters object must be an instance of
* <code>CollectionCertStoreParameters</code>.
*
* @param params the algorithm parameters
* @exception InvalidAlgorithmParameterException if params is not an
* instance of <code>CollectionCertStoreParameters</code>
*/
public IndexedCollectionCertStore(CertStoreParameters params)
throws InvalidAlgorithmParameterException {
super(params);
if (!(params instanceof CollectionCertStoreParameters)) {
throw new InvalidAlgorithmParameterException(
"parameters must be CollectionCertStoreParameters");
}
Collection<?> coll = ((CollectionCertStoreParameters)params).getCollection();
if (coll == null) {
throw new InvalidAlgorithmParameterException
("Collection must not be null");
}
buildIndex(coll);
}
ValidatorParams(CertPath cp, PKIXParameters params)
throws InvalidAlgorithmParameterException
{
this(params);
if (!cp.getType().equals("X.509") && !cp.getType().equals("X509")) {
throw new InvalidAlgorithmParameterException("inappropriate "
+ "CertPath type specified, must be X.509 or X509");
}
this.certPath = cp;
}
static ValidatorParams checkParams(CertPath cp, CertPathParameters params)
throws InvalidAlgorithmParameterException
{
if (!(params instanceof PKIXParameters)) {
throw new InvalidAlgorithmParameterException("inappropriate "
+ "params, must be an instance of PKIXParameters");
}
return new ValidatorParams(cp, (PKIXParameters)params);
}
@Override
protected void initCipher(int mode) throws InvalidKeyException,
InvalidAlgorithmParameterException, InvalidParameterSpecException {
if (Cipher.ENCRYPT_MODE == mode) {
ci.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(key.getEncoded(),
KEY_ALGORITHM));
iv = ci.getParameters().getParameterSpec(IvParameterSpec.class)
.getIV();
} else {
ci.init(Cipher.DECRYPT_MODE, new SecretKeySpec(key.getEncoded(),
KEY_ALGORITHM), new IvParameterSpec(iv));
}
}