Search in sources :

Example 1 with KeyPairGenerator

use of java.security.KeyPairGenerator in project OpenAttestation by OpenAttestation.

the class CertificateUtils method generateSelfSignedX509Certificate.

/**
	 * Generate a self signed X509 certificate with Bouncy Castle.
	 * @throws SignatureException 
	 * @throws IllegalStateException 
	 * @throws InvalidKeyException 
	 * @throws CertificateEncodingException 
	 */
public static X509Certificate generateSelfSignedX509Certificate() throws NoSuchAlgorithmException, NoSuchProviderException, CertificateEncodingException, InvalidKeyException, IllegalStateException, SignatureException {
    Security.addProvider(new BouncyCastleProvider());
    int validityDays = 3652;
    // GENERATE THE PUBLIC/PRIVATE RSA KEY PAIR
    KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA", "BC");
    keyPairGenerator.initialize(1024, new SecureRandom());
    KeyPair keyPair = keyPairGenerator.generateKeyPair();
    // GENERATE THE X509 CERTIFICATE
    X509V1CertificateGenerator certGen = new X509V1CertificateGenerator();
    X500Principal dnName = new X500Principal("CN=OATServer");
    certGen.setSerialNumber(BigInteger.valueOf(System.currentTimeMillis()));
    certGen.setSubjectDN(dnName);
    // use the same
    certGen.setIssuerDN(dnName);
    certGen.setNotBefore(new java.sql.Time(System.currentTimeMillis()));
    Calendar expiry = Calendar.getInstance();
    expiry.add(Calendar.DAY_OF_YEAR, validityDays);
    certGen.setNotAfter(expiry.getTime());
    certGen.setPublicKey(keyPair.getPublic());
    certGen.setSignatureAlgorithm("SHA256WithRSAEncryption");
    X509Certificate cert = certGen.generate(keyPair.getPrivate(), "BC");
    return cert;
}
Also used : KeyPair(java.security.KeyPair) X509V1CertificateGenerator(org.bouncycastle.x509.X509V1CertificateGenerator) Calendar(java.util.Calendar) SecureRandom(java.security.SecureRandom) X500Principal(javax.security.auth.x500.X500Principal) KeyPairGenerator(java.security.KeyPairGenerator) X509Certificate(java.security.cert.X509Certificate) BouncyCastleProvider(org.bouncycastle.jce.provider.BouncyCastleProvider)

Example 2 with KeyPairGenerator

use of java.security.KeyPairGenerator in project neo4j by neo4j.

the class Certificates method createSelfSignedCertificate.

public void createSelfSignedCertificate(File certificatePath, File privateKeyPath, String hostName) throws GeneralSecurityException, IOException, OperatorCreationException {
    installCleanupHook(certificatePath, privateKeyPath);
    KeyPairGenerator keyGen = KeyPairGenerator.getInstance(DEFAULT_ENCRYPTION);
    keyGen.initialize(2048, random);
    KeyPair keypair = keyGen.generateKeyPair();
    // Prepare the information required for generating an X.509 certificate.
    X500Name owner = new X500Name("CN=" + hostName);
    X509v3CertificateBuilder builder = new JcaX509v3CertificateBuilder(owner, new BigInteger(64, random), NOT_BEFORE, NOT_AFTER, owner, keypair.getPublic());
    PrivateKey privateKey = keypair.getPrivate();
    ContentSigner signer = new JcaContentSignerBuilder("SHA512WithRSAEncryption").build(privateKey);
    X509CertificateHolder certHolder = builder.build(signer);
    X509Certificate cert = new JcaX509CertificateConverter().setProvider(PROVIDER).getCertificate(certHolder);
    //check so that cert is valid
    cert.verify(keypair.getPublic());
    //write to disk
    writePem("CERTIFICATE", cert.getEncoded(), certificatePath);
    writePem("PRIVATE KEY", privateKey.getEncoded(), privateKeyPath);
    // Mark as done so we don't clean up certificates
    cleanupRequired = false;
}
Also used : KeyPair(java.security.KeyPair) PrivateKey(java.security.PrivateKey) JcaX509v3CertificateBuilder(org.bouncycastle.cert.jcajce.JcaX509v3CertificateBuilder) X509v3CertificateBuilder(org.bouncycastle.cert.X509v3CertificateBuilder) JcaContentSignerBuilder(org.bouncycastle.operator.jcajce.JcaContentSignerBuilder) JcaX509CertificateConverter(org.bouncycastle.cert.jcajce.JcaX509CertificateConverter) JcaX509v3CertificateBuilder(org.bouncycastle.cert.jcajce.JcaX509v3CertificateBuilder) X509CertificateHolder(org.bouncycastle.cert.X509CertificateHolder) ContentSigner(org.bouncycastle.operator.ContentSigner) BigInteger(java.math.BigInteger) KeyPairGenerator(java.security.KeyPairGenerator) X500Name(org.bouncycastle.asn1.x500.X500Name) X509Certificate(java.security.cert.X509Certificate)

Example 3 with KeyPairGenerator

use of java.security.KeyPairGenerator in project OpenAM by OpenRock.

the class JwtGenerator method main.

