List of usage examples for org.bouncycastle.x509 X509V1CertificateGenerator generateX509Certificate
public X509Certificate generateX509Certificate(PrivateKey key) throws SecurityException, SignatureException, InvalidKeyException
From source file:org.tranche.security.SecurityUtil.java
License:Apache License
/** * <p>Helper method that uses the bouncycastle.org's X509 certificate generator to make a certificate for the given public/private key pair.</p> * @param name/*from ww w . j a va 2 s. c om*/ * @param pub * @param priv * @return * @throws java.security.GeneralSecurityException */ public static Certificate createCertificate(String name, PublicKey pub, PrivateKey priv) throws GeneralSecurityException { lazyLoad(); // make a new certificate X509V1CertificateGenerator gen = new X509V1CertificateGenerator(); Hashtable attrs = new Hashtable(); attrs.put(X509Principal.CN, name); attrs.put(X509Principal.OU, "Default DFS Website"); attrs.put(X509Principal.O, "Certificate Auto-Generator"); attrs.put(X509Principal.L, "Ann Arbor"); attrs.put(X509Principal.ST, "Michigan"); attrs.put(X509Principal.C, "US"); Date firstDate = new Date(); // Set back startdate ten minutes to avoid some problems with wrongly set clocks. firstDate.setTime(firstDate.getTime() - 10 * 60 * 1000); Date lastDate = new Date(); // validity in days = validity*24*60*60*1000 milliseconds lastDate.setTime(lastDate.getTime() + (60 * (24 * 60 * 60 * 1000))); // Serialnumber is random bits, where random generator is initialized with Date.getTime() byte[] serno = new byte[8]; SecureRandom random = SecureRandom.getInstance("SHA1PRNG"); random.setSeed((new Date().getTime())); random.nextBytes(serno); BigInteger sn = new java.math.BigInteger(serno).abs(); // make the principle X509Principal principal = new X509Principal(attrs); //generate cert gen.setSerialNumber(sn); gen.setIssuerDN(principal); gen.setNotBefore(firstDate); gen.setNotAfter(lastDate); gen.setSubjectDN(principal); gen.setSignatureAlgorithm("SHA1WITHRSA"); gen.setPublicKey(pub); return gen.generateX509Certificate(priv); }