Bouncycastle Signature authentication CA mechanism
Package com.ideal.mdm.cert.service;
Import Java.io.BufferedReader;
Import java.io.IOException;
Import Java.io.InputStream;
Import Java.io.InputStreamReader;
Import Java.math.BigInteger;
Import java.security.InvalidKeyException;
Import Java.security.KeyFactory;
Import Java.security.KeyPair;
Import java.security.NoSuchAlgorithmException;
Import java.security.NoSuchProviderException;
Import Java.security.PrivateKey;
Import Java.security.PublicKey;
Import java.security.Security;
Import java.security.SignatureException;
Import java.security.cert.CertStoreException;
Import java.security.cert.CertificateException;
Import Java.security.cert.CertificateFactory;
Import Java.security.cert.X509Certificate;
Import java.security.spec.InvalidKeySpecException;
Import Java.security.spec.RSAPublicKeySpec;
Import Java.util.Calendar;
Import Java.util.Date;
Import Java.util.GregorianCalendar; Import java.uTil.
Random;
Import Javax.security.auth.x500.X500Principal;
Import Org.apache.log4j.Logger;
Import Org.bouncycastle.asn1.ASN1EncodableVector;
Import org.bouncycastle.asn1.ASN1Sequence;
Import org.bouncycastle.asn1.DEROctetString;
Import org.bouncycastle.asn1.DERSequence;
Import Org.bouncycastle.asn1.x500.X500Name;
Import Org.bouncycastle.asn1.x500.X500NameStyle;
Import org.bouncycastle.asn1.x509.BasicConstraints;
Import Org.bouncycastle.asn1.x509.ExtendedKeyUsage;
Import org.bouncycastle.asn1.x509.Extension;
Import Org.bouncycastle.asn1.x509.GeneralName;
Import Org.bouncycastle.asn1.x509.KeyPurposeId;
Import Org.bouncycastle.asn1.x509.KeyUsage;
Import Org.bouncycastle.asn1.x509.SubjectPublicKeyInfo;
Import org.bouncycastle.asn1.x509.X509Extension;
Import Org.bouncycastle.cert.X509CertificateHolder;
Import Org.bouncycastle.cert.jcajce.JcaX509CertificateConverter; Import Org.bouncycastle.cert.jcajce.JcaX509v3CerTificatebuilder;
Import Org.bouncycastle.crypto.params.RSAKeyParameters;
Import Org.bouncycastle.crypto.util.PublicKeyFactory;
Import Org.bouncycastle.openssl.PEMReader;
Import Org.bouncycastle.operator.ContentSigner;
Import org.bouncycastle.operator.OperatorCreationException;
Import Org.bouncycastle.operator.jcajce.JcaContentSignerBuilder;
Import Org.bouncycastle.pkcs.PKCS10CertificationRequest;
Import org.jscep.client.ClientException;
Import Org.jscep.transaction.FailInfo;
Import org.jscep.transaction.OperationFailureException;
Import org.jscep.transaction.TransactionException;
Import Com.ideal.mdm.cert.util.WinBCStyle;
Import Sun.misc.BASE64Decoder;
public class Scepcertservice {protected static final Logger Logger = Logger.getlogger (Scepcertservice.class);
private static Privatekey Prikey;
private static PublicKey PubKey;
private static X509Certificate CA; private static X500name isSuer;
private static X500name Pollname;
private static BigInteger caserial; public static X509Certificate mainsigncsrprocedure (String b64dercsr) throws NoSuchAlgorithmException, Signatur Eexception, InvalidKeyException, Nosuchproviderexception, Clientexception, Operatorcreationexcepti
On, TransactionException, Certificateexception, Certstoreexception, IOException, invalidkeyspecexception {
Init ();
Base64decoder decoder = new Base64decoder ();
Byte[] DERCSR;
PublicKey Csrpubkey;
Dercsr=decoder.decodebuffer (B64DERCSR);
Csrpubkey = Geneneratepublickey (DERCSR);
X509Certificate Issued=doenrol (Csrpubkey);
return issued;
Pemreader pemreader = null;
/*try {FileReader FileReader = new FileReader (Csrpath);
Pemreader = new Pemreader (FileReader); catch (FilenotFoundexception E1) {e1.printstacktrace ();
Logger.debug (E1.getmessage ());
}*//*pkcs10certificationrequest CSR = null; try {CSR = new Pkcs10certificationrequest (Pemreader.readpemobject (). GetContent ()
);
catch (IOException e) {e.printstacktrace ();
Logger.debug (E.getmessage ());
}*/} protected static X509Certificate Doenrol (PublicKey csrpubkey) throws Operationfailureexception {
try {//x500name origin_subject = x500name.getinstance (Csr.getsubject ());
/*if (Subject.equals (pollname)) {return collections.emptylist ();
}*///logger.debug (origin_subject.tostring ());
New X500name ();
PrintableString ps=new printablestring (""); X500principal X500name NEW_subject=new X500name (winbcstyle.instance, "cn=idealmobile01");
New_subject instanceof printablestring;
New_subject.getrdns () [0].
PublicKey PubKey = Certificationrequestutils.getpublickey (CSR);
X509Certificate issued = Generatecertificate (Csrpubkey, New_subject, issuer, getserial ());
return issued;
catch (Exception e) {logger.debug (E.getmessage ());
throw new Operationfailureexception (failinfo.badrequest); }} private static X509Certificate generatecertificate (PublicKey pubkey, x500name subject, X5 00Name issuer, BigInteger serial) throws Exception {Calendar cal = Gregoriancalendar.getinstance (
);
Cal.add (Calendar.year,-1);
Date Notbefore = Cal.gettime ();
Cal.add (Calendar.year, 2);
Date notafter = Cal.gettime (); Jcax509v3certificatebuilder builder = new Jcax509v3certificatebuilder (issuer, serial, Notbefore, notAf
ter, subject, pubkey);
Builder.addextension (X509extension.basicconstraints, True, new Basicconstraints (false));
Extendedkeyusage anyextendedkeyusage = new Extendedkeyusage (keypurposeid.anyextendedkeyusage);
X509extension anyextendedkeyusageextension = new X509extension (False, New deroctetstring (Anyextendedkeyusage));
Builder.addextension (X509extension.extendedkeyusage, True, Anyextendedkeyusageextension.getparsedvalue ());
Asn1encodablevector asn1extkeyusage = new Asn1encodablevector (); Asn1extkeyusage.add (Keypurposeid.anyextendedkeyusage); Any use//Asn1extkeyusage.add (Keypurposeid.id_kp_serverauth); SSL Server Authentication Asn1extkeyusage.add (Keypurposeid.id_kp_clientauth); SSL client Authentication//Asn1extkeyusage.add (keypurposeid.id_kp_codesigning); Code Signature//ASN1extkeyusage.add (keypurposeid.id_kp_codesigning); Code Signature//Asn1extkeyusage.add (Keypurposeid.id_kp_ipsecendsystem); Asn1extkeyusage.add (Keypurposeid.id_kp_ipsectunnel); Asn1extkeyusage.add (Keypurposeid.id_kp_ipsecuser); Asn1extkeyusage.add (keypurposeid.id_kp_timestamping); Time stamp Certification//Asn1extkeyusage.add (keypurposeid.id_kp_ocspsigning);
OCSP Certificate Certification//Asn1extkeyusage.add (Keypurposeid.id_kp_smartcardlogon);
Asn1extkeyusage.add (New Generalname (Generalname.dnsname, "ejbca.linyiheng.cn"));
Extendedkeyusage extendedkeyusage = new Extendedkeyusage (new Dersequence (asn1extkeyusage));
Builder.addextension (Extension.extendedkeyusage, True, extendedkeyusage); Builder.addextension (Extension.subjectalternativename, True, arg2) keyusage keyusage= new Keyusage (KeyUsage.dig
Italsignature); X509extension keyusageextension = new X509extension (True, new deroctetstring (Keyusage));
Builder.addextension (X509extension.keyusage, True, Keyusageextension.getparsedvalue ());
Contentsigner signer;
try {signer = new Jcacontentsignerbuilder ("Sha1withrsa"). Build (Prikey);
catch (Operatorcreationexception e) {logger.debug (E.getmessage ());
throw new Exception (e);
} X509certificateholder holder = Builder.build (signer);
X509Certificate cert = new Jcax509certificateconverter (). getcertificate (holder);
Savepemfile ("/root/certificate/client.crt", cert);
Logger.debug ("Cert ' s issuer DN is:" +cert);
return cert; }//private static void Savepemfile (String path, Object obj) throws IOException {//FileWriter FW = new F
Ilewriter (path);
Pemwriter writer = new Pemwriter (FW);
Writer.writeobject (obj);
Writer.close (); public static void Init () {try {CA = loadlocalCertificate ();
Bouncycastlehelpers.tox500name (Ca.getsubjectx500principal ());
New X500name ((asn1sequence) Ca.getissuerdn ());
New X500name (); New X500name (Ca.getsubjectx500principal ().
RFC1779);
Logger.debug ("CA ' issuer is:" + ca.getsubjectx500principal (). GetName ());
Logger.debug ("CA ' issuer is:" + ca.getsubjectx500principal (). GetName (x500principal.rfc1779));
Logger.debug ("CA ' issuer is:" + ca.getsubjectx500principal (). GetName (x500principal.rfc2253));
Logger.debug ("CA ' issuer is:" + ca.getsubjectx500principal (). GetName (x500principal.canonical)); Issuer = new X500name (winbcstyle.instance, "c=cn,st=sh,l=sh,o=ideal,ou=ideal,cn=host.linyiheng.cn,emailaddress=
Linyiheng123@sina.com ");
Pollname = new X500name ("Cn=poll2");
Caserial = Biginteger.ten;
BufferedReader br = new BufferedReader (New InputStreamReader ( New Scepcertservice (). GetClass (). getResourceAsStream ("/ca.key"));
Pemreader localpemreader=new Pemreader (BR); Pemreader Localpemreader = new Pemreader (BR, New Passwordfinder () {////public char[] G
Etpassword () {//return "1111". ToCharArray ();
// }
//
// });
Security.addprovider (New Org.bouncycastle.jce.provider.BouncyCastleProvider ());
Prikey = ((KeyPair) Localpemreader.readobject ()). Getprivate ();
Localpemreader.close ();
Br.close ();
PubKey = Ca.getpublickey ();
catch (IOException e) {logger.debug (E.getmessage ());
E.printstacktrace (); public static X509Certificate loadlocalcertificate () {try {inputstream ica = new Scepc
Ertservice (). GetClass (). getResourceAsStream ("/ca.crt");
Certificatefactory certfactory = certificatefactory . getinstance ("X.509");
CA = (x509certificate) certfactory.generatecertificate (ICA);
catch (Exception e) {logger.debug (E.getmessage ());
E.printstacktrace ();
} return CA;
private static BigInteger getserial () {Random rnd = new Random ();
Return biginteger.valueof (Math.Abs (Rnd.nextlong ()) + 1); public static PublicKey Geneneratepublickey (byte[] key) throws IOException, NoSuchAlgorithmException, Invalidkeyspe
CException {pkcs10certificationrequest pkcs10certreq=new pkcs10certificationrequest (key);
Subjectpublickeyinfo pkinfo = Pkcs10certreq.getsubjectpublickeyinfo ();
rsakeyparameters RSA = (rsakeyparameters) publickeyfactory.createkey (pkinfo);
Rsapublickeyspec Rsaspec = new Rsapublickeyspec (Rsa.getmodulus (), rsa.getexponent ());
Keyfactory keyfactory = keyfactory.getinstance ("RSA"); Return Keyfactory.generatepublic (RSASPEC); }
}
BC Style
You can modify the name type of subject and issuer by modifying the default Bcstyle. Specific through Grepcode to understand the source code.