public static void main(String[] args) throws Exception {
    if (args.length != 3) {
        System.out.println("Usage: JwtGenerator <subject> <issuer> <audience>");
        System.exit(1);
    }
    KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
    keyGen.initialize(512);
    KeyPair keyPair = keyGen.genKeyPair();
    PublicKey publicKey = keyPair.getPublic();
    long validTime = System.currentTimeMillis() + 1000 * 60 * 60 * 24 / 2;
    String jwt = new JwtBuilderFactory().jws(new SigningManager().newRsaSigningHandler(keyPair.getPrivate())).headers().alg(JwsAlgorithm.RS256).done().claims(new JwtClaimsSet(json(object(field("iss", args[0]), field("sub", args[1]), field("aud", args[2]), field("exp", validTime / 1000))).asMap())).build();
    System.out.println("JWT: " + jwt);
    Calendar expiry = Calendar.getInstance();
    expiry.add(Calendar.DAY_OF_YEAR, 7);
    X509CertInfo info = new X509CertInfo();
    CertificateValidity interval = new CertificateValidity(new Date(), new Date(validTime));
    BigInteger sn = new BigInteger(64, new SecureRandom());
    X500Name owner = new X500Name("CN=ForgeRock,L=Bristol,C=GB");
    info.set(X509CertInfo.VALIDITY, interval);
    info.set(X509CertInfo.SERIAL_NUMBER, new CertificateSerialNumber(sn));
    info.set(X509CertInfo.SUBJECT, new CertificateSubjectName(owner));
    info.set(X509CertInfo.ISSUER, new CertificateIssuerName(owner));
    info.set(X509CertInfo.KEY, new CertificateX509Key(publicKey));
    info.set(X509CertInfo.VERSION, new CertificateVersion(CertificateVersion.V3));
    AlgorithmId algo = new AlgorithmId(AlgorithmId.sha256WithRSAEncryption_oid);
    info.set(X509CertInfo.ALGORITHM_ID, new CertificateAlgorithmId(algo));
    // Sign the cert to identify the algorithm that's used.
    X509CertImpl cert = new X509CertImpl(info);
    cert.sign(keyPair.getPrivate(), "SHA256withRSA");
    System.out.println("Certificate:");
    BASE64Encoder encoder = new BASE64Encoder();
    System.out.println(X509Factory.BEGIN_CERT);
    encoder.encodeBuffer(cert.getEncoded(), System.out);
    System.out.println(X509Factory.END_CERT);
}
Also used : JwtBuilderFactory(org.forgerock.json.jose.builders.JwtBuilderFactory) CertificateSubjectName(sun.security.x509.CertificateSubjectName) KeyPair(java.security.KeyPair) X509CertInfo(sun.security.x509.X509CertInfo) PublicKey(java.security.PublicKey) Calendar(java.util.Calendar) CertificateIssuerName(sun.security.x509.CertificateIssuerName) BASE64Encoder(sun.misc.BASE64Encoder) SecureRandom(java.security.SecureRandom) CertificateVersion(sun.security.x509.CertificateVersion) CertificateValidity(sun.security.x509.CertificateValidity) KeyPairGenerator(java.security.KeyPairGenerator) X500Name(sun.security.x509.X500Name) CertificateX509Key(sun.security.x509.CertificateX509Key) SigningManager(org.forgerock.json.jose.jws.SigningManager) Date(java.util.Date) CertificateSerialNumber(sun.security.x509.CertificateSerialNumber) JwtClaimsSet(org.forgerock.json.jose.jwt.JwtClaimsSet) CertificateAlgorithmId(sun.security.x509.CertificateAlgorithmId) AlgorithmId(sun.security.x509.AlgorithmId) X509CertImpl(sun.security.x509.X509CertImpl) BigInteger(java.math.BigInteger) CertificateAlgorithmId(sun.security.x509.CertificateAlgorithmId)

Example 4 with KeyPairGenerator

use of java.security.KeyPairGenerator in project OpenAM by OpenRock.

the class KeyPairProviderImpl method newKeyPair.

private KeyPair newKeyPair(String algorithm, int keySize) {
    try {
        KeyPairGenerator generator = KeyPairGenerator.getInstance(algorithm);
        generator.initialize(keySize);
        return generator.generateKeyPair();
    } catch (NoSuchAlgorithmException nsaE) {
        throw new IllegalArgumentException("Unsupported key algorithm " + algorithm, nsaE);
    }
}
Also used : KeyPairGenerator(java.security.KeyPairGenerator) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException)

Example 5 with KeyPairGenerator

use of java.security.KeyPairGenerator in project OpenAM by OpenRock.

the class JwtSessionMapperTest method newKeyPair.

/**
     * Generate a random RSA public-private key pair.
     *
     * @return The public-private KeyPair.
     */
static KeyPair newKeyPair() {
    try {
        KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
        keyPairGenerator.initialize(1024);
        return keyPairGenerator.generateKeyPair();
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
        return null;
    }
}
Also used : KeyPairGenerator(java.security.KeyPairGenerator) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException)

Aggregations

KeyPairGenerator (java.security.KeyPairGenerator)492 KeyPair (java.security.KeyPair)341 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)122 SecureRandom (java.security.SecureRandom)91 Test (org.junit.Test)79 PrivateKey (java.security.PrivateKey)74 PublicKey (java.security.PublicKey)62 X509Certificate (java.security.cert.X509Certificate)58 IOException (java.io.IOException)53 BigInteger (java.math.BigInteger)44 Date (java.util.Date)44 GeneralSecurityException (java.security.GeneralSecurityException)42 RSAPublicKey (java.security.interfaces.RSAPublicKey)41 X500Principal (javax.security.auth.x500.X500Principal)36 ECPublicKey (java.security.interfaces.ECPublicKey)34 KeyStore (java.security.KeyStore)33 KeyFactory (java.security.KeyFactory)31 ECPrivateKey (java.security.interfaces.ECPrivateKey)31 RSAPrivateKey (java.security.interfaces.RSAPrivateKey)30 InvalidAlgorithmParameterException (java.security.InvalidAlgorithmParameterException)29