List of usage examples for org.bouncycastle.jce.provider BouncyCastleProvider BouncyCastleProvider
public BouncyCastleProvider()
From source file:com.alu.e3.prov.security.InitSslProvider.java
License:Apache License
public InitSslProvider() { super(); Security.addProvider(new BouncyCastleProvider()); }
From source file:com.alu.e3.security.BaseStoreFileService.java
License:Apache License
public void init() { Security.addProvider(new BouncyCastleProvider()); File f = new File(storePath); if (f.exists()) { f.delete();/*from w w w .j a v a 2s. c o m*/ } FileOutputStream out = null; try { KeyStore ks = KeyStore.getInstance("BKS"); ks.load(null, storePassword.toCharArray()); out = new FileOutputStream(f); ks.store(out, storePassword.toCharArray()); } catch (Exception e) { if (logger.isErrorEnabled()) { logger.error("Unable to create the store", e); } } finally { if (out != null) { try { out.close(); } catch (IOException e) { // Nothing to do } } } }
From source file:com.amazonaws.service.iot.mqttloadapp.SslUtil.java
License:Open Source License
public static SSLSocketFactory getSocketFactory(final String caCrtFile, final String crtFile, final String keyFile, final String password) throws Exception { Security.addProvider(new BouncyCastleProvider()); // load CA certificate PEMReader reader = new PEMReader( new InputStreamReader(new ByteArrayInputStream(getBytesFromFile(caCrtFile)))); X509Certificate caCert = (X509Certificate) reader.readObject(); reader.close();//from w w w . j a v a 2 s . co m // load client certificate reader = new PEMReader(new InputStreamReader(new ByteArrayInputStream(getBytesFromFile(crtFile)))); X509Certificate cert = (X509Certificate) reader.readObject(); reader.close(); // load client private key reader = new PEMReader(new InputStreamReader(new ByteArrayInputStream(getBytesFromFile(keyFile))), new PasswordFinder() { @Override public char[] getPassword() { return password.toCharArray(); } }); KeyPair key = (KeyPair) reader.readObject(); reader.close(); // CA certificate is used to authenticate server KeyStore caKs = KeyStore.getInstance(KeyStore.getDefaultType()); caKs.load(null, null); caKs.setCertificateEntry("ca-certificate", caCert); TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); tmf.init(caKs); // client key and certificates are sent to server so it can authenticate us KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType()); ks.load(null, null); ks.setCertificateEntry("certificate", cert); ks.setKeyEntry("private-key", key.getPrivate(), password.toCharArray(), new java.security.cert.Certificate[] { cert }); KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); kmf.init(ks, password.toCharArray()); // finally, create SSL socket factory SSLContext context = SSLContext.getInstance(System.getProperty("tlsversion", "TLSv1.2")); context.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null); return context.getSocketFactory(); }
From source file:com.amazonaws.services.dynamodbv2.datamodeling.encryption.DynamoDBEncryptorTest.java
License:Open Source License
private EncryptionMaterialsProvider getMaterialProviderwithECDSA() throws NoSuchAlgorithmException, InvalidAlgorithmParameterException, NoSuchProviderException { Security.addProvider(new BouncyCastleProvider()); ECParameterSpec ecSpec = ECNamedCurveTable.getParameterSpec("secp384r1"); KeyPairGenerator g = KeyPairGenerator.getInstance("ECDSA", "BC"); g.initialize(ecSpec, Utils.getRng()); KeyPair keypair = g.generateKeyPair(); Map<String, String> description = new HashMap<String, String>(); description.put(DynamoDBEncryptor.DEFAULT_SIGNING_ALGORITHM_HEADER, "SHA384withECDSA"); return new SymmetricStaticProvider(null, keypair, description); }
From source file:com.amazonaws.services.dynamodbv2.datamodeling.encryption.DynamoDBSignerTest.java
License:Open Source License
@BeforeClass public static void setUpClass() throws Exception { //RSA key generation KeyPairGenerator rsaGen = KeyPairGenerator.getInstance("RSA"); rsaGen.initialize(2048, Utils.getRng()); KeyPair sigPair = rsaGen.generateKeyPair(); pubKeyRsa = sigPair.getPublic();/*from w w w .ja v a 2 s.c o m*/ privKeyRsa = sigPair.getPrivate(); KeyGenerator macGen = KeyGenerator.getInstance("HmacSHA256"); macGen.init(256, Utils.getRng()); macKey = macGen.generateKey(); Security.addProvider(new BouncyCastleProvider()); ECParameterSpec ecSpec = ECNamedCurveTable.getParameterSpec("secp384r1"); KeyPairGenerator g = KeyPairGenerator.getInstance("ECDSA", "BC"); g.initialize(ecSpec, Utils.getRng()); KeyPair keypair = g.generateKeyPair(); pubKeyEcdsa = keypair.getPublic(); privKeyEcdsa = keypair.getPrivate(); }
From source file:com.amazonaws.services.iot.demo.danbo.rpi.SslUtil.java
License:Open Source License
public static SSLSocketFactory getSslSocketFactory(final String caCrtFile, final String crtFile, final String keyFile, final String password) throws InvalidPathException, IOException, KeyStoreException, NoSuchAlgorithmException, CertificateException, UnrecoverableKeyException, KeyManagementException, Exception { Security.addProvider(new BouncyCastleProvider()); // load CA certificate PEMParser parser = new PEMParser( new InputStreamReader(new ByteArrayInputStream(Files.readAllBytes(Paths.get(caCrtFile))))); X509CertificateHolder caCert = (X509CertificateHolder) parser.readObject(); parser.close();//w w w . jav a 2 s. c o m // load client certificate parser = new PEMParser( new InputStreamReader(new ByteArrayInputStream(Files.readAllBytes(Paths.get(crtFile))))); X509CertificateHolder cert = (X509CertificateHolder) parser.readObject(); parser.close(); // load client private key parser = new PEMParser( new InputStreamReader(new ByteArrayInputStream(Files.readAllBytes(Paths.get(keyFile))))); Object obj = parser.readObject(); KeyPair key = null; JcaPEMKeyConverter converter = new JcaPEMKeyConverter().setProvider("BC"); if (obj instanceof PEMEncryptedKeyPair) { PEMDecryptorProvider decProv = new JcePEMDecryptorProviderBuilder().build(password.toCharArray()); converter = new JcaPEMKeyConverter().setProvider("BC"); key = converter.getKeyPair(((PEMEncryptedKeyPair) obj).decryptKeyPair(decProv)); } else { key = converter.getKeyPair((PEMKeyPair) obj); } parser.close(); JcaX509CertificateConverter certConverter = new JcaX509CertificateConverter(); certConverter.setProvider("BC"); // CA certificate is used to authenticate server KeyStore caKs = KeyStore.getInstance(KeyStore.getDefaultType()); caKs.load(null, null); caKs.setCertificateEntry("ca-certificate", certConverter.getCertificate(caCert)); TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); tmf.init(caKs); // Client key and certificates are sent to server so it can authenticate // us KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType()); ks.load(null, null); ks.setCertificateEntry("certificate", certConverter.getCertificate(cert)); ks.setKeyEntry("private-key", key.getPrivate(), password.toCharArray(), new java.security.cert.Certificate[] { certConverter.getCertificate(cert) }); KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); kmf.init(ks, password.toCharArray()); // Finally, create SSL socket factory SSLContext context = SSLContext.getInstance("TLSv1.2"); context.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null); return context.getSocketFactory(); }
From source file:com.android.builder.internal.packaging.sign.SignatureTestUtils.java
License:Apache License
/** * Generates a private key / certificate. * * @param sign the asymmetric cypher, <em>e.g.</em>, {@code RSA} * @param full the full signature algorithm name, <em>e.g.</em>, {@code SHA1withRSA} * @return the pair with the private key and certificate * @throws Exception failed to generate the signature data *///from w ww . j a v a 2 s . c o m @NonNull public static Pair<PrivateKey, X509Certificate> generateSignature(@NonNull String sign, @NonNull String full) throws Exception { // http://stackoverflow.com/questions/28538785/ // easy-way-to-generate-a-self-signed-certificate-for-java-security-keystore-using KeyPairGenerator generator = null; try { generator = KeyPairGenerator.getInstance(sign); } catch (NoSuchAlgorithmException e) { Assume.assumeNoException("Algorithm " + sign + " not supported.", e); } assertNotNull(generator); KeyPair keyPair = generator.generateKeyPair(); Date notBefore = new Date(System.currentTimeMillis() - 24 * 60 * 60 * 1000); Date notAfter = new Date(System.currentTimeMillis() + 365L * 24 * 60 * 60 * 1000); X500Name issuer = new X500Name(new X500Principal("cn=Myself").getName()); SubjectPublicKeyInfo publicKeyInfo; if (keyPair.getPublic() instanceof RSAPublicKey) { RSAPublicKey rsaPublicKey = (RSAPublicKey) keyPair.getPublic(); publicKeyInfo = SubjectPublicKeyInfoFactory.createSubjectPublicKeyInfo( new RSAKeyParameters(false, rsaPublicKey.getModulus(), rsaPublicKey.getPublicExponent())); } else if (keyPair.getPublic() instanceof ECPublicKey) { publicKeyInfo = SubjectPublicKeyInfo.getInstance(keyPair.getPublic().getEncoded()); } else { fail(); publicKeyInfo = null; } X509v1CertificateBuilder builder = new X509v1CertificateBuilder(issuer, BigInteger.ONE, notBefore, notAfter, issuer, publicKeyInfo); ContentSigner signer = new JcaContentSignerBuilder(full).setProvider(new BouncyCastleProvider()) .build(keyPair.getPrivate()); X509CertificateHolder holder = builder.build(signer); JcaX509CertificateConverter converter = new JcaX509CertificateConverter() .setProvider(new BouncyCastleProvider()); return Pair.of(keyPair.getPrivate(), converter.getCertificate(holder)); }
From source file:com.android.dumpkey.DumpPublicKey.java
License:Apache License
public static void main(String[] args) { if (args.length < 1) { System.err.println("Usage: DumpPublicKey certfile ... > source.c"); System.exit(1);//from w w w. ja v a 2 s . c o m } Security.addProvider(new BouncyCastleProvider()); try { for (int i = 0; i < args.length; i++) { FileInputStream input = new FileInputStream(args[i]); CertificateFactory cf = CertificateFactory.getInstance("X.509"); X509Certificate cert = (X509Certificate) cf.generateCertificate(input); boolean useSHA256 = false; String sigAlg = cert.getSigAlgName(); if ("SHA1withRSA".equals(sigAlg) || "MD5withRSA".equals(sigAlg)) { // SignApk has historically accepted "MD5withRSA" // certificates, but treated them as "SHA1withRSA" // anyway. Continue to do so for backwards // compatibility. useSHA256 = false; } else if ("SHA256withRSA".equals(sigAlg) || "SHA256withECDSA".equals(sigAlg)) { useSHA256 = true; } else { System.err.println(args[i] + ": unsupported signature algorithm \"" + sigAlg + "\""); System.exit(1); } PublicKey key = cert.getPublicKey(); check(key, useSHA256); System.out.print(print(key, useSHA256)); System.out.println(i < args.length - 1 ? "," : ""); } } catch (Exception e) { e.printStackTrace(); System.exit(1); } System.exit(0); }
From source file:com.android.ide.common.signing.KeystoreHelper.java
License:Apache License
/** * Generates a key and self-signed certificate pair. * @param asymmetric the asymmetric encryption algorithm (<em>e.g.,</em> {@code RSA}) * @param sign the signature algorithm (<em>e.g.,</em> {@code SHA1withRSA}) * @param validityYears number of years the certificate should be valid, must be greater than * zero/*from w ww . ja va 2 s . c o m*/ * @param dn the distinguished name of the issuer and owner of the certificate * @return a pair with the private key and the corresponding certificate * @throws KeytoolException failed to generate the pair */ private static Pair<PrivateKey, X509Certificate> generateKeyAndCertificate(@NonNull String asymmetric, @NonNull String sign, int validityYears, @NonNull String dn) throws KeytoolException { Preconditions.checkArgument(validityYears > 0, "validityYears <= 0"); KeyPair keyPair; try { keyPair = KeyPairGenerator.getInstance(asymmetric).generateKeyPair(); } catch (NoSuchAlgorithmException e) { throw new KeytoolException( "Failed to generate key and certificate pair for " + "algorithm '" + asymmetric + "'.", e); } Date notBefore = new Date(System.currentTimeMillis()); Date notAfter = new Date(System.currentTimeMillis() + validityYears * 365L * 24 * 60 * 60 * 1000); X500Name issuer = new X500Name(new X500Principal(dn).getName()); SubjectPublicKeyInfo publicKeyInfo = SubjectPublicKeyInfo.getInstance(keyPair.getPublic().getEncoded()); X509v1CertificateBuilder builder = new X509v1CertificateBuilder(issuer, BigInteger.ONE, notBefore, notAfter, issuer, publicKeyInfo); ContentSigner signer; try { signer = new JcaContentSignerBuilder(sign).setProvider(new BouncyCastleProvider()) .build(keyPair.getPrivate()); } catch (OperatorCreationException e) { throw new KeytoolException("Failed to build content signer with signature algorithm '" + sign + "'.", e); } X509CertificateHolder holder = builder.build(signer); JcaX509CertificateConverter converter = new JcaX509CertificateConverter() .setProvider(new BouncyCastleProvider()); X509Certificate certificate; try { certificate = converter.getCertificate(holder); } catch (CertificateException e) { throw new KeytoolException("Failed to obtain the self-signed certificate.", e); } return Pair.of(keyPair.getPrivate(), certificate); }
From source file:com.android.signapk.SignApk.java
License:Apache License
public static void main(String[] args) { if (args.length < 4) usage();//from www. j av a 2 s . c o m sBouncyCastleProvider = new BouncyCastleProvider(); Security.addProvider(sBouncyCastleProvider); boolean signWholeFile = false; String providerClass = null; String providerArg = null; int alignment = 4; int argstart = 0; while (argstart < args.length && args[argstart].startsWith("-")) { if ("-w".equals(args[argstart])) { signWholeFile = true; ++argstart; } else if ("-providerClass".equals(args[argstart])) { if (argstart + 1 >= args.length) { usage(); } providerClass = args[++argstart]; ++argstart; } else if ("-a".equals(args[argstart])) { alignment = Integer.parseInt(args[++argstart]); ++argstart; } else { usage(); } } if ((args.length - argstart) % 2 == 1) usage(); int numKeys = ((args.length - argstart) / 2) - 1; if (signWholeFile && numKeys > 1) { System.err.println("Only one key may be used with -w."); System.exit(2); } loadProviderIfNecessary(providerClass); String inputFilename = args[args.length - 2]; String outputFilename = args[args.length - 1]; JarFile inputJar = null; FileOutputStream outputFile = null; int hashes = 0; try { File firstPublicKeyFile = new File(args[argstart + 0]); X509Certificate[] publicKey = new X509Certificate[numKeys]; try { for (int i = 0; i < numKeys; ++i) { int argNum = argstart + i * 2; publicKey[i] = readPublicKey(new File(args[argNum])); hashes |= getDigestAlgorithm(publicKey[i]); } } catch (IllegalArgumentException e) { System.err.println(e); System.exit(1); } // Set the ZIP file timestamp to the starting valid time // of the 0th certificate plus one hour (to match what // we've historically done). long timestamp = publicKey[0].getNotBefore().getTime() + 3600L * 1000; PrivateKey[] privateKey = new PrivateKey[numKeys]; for (int i = 0; i < numKeys; ++i) { int argNum = argstart + i * 2 + 1; privateKey[i] = readPrivateKey(new File(args[argNum])); } inputJar = new JarFile(new File(inputFilename), false); // Don't verify. outputFile = new FileOutputStream(outputFilename); if (signWholeFile) { SignApk.signWholeFile(inputJar, firstPublicKeyFile, publicKey[0], privateKey[0], outputFile); } else { JarOutputStream outputJar = new JarOutputStream(outputFile); // For signing .apks, use the maximum compression to make // them as small as possible (since they live forever on // the system partition). For OTA packages, use the // default compression level, which is much much faster // and produces output that is only a tiny bit larger // (~0.1% on full OTA packages I tested). outputJar.setLevel(9); Manifest manifest = addDigestsToManifest(inputJar, hashes); copyFiles(manifest, inputJar, outputJar, timestamp, alignment); signFile(manifest, inputJar, publicKey, privateKey, outputJar); outputJar.close(); } } catch (Exception e) { e.printStackTrace(); System.exit(1); } finally { try { if (inputJar != null) inputJar.close(); if (outputFile != null) outputFile.close(); } catch (IOException e) { e.printStackTrace(); System.exit(1); } } }