org.spongycastle.operator.jcajce.JcaContentSignerBuilder Java Examples

The following examples show how to use org.spongycastle.operator.jcajce.JcaContentSignerBuilder. 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: EditServerActivity.java    From revolution-irc with GNU General Public License v3.0 6 votes vote down vote up
private void generateCert() throws Exception {
    KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
    keyPairGenerator.initialize(2048);
    KeyPair kp = keyPairGenerator.generateKeyPair();

    X500Name name = new X500Name("CN=Revolution IRC Client Certificate");
    BigInteger serial = new BigInteger(64, new SecureRandom());
    Date from = new Date();
    Date to = new Date(from.getTime() + 30L * 365L * 24L * 60L * 60L * 1000L);
    X509v3CertificateBuilder builder = new X509v3CertificateBuilder(name, serial, from, to, name, SubjectPublicKeyInfo.getInstance(kp.getPublic().getEncoded()));
    ContentSigner signer = new JcaContentSignerBuilder("SHA256WithRSA").build(kp.getPrivate());
    X509CertificateHolder holder = builder.build(signer);


    CertificateFactory factory = CertificateFactory.getInstance("X.509");
    mServerCert = (X509Certificate) factory.generateCertificate(
            new ByteArrayInputStream(holder.getEncoded()));
    mServerPrivKey = kp.getPrivate().getEncoded();
    mServerPrivKeyType = kp.getPrivate().getAlgorithm();
    mServerAuthSASLExtFP.setText(getString(R.string.server_sasl_ext_fp,
            getCertificateFingerprint(mServerCert)));
}
 
Example #2
Source File: SignatureBlockGenerator.java    From java-n-IDE-for-Android with Apache License 2.0 5 votes vote down vote up
/**
 * Sign the given content using the private and public keys from the keySet, and return the encoded CMS (PKCS#7) data.
 * Use of direct signature and DER encoding produces a block that is verifiable by Android recovery programs.
 */
public static byte[] generate(KeySet keySet, byte[] content) {
    try {
        List certList = new ArrayList();
        CMSTypedData msg = new CMSProcessableByteArray(content);

        certList.add(keySet.getPublicKey());

        Store certs = new JcaCertStore(certList);

        CMSSignedDataGenerator gen = new CMSSignedDataGenerator();

        JcaContentSignerBuilder jcaContentSignerBuilder = new JcaContentSignerBuilder(keySet.getSignatureAlgorithm()).setProvider("SC");
        ContentSigner sha1Signer = jcaContentSignerBuilder.build(keySet.getPrivateKey());

        JcaDigestCalculatorProviderBuilder jcaDigestCalculatorProviderBuilder = new JcaDigestCalculatorProviderBuilder().setProvider("SC");
        DigestCalculatorProvider digestCalculatorProvider = jcaDigestCalculatorProviderBuilder.build();

        JcaSignerInfoGeneratorBuilder jcaSignerInfoGeneratorBuilder = new JcaSignerInfoGeneratorBuilder( digestCalculatorProvider);
        jcaSignerInfoGeneratorBuilder.setDirectSignature(true);
        SignerInfoGenerator signerInfoGenerator = jcaSignerInfoGeneratorBuilder.build(sha1Signer, keySet.getPublicKey());

        gen.addSignerInfoGenerator( signerInfoGenerator);

        gen.addCertificates(certs);

        CMSSignedData sigData = gen.generate(msg, false);
        return sigData.toASN1Structure().getEncoded("DER");

    } catch (Exception x) {
        throw new RuntimeException(x.getMessage(), x);
    }
}
 
Example #3
Source File: TlsHelper.java    From an2linuxclient with GNU General Public License v3.0 5 votes vote down vote up
static void initialiseCertificate(Context c, KeyPair keyPair){
    Calendar calendar = Calendar.getInstance();
    calendar.add(Calendar.DAY_OF_MONTH, -1);
    Date notBefore = calendar.getTime();
    calendar.add(Calendar.YEAR, 10);
    Date notAfter = calendar.getTime();

    X500NameBuilder nameBuilder = new X500NameBuilder(BCStyle.INSTANCE);
    nameBuilder.addRDN(BCStyle.CN, "an2linuxclient");
    nameBuilder.addRDN(BCStyle.SERIALNUMBER, new BigInteger(128, new Random()).toString(16));

    X509v3CertificateBuilder certificateBuilder = new JcaX509v3CertificateBuilder(
            nameBuilder.build(),
            BigInteger.ONE,
            notBefore, notAfter,
            nameBuilder.build(),
            keyPair.getPublic()
    );
    try {
        ContentSigner contentSigner = new JcaContentSignerBuilder("SHA256WithRSAEncryption").build(keyPair.getPrivate());
        X509Certificate certificate = new JcaX509CertificateConverter().getCertificate(certificateBuilder.build(contentSigner));

        SharedPreferences deviceKeyPref = c.getSharedPreferences(
                c.getString(R.string.device_key_and_cert), MODE_PRIVATE);
        deviceKeyPref.edit().putString(c.getString(R.string.certificate),
                Base64.encodeToString(certificate.getEncoded(), Base64.NO_WRAP)).apply();
        Log.d("TlsHelper", "Generated new certificate successfully");
    } catch (Exception e){
        Log.e("TlsHelper", "initialiseCertificate");
        Log.e("StackTrace", Log.getStackTraceString(e));
    }
}
 
Example #4
Source File: TlsHelper.java    From an2linuxclient with GNU General Public License v3.0 5 votes vote down vote up
static void initialiseCertificate(Context c, KeyPair keyPair){
    Calendar calendar = Calendar.getInstance();
    calendar.add(Calendar.DAY_OF_MONTH, -1);
    Date notBefore = calendar.getTime();
    calendar.add(Calendar.YEAR, 10);
    Date notAfter = calendar.getTime();

    X500NameBuilder nameBuilder = new X500NameBuilder(BCStyle.INSTANCE);
    nameBuilder.addRDN(BCStyle.CN, "an2linuxclient");
    nameBuilder.addRDN(BCStyle.SERIALNUMBER, new BigInteger(128, new Random()).toString(16));

    X509v3CertificateBuilder certificateBuilder = new JcaX509v3CertificateBuilder(
            nameBuilder.build(),
            BigInteger.ONE,
            notBefore, notAfter,
            nameBuilder.build(),
            keyPair.getPublic()
    );
    try {
        ContentSigner contentSigner = new JcaContentSignerBuilder("SHA256WithRSAEncryption").build(keyPair.getPrivate());
        X509Certificate certificate = new JcaX509CertificateConverter().getCertificate(certificateBuilder.build(contentSigner));

        SharedPreferences deviceKeyPref = c.getSharedPreferences(
                c.getString(R.string.device_key_and_cert), MODE_PRIVATE);
        deviceKeyPref.edit().putString(c.getString(R.string.certificate),
                Base64.encodeToString(certificate.getEncoded(), Base64.NO_WRAP)).apply();
        Log.d("TlsHelper", "Generated new certificate successfully");
    } catch (Exception e){
        Log.e("TlsHelper", "initialiseCertificate");
        Log.e("StackTrace", Log.getStackTraceString(e));
    }
}
 
Example #5
Source File: ModSSL.java    From spydroid-ipcamera with GNU General Public License v3.0 5 votes vote down vote up
public static X509Certificate generateSignedCertificate(X509Certificate caCertificate, PrivateKey caPrivateKey, PublicKey publicKey, String CN) 
		throws NoSuchAlgorithmException, OperatorCreationException, CertificateException, 
		KeyStoreException, UnrecoverableKeyException, IOException, 
		InvalidKeyException, NoSuchPaddingException, InvalidParameterSpecException, 
		InvalidKeySpecException, InvalidAlgorithmParameterException, IllegalBlockSizeException, 
		BadPaddingException {

	X500NameBuilder builder = new X500NameBuilder(BCStyle.INSTANCE);

	builder.addRDN(BCStyle.CN, CN);

	// We want this root certificate to be valid for one year
	Calendar calendar = Calendar.getInstance();
	calendar.add(Calendar.YEAR, 1);

	ContentSigner sigGen = new JcaContentSignerBuilder("SHA1WithRSAEncryption").setProvider(BC).build(caPrivateKey);
	X509v3CertificateBuilder certGen = new JcaX509v3CertificateBuilder(
			caCertificate, 
			new BigInteger(80, new Random()), 
			new Date(System.currentTimeMillis() - 50000),
			calendar.getTime(),
			new X500Principal(builder.build().getEncoded()),
			publicKey);

	// Those are the extensions needed for the certificate to be a leaf certificate that authenticates a SSL server
	certGen.addExtension(new ASN1ObjectIdentifier("2.5.29.15"), true, new X509KeyUsage(X509KeyUsage.keyEncipherment));
	certGen.addExtension(new ASN1ObjectIdentifier("2.5.29.37"), true, new DERSequence(KeyPurposeId.id_kp_serverAuth));

	X509CertificateHolder certificateHolder = certGen.build(sigGen);
	X509Certificate certificate = new JcaX509CertificateConverter().setProvider(BC).getCertificate(certificateHolder);

	return certificate;

}
 
Example #6
Source File: ModSSL.java    From spydroid-ipcamera with GNU General Public License v3.0 5 votes vote down vote up
public static X509Certificate generateRootCertificate(KeyPair keys, String CN) 
		throws NoSuchAlgorithmException, OperatorCreationException, CertificateException, 
		KeyStoreException, UnrecoverableKeyException, IOException, 
		InvalidKeyException, NoSuchPaddingException, InvalidParameterSpecException, 
		InvalidKeySpecException, InvalidAlgorithmParameterException, IllegalBlockSizeException, 
		BadPaddingException {

	X500NameBuilder builder = new X500NameBuilder(BCStyle.INSTANCE);

	builder.addRDN(BCStyle.CN, CN);

	// We want this root certificate to be valid for one year 
	Calendar calendar = Calendar.getInstance();
	calendar.add( Calendar.YEAR, 1 );

	ContentSigner sigGen = new JcaContentSignerBuilder("SHA1WithRSAEncryption").setProvider(BC).build(keys.getPrivate());
	X509v3CertificateBuilder certGen = new JcaX509v3CertificateBuilder(
			builder.build(), 
			new BigInteger(80, new Random()), 
			new Date(System.currentTimeMillis() - 50000),
			calendar.getTime(),
			builder.build(),
			keys.getPublic());

	// Those are the extensions needed for a CA certificate
	certGen.addExtension(new ASN1ObjectIdentifier("2.5.29.19"), true, new BasicConstraints(true));
	certGen.addExtension(new ASN1ObjectIdentifier("2.5.29.15"), true, new X509KeyUsage(X509KeyUsage.digitalSignature));
	certGen.addExtension(new ASN1ObjectIdentifier("2.5.29.37"), true, new ExtendedKeyUsage(KeyPurposeId.id_kp_serverAuth));

	X509CertificateHolder certificateHolder = certGen.build(sigGen);

	X509Certificate certificate = new JcaX509CertificateConverter().setProvider(BC).getCertificate(certificateHolder);

	return certificate;

}
 
Example #7
Source File: JumbleCertificateGenerator.java    From Jumble with GNU General Public License v3.0 5 votes vote down vote up
public static X509Certificate generateCertificate(OutputStream output) throws NoSuchAlgorithmException, OperatorCreationException, CertificateException, KeyStoreException, NoSuchProviderException, IOException {
	BouncyCastleProvider provider = new BouncyCastleProvider(); // Use SpongyCastle provider, supports creating X509 certs
	KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA");
	generator.initialize(2048, new SecureRandom());
	
	KeyPair keyPair = generator.generateKeyPair();
	
	SubjectPublicKeyInfo publicKeyInfo = SubjectPublicKeyInfo.getInstance(keyPair.getPublic().getEncoded());
	ContentSigner signer = new JcaContentSignerBuilder("SHA1withRSA").setProvider(provider).build(keyPair.getPrivate());
	
	Date startDate = new Date();
	Calendar calendar = Calendar.getInstance();
	calendar.setTime(startDate);
	calendar.add(Calendar.YEAR, YEARS_VALID);
    Date endDate = calendar.getTime();
	
	X509v3CertificateBuilder certBuilder = new X509v3CertificateBuilder(new X500Name(ISSUER),
			BigInteger.ONE, 
			startDate, endDate, new X500Name(ISSUER),
			publicKeyInfo);

	X509CertificateHolder certificateHolder = certBuilder.build(signer);
	
	X509Certificate certificate = new JcaX509CertificateConverter().setProvider(provider).getCertificate(certificateHolder);
	
	KeyStore keyStore = KeyStore.getInstance("PKCS12", provider);
	keyStore.load(null, null);
	keyStore.setKeyEntry("Jumble Key", keyPair.getPrivate(), null, new X509Certificate[] { certificate });
	
	keyStore.store(output, "".toCharArray());
	
	return certificate;
}