java.security.NoSuchProviderException Java Examples
The following examples show how to use
java.security.NoSuchProviderException.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: LTI13KeySetTest.java From sakai with Educational Community License v2.0 | 6 votes |
@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); }
Example #2
Source File: TestDSAGenParameterSpec.java From openjdk-jdk8u-backup with GNU General Public License v2.0 | 6 votes |
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); } }
Example #3
Source File: UnexpectedNPE.java From jdk8u-jdk with GNU General Public License v2.0 | 6 votes |
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; }
Example #4
Source File: TSet.java From Clusion with GNU General Public License v3.0 | 6 votes |
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; }
Example #5
Source File: TestData.java From UAF with Apache License 2.0 | 6 votes |
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")); }
Example #6
Source File: KeyStoreUtil.java From CapturePacket with MIT License | 6 votes |
/** * 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; }
Example #7
Source File: X509CertificateObject.java From RipplePower with Apache License 2.0 | 6 votes |
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); }
Example #8
Source File: SecretKeyBackupHelperTest.java From Smack with Apache License 2.0 | 6 votes |
@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())); }
Example #9
Source File: KeyStoreUtil.java From Dream-Catcher with MIT License | 6 votes |
/** * 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); } }
Example #10
Source File: SignatureUtils.java From freehealth-connector with GNU Affero General Public License v3.0 | 6 votes |
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); } } }
Example #11
Source File: MDSJwtVerifier.java From fido2 with GNU Lesser General Public License v2.1 | 6 votes |
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"); } }
Example #12
Source File: TokenCreator.java From cf-java-logging-support with Apache License 2.0 | 6 votes |
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()); } }
Example #13
Source File: IdentityController.java From Spark with Apache License 2.0 | 6 votes |
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; }
Example #14
Source File: X509V1CertificateGenerator.java From ripple-lib-java with ISC License | 6 votes |
/** * 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); }
Example #15
Source File: TLSCompatSocketFactory.java From bitmask_android with GNU General Public License v3.0 | 5 votes |
private void initForSelfSignedCAs(String trustedSelfSignedCaCert) throws KeyStoreException, CertificateException, NoSuchAlgorithmException, IOException, IllegalStateException, KeyManagementException, NoSuchProviderException { // Create a KeyStore containing our trusted CAs String defaultType = KeyStore.getDefaultType(); KeyStore keyStore = KeyStore.getInstance(defaultType); keyStore.load(null, null); if (!TextUtils.isEmpty(trustedSelfSignedCaCert)) { java.security.cert.Certificate provider_certificate = ConfigHelper.parseX509CertificateFromString(trustedSelfSignedCaCert); keyStore.setCertificateEntry("provider_ca_certificate", provider_certificate); } // Create a TrustManager that trusts the CAs in our KeyStore String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm(); TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm); tmf.init(keyStore); // Check if there's only 1 X509Trustmanager -> from okttp3 source code example TrustManager[] trustManagers = tmf.getTrustManagers(); if (trustManagers.length != 1 || !(trustManagers[0] instanceof X509TrustManager)) { throw new IllegalStateException("Unexpected default trust managers:" + Arrays.toString(trustManagers)); } trustManager = trustManagers[0]; // Create a SSLContext that uses our TrustManager SSLContext sslContext = SSLContext.getInstance("TLS"); sslContext.init(null, tmf.getTrustManagers(), null); internalSSLSocketFactory = sslContext.getSocketFactory(); }
Example #16
Source File: AESSensitivePropertyProvider.java From nifi with Apache License 2.0 | 5 votes |
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); } }
Example #17
Source File: ECKeyFactory.java From aion with MIT License | 5 votes |
public static KeyFactory getInstance(final String provider) throws NoSuchProviderException { try { return KeyFactory.getInstance(ALGORITHM, provider); } catch (NoSuchAlgorithmException ex) { throw new AssertionError(algorithmAssertionMsg, ex); } }
Example #18
Source File: X509V1CertificateGenerator.java From TorrentEngine with GNU General Public License v3.0 | 5 votes |
/** * 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); }
Example #19
Source File: clientUtilAuth.java From fido2 with GNU Lesser General Public License v2.1 | 5 votes |
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); }
Example #20
Source File: KeyStoreTestUtil.java From big-c with Apache License 2.0 | 5 votes |
@SuppressWarnings("deprecation") /** * Create a self-signed X.509 Certificate. * * @param dn the X.509 Distinguished Name, eg "CN=Test, L=London, C=GB" * @param pair the KeyPair * @param days how many days from now the Certificate is valid for * @param algorithm the signing algorithm, eg "SHA1withRSA" * @return the self-signed certificate */ public static X509Certificate generateCertificate(String dn, KeyPair pair, int days, String algorithm) throws CertificateEncodingException, InvalidKeyException, IllegalStateException, NoSuchProviderException, NoSuchAlgorithmException, SignatureException{ Date from = new Date(); Date to = new Date(from.getTime() + days * 86400000l); BigInteger sn = new BigInteger(64, new SecureRandom()); KeyPair keyPair = pair; X509V1CertificateGenerator certGen = new X509V1CertificateGenerator(); X500Principal dnName = new X500Principal(dn); certGen.setSerialNumber(sn); certGen.setIssuerDN(dnName); certGen.setNotBefore(from); certGen.setNotAfter(to); certGen.setSubjectDN(dnName); certGen.setPublicKey(keyPair.getPublic()); certGen.setSignatureAlgorithm(algorithm); X509Certificate cert = certGen.generate(pair.getPrivate()); return cert; }
Example #21
Source File: OauthDouban.java From mblog with GNU General Public License v3.0 | 5 votes |
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; }
Example #22
Source File: KeyStoreUtils.java From guarda-android-wallets with GNU General Public License v3.0 | 5 votes |
private byte[] rsaEncrypt(byte[] secret) throws NoSuchAlgorithmException, UnrecoverableEntryException, KeyStoreException, NoSuchProviderException, NoSuchPaddingException, InvalidKeyException, IOException { KeyStore.PrivateKeyEntry privateKeyEntry = (KeyStore.PrivateKeyEntry) keyStore.getEntry(KEY_ALIAS, null); // Encrypt the text Cipher inputCipher = Cipher.getInstance(RSA_MODE, "AndroidOpenSSL"); inputCipher.init(Cipher.ENCRYPT_MODE, privateKeyEntry.getCertificate().getPublicKey()); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); CipherOutputStream cipherOutputStream = new CipherOutputStream(outputStream, inputCipher); cipherOutputStream.write(secret); cipherOutputStream.close(); byte[] vals = outputStream.toByteArray(); return vals; }
Example #23
Source File: UnknownProvider.java From openjdk-jdk9 with GNU General Public License v2.0 | 5 votes |
public static void main(String[] args) throws NoSuchAlgorithmException { try { TransformService ts = TransformService.getInstance( Transform.BASE64, "DOM", "SomeProviderThatDoesNotExist"); } catch(NoSuchProviderException e) { // this is expected } }
Example #24
Source File: cryptoCommon.java From fido2 with GNU Lesser General Public License v2.1 | 5 votes |
public static X509Certificate generateX509FromInputStream(InputStream instr) { try { CertificateFactory certFactory = CertificateFactory.getInstance("X.509", "BCFIPS"); return (X509Certificate) certFactory.generateCertificate(instr); } catch (CertificateException | NoSuchProviderException ex) { logp(Level.SEVERE, classname, "generateX509FromBytes", "CRYPTO-MSG-1000", printStackTrace(ex)); } return null; }
Example #25
Source File: BCECUtil.java From gmhelper with Apache License 2.0 | 5 votes |
public static KeyPair generateKeyPair(ECDomainParameters domainParameters, SecureRandom random) throws NoSuchProviderException, NoSuchAlgorithmException, InvalidAlgorithmParameterException { KeyPairGenerator kpg = KeyPairGenerator.getInstance(ALGO_NAME_EC, BouncyCastleProvider.PROVIDER_NAME); ECParameterSpec parameterSpec = new ECParameterSpec(domainParameters.getCurve(), domainParameters.getG(), domainParameters.getN(), domainParameters.getH()); kpg.initialize(parameterSpec, random); return kpg.generateKeyPair(); }
Example #26
Source File: PackedAttestationStatement.java From fido2 with GNU Lesser General Public License v2.1 | 5 votes |
@Override public byte[] signwithCredentialKey(PrivateKey pvtKey, byte[] tbs) { try { Signature sig = Signature.getInstance("SHA256withECDSA", "BCFIPS"); sig.initSign(pvtKey, new SecureRandom()); sig.update(tbs); signature = sig.sign(); return signature; } catch (InvalidKeyException | NoSuchAlgorithmException | NoSuchProviderException | SignatureException ex) { Logger.getLogger(PackedAttestationStatement.class.getName()).log(Level.SEVERE, null, ex); return null; } }
Example #27
Source File: ECKeyAgreement.java From wkcwallet-java with Apache License 2.0 | 5 votes |
public static KeyAgreement getInstance(final String provider) throws NoSuchProviderException { try { return KeyAgreement.getInstance(ALGORITHM, provider); } catch (NoSuchAlgorithmException ex) { throw new AssertionError(algorithmAssertionMsg, ex); } }
Example #28
Source File: P12Manager.java From web3sdk with Apache License 2.0 | 5 votes |
public void load() throws KeyStoreException, NoSuchAlgorithmException, CertificateException, IOException, NoSuchProviderException { ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver(); keyStore = KeyStore.getInstance("PKCS12", "BC"); Resource keyStoreResource = resolver.getResource(p12File); keyStore.load(keyStoreResource.getInputStream(), password.toCharArray()); // logger.debug(" p12 load, keyStore: {}", keyStore); }
Example #29
Source File: BiometricManagerV23.java From smart-farmer-android with Apache License 2.0 | 5 votes |
void generateKey() { try { keyStore = KeyStore.getInstance("AndroidKeyStore"); keyStore.load(null); //第二次启动的时候,如果存在key就不用再次创建了 if (!keyStore.containsAlias(KEY_NAME)) { keyGenerator = KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES, "AndroidKeyStore"); keyGenerator.init(new KeyGenParameterSpec.Builder(KEY_NAME, KeyProperties.PURPOSE_ENCRYPT | KeyProperties.PURPOSE_DECRYPT) .setBlockModes(KeyProperties.BLOCK_MODE_CBC) .setUserAuthenticationRequired(true) .setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_PKCS7) .build()); keyGenerator.generateKey(); } } catch (KeyStoreException | NoSuchAlgorithmException | NoSuchProviderException | InvalidAlgorithmParameterException | CertificateException | IOException exc) { exc.printStackTrace(); } }
Example #30
Source File: CipherFactory.java From chvote-1-0 with GNU Affero General Public License v3.0 | 5 votes |
/** * Returns an instance of Cipher for the given algorithm * <p/> * The Security Provider is chosen depending on the algorithm * * @return an instance of Cipher */ public Cipher getInstance(String algo) { Preconditions.checkNotNull(algo); try { final String provider = providerByAlgo.get(algo); return Cipher.getInstance(algo, provider); } catch (NoSuchAlgorithmException | NoSuchProviderException | NoSuchPaddingException e) { throw new CryptoConfigurationRuntimeException("Error creating Cipher", e); } }