A simple example of realizing digital certificate generation signature in pure Java _java

Source: Internet
Author: User
Tags base64 dname md5 hash pkcs12 rfc

Package Com.ylsoft.cert;
Import Java.io.File;
Import Java.io.FileInputStream;
Import Java.io.FileOutputStream;
Import java.io.IOException;
Import java.security.InvalidKeyException;
Import Java.security.KeyPair;
Import Java.security.KeyPairGenerator;
Import Java.security.KeyStore;
Import java.security.KeyStoreException;
Import java.security.NoSuchAlgorithmException;
Import java.security.NoSuchProviderException;
Import Java.security.PrivateKey;
Import Java.security.SecureRandom;
Import Java.security.Signature;
Import java.security.SignatureException;
Import java.security.UnrecoverableKeyException;
Import Java.security.cert.Certificate;
Import java.security.cert.CertificateException;
Import Java.security.cert.X509Certificate;
Import Java.util.Date;

Import Java.util.Vector;
Import Sun.misc.BASE64Encoder;
Import Sun.security.util.ObjectIdentifier;
Import Sun.security.x509.AlgorithmId;
Import Sun.security.x509.CertAndKeyGen;
Import Sun.security.x509.CertificateAlgorithmId; Import Sun.secuRity.x509.CertificateExtensions;
Import Sun.security.x509.CertificateSerialNumber;
Import sun.security.x509.CertificateValidity;
Import sun.security.x509.CertificateVersion;
Import Sun.security.x509.CertificateX509Key;
Import sun.security.x509.ExtendedKeyUsageExtension;
Import sun.security.x509.Extension;
Import Sun.security.x509.KeyIdentifier;
Import sun.security.x509.KeyUsageExtension;
Import sun.security.x509.SubjectKeyIdentifierExtension;
Import Sun.security.x509.X500Name;
Import Sun.security.x509.X500Signer;
Import Sun.security.x509.X509CertImpl;

Import Sun.security.x509.X509CertInfo;  /** * First generate the root certificate of the CA and then have the CA's root certificate to sign the SCRIPTX certificate * * @author Administrator */public class Genx509cert {/** provides strong cryptographic random number generators

	(RNG) * * */private securerandom SR; Public Genx509cert () throws NoSuchAlgorithmException, nosuchproviderexception {//return RNG that implements the specified random number generator (Securerando) algorithm
		M object.
	sr = securerandom.getinstance ("Sha1prng", "SUN"); } public void Createcert (X509Certificate certificate, PrivAtekey Rootprivkey, KeyPair kp) throws Certificateexception, IOException, InvalidKeyException, nosuchalgorithmexcept Ion, Nosuchproviderexception, signatureexception {//X.509 v1 certificate abstract class.
		This class provides a standard way to access all properties of a X.509 v1 certificate.

		byte certbytes[] = certificate.getencoded ();
		The X509certimpl class represents an X.509 certificate.

		X509certimpl X509certimpl = new X509certimpl (certbytes);
		The X509certinfo class represents X.509 certificate information.

		X509certinfo X509certinfo = (x509certinfo) x509certimpl. Get ("X509.info");
		This class defines the X509key attribute for the certificate.

		X509certinfo.set ("Key", New Certificatex509key (Kp.getpublic ())); This class defines the Extensions attribute for the certificate certificateextensions certificateextensions = new Cer

		Tificateextensions (); Certificateextensions.set ("Subjectkeyidentifier", New Subjectkeyidentifierextension (New KeyIdentifier (KP. getPu

		Blic ())). Getidentifier ()); X509certinfo. Set ("Extensions", certificateextensions);
		Set issuer domain x500name issuer = new X500name ("CN=ROOTCA,OU=HACKWP,O=WP,L=BJ,S=BJ,C=CN");

		X509certinfo.set ("Issuer.dname", issuer); Constructs a name from a conventionally formatted string, such as//"Cn=dave, Ou=javasoft, O=sun Microsystems, C=us" .
		(RFC 1779 or RFC//2253 style).

		X500name subject = new X500name ("Cn=scriptx, Ou=wps, O=wps, L=BJ, ST=BJ, C=CN");

		X509certinfo.set ("Subject.dname", subject); This Signature class is used to provide the digital Signature algorithm functionality for an application.
		Returns the Signature object that implements the specified signature algorithm.

		Signature Signature = signature.getinstance ("Md5withrsa"); Initializes the object that is used for signing.
		If you call this method again with another parameter, the result of this call is invalid.

		Signature.initsign (Kp.getprivate ()); This class provides a binding between a Signature object and A//authenticated X.500 name (from a X.509 certificat
		e chain), which is//needed in many public key signing applications.

		X500signer signer = new X500signer (signature, issuer); This class identifies algorithms, such as CryptogRaphic transforms,//each of the which may is associated with parameters.

		Algorithmid Algorithmid = Signer.getalgorithmid ();
		This class defines the Algorithmid for the certificate.

		X509certinfo. Set ("Algorithmid", New Certificatealgorithmid (Algorithmid));

		Start time Date bdate = new Date ();

		End time Date edate = new Date ();

		Days hours seconds milliseconds edate.settime (bdate.gettime () + 3650 * 24L * 60L * 60L * 1000L); Validity is a valid time length unit of seconds, this class defines the interval for which the//certificate is valid. Valid time for Certificates Certificatevalid

		ity certificatevalidity = new Certificatevalidity (bdate, edate);

		X509certinfo.set ("validity", certificatevalidity);
		This class defines the SerialNumber attribute for the certificate. Set the Expiration field (including start time and expiration) the domain name equals the x509certinfo.

		Validity X509certinfo.set ("SerialNumber", new Certificateserialnumber (int) (New Date (). GetTime ()/1000L));
		Set the serial Number field, this class defines the version of the X509 certificate. Certificateversion CV = new Certificateversion (CERTIFICATEVERSION.V3);

		X509certinfo.set (X509certinfo.version, CV);  Set version number only V1, v2,v3 these legal values/** * above is the basic information of the certificate if you want to add user extension information It is more cumbersome to first determine that version must be V3 or not, and then follow the steps below * * * objectidentifier

		OID = new Objectidentifier (new int[] {2, 5, 29, 15});
		The ID of the Build extension field is an int array 1th bit maximum 2 2nd digit Maximum 39 can be a few unknown ....

		String userData = "Digital Signature, Non-repudiation, Key encipherment, Data encipherment (F0)";

		byte L = (byte) userdata.length ()//Total data length 17 byte f = 0x04;

		Byte[] bs = new Byte[userdata.length () + 2];

		Bs[0] = f;

		BS[1] = l;
		for (int i = 2; i < bs.length i++) {bs[i] = (byte) userdata.charat (i-2);

		} Extension ext = new Extension (OID, True, BS); Generates a extension object parameter is OID, key extension, byte[] content value//the content is in a weird format the first one is flag here, take 4. The 2nd digit used to illustrate the usefulness of the data is the length of the actual data, followed by the data/

		/Key Usage keyusageextension keyusage = new Keyusageextension ();

		Keyusage.set (Keyusageextension.digital_signature, true); Keyusage.set (Keyusageextension.non_Repudiation, true);

		Keyusage.set (Keyusageextension.key_encipherment, true);

		Keyusage.set (Keyusageextension.data_encipherment, true);

Enhanced Key usage Objectidentifier ekeyoid = new Objectidentifier (new int[] {1, 3, 6, 1, 5, 5, 7, 3, 3});

vector<objectidentifier> vkeyoid = new vector<objectidentifier> ();

		Vkeyoid.add (ekeyoid);

		Extendedkeyusageextension exkeyusage = new Extendedkeyusageextension (vkeyoid);

		Certificateextensions exts = new Certificateextensions ();

		Exts.set ("Keyusage", keyusage);

		Exts.set ("Extendedkeyusage", exkeyusage);
		If there are multiple extension are placed in the Certificateextensions class, X509certinfo.set (X509certinfo.extensions, exts);

		Set extensions domain X509certimpl X509CERTIMPL1 = new X509certimpl (x509certinfo);
		X509certimpl1.sign (Rootprivkey, "Md5withrsa");

		Use the private key of another certificate to sign this certificate use MD5 hash to encrypt base64encoder base64 = new Base64encoder ();

		FileOutputStream fos = new FileOutputStream (New File ("F:\\SCRIPTX.CRT")); Base64.encodebuffer (x509certimpl1.getencoded (), FOS);

			try {certificate[] Certchain = {X509CERTIMPL1};

			SAVEPFX ("ScriptX", Kp.getprivate (), "123456", Certchain, "f:\\scriptx.pfx");

			FileInputStream in = new FileInputStream ("f:\\scriptx.pfx");

			KeyStore Inputkeystore = keystore.getinstance ("pkcs12");

			Inputkeystore.load (In, "123456". ToCharArray ());

			Certificate cert = inputkeystore.getcertificate ("ScriptX");

			System.out.print (Cert.getpublickey ());

			Privatekey PRIVK = (privatekey) inputkeystore.getkey ("ScriptX", "123456". ToCharArray ());

			FileOutputStream Privkfos = new FileOutputStream (New File ("f:\\scriptx.pvk"));

			Privkfos.write (privk.getencoded ());
			System.out.print (PRIVK);

			Base64.encode (key.getencoded (), Privkfos);

		In.close ();
		catch (Exception e) {//TODO auto-generated catch block E.printstacktrace ();

	}//Generate File X509certimpl1.verify (Certificate.getpublickey (), NULL); /** * Save this root certificate information keystore Personal Information exchAnge * @param alias * @param privkey * @param pwd * @param certchain * @param filepath * @throws exceptio n */public void savepfx (string alias, Privatekey Privkey, string pwd, certificate[] certchain, string filepath) thr
		OWS Exception {//This class represents the storage facility for keys and certificates. Returns the KeyStore object of the specified type. This method traverses the registered Security provider list starting with the preferred Provider.
		Returns a new KeyStore object that encapsulates the KEYSTORESPI//implementation taken from the first Provider that supports the specified type.

		KeyStore Outputkeystore = keystore.getinstance ("pkcs12");

		System.out.println ("KeyStore type:" + outputkeystore.gettype ()); Loads the KeyStore from the given input stream. A password can be given to unlock the KeyStore (for example, KeyStore on a hardware tag device) or to verify//KeyStore data integrity. If no password is specified for integrity verification, the integrity test is not performed. If you want to create an empty//KeyStore, or you cannot initialize KeyStore from the stream, NULL is passed as a parameter of the stream.
		Note that if this keystore//has been loaded, it will be reinitialized and loaded again from the given input stream.

		Outputkeystore.load (NULL, Pwd.tochararray ()); Assigns the given key (already protected) to the given alias. If the protected key is of type//Java.security.PrivateKey, it must be accompanied by a certificate chain that proves the corresponding public key. If the underlying KeyStore implementation type is//JKS, the key must be encoded AS//encryptedprivatekeyinfo according to the definition in the PKCS #8 standard. If the given alias already existsIn, the KeyStore//information associated with the alias will be overridden by the given key, which may also include the certificate chain.

		Outputkeystore. Setkeyentry (alias, Privkey, Pwd.tochararray (), certchain);
		Keystore.privatekeyentry pke=new//Keystore.privatekeyentry (Kp.getprivate (), certchain);
		Keystore.passwordprotection password=new//Keystore.passwordprotection ("123456". ToCharArray ());

		Outputkeystore.setentry ("ScriptX", Pke, password);

		FileOutputStream out = new FileOutputStream (filepath);
		Stores this keystore to a given output stream and protects its integrity with a given password.

		Outputkeystore.store (out, Pwd.tochararray ());
	Out.close (); public void Savejks (string alias, Privatekey Privkey, string pwd, certificate[] certchain, string filepath) throws

		Exception {KeyStore Outputkeystore = keystore.getinstance ("JKs");

		System.out.println (Outputkeystore.gettype ());

		Outputkeystore.load (NULL, Pwd.tochararray ());

		Outputkeystore. Setkeyentry (alias, Privkey, Pwd.tochararray (), certchain); Keystore.privatekeyentry pke=new//Keystore.privatekeyentry (Kp.getprivaTe (), Certchain);
		Keystore.passwordprotection password=new//Keystore.passwordprotection ("123456". ToCharArray ());

		Outputkeystore.setentry ("ScriptX", Pke, password);

		FileOutputStream out = new FileOutputStream (filepath);

		Outputkeystore.store (out, Pwd.tochararray ());
	Out.close (); /** * issued a root certificate, itself as a CA * * @throws nosuchalgorithmexception * @throws nosuchproviderexception * @throws Invalid Keyexception * @throws IOException * @throws certificateexception * @throws signatureexception * @throws unrecover Ablekeyexception */public void Createrootca () throws NoSuchAlgorithmException, Nosuchproviderexception, InvalidKeyE Xception, IOException, Certificateexception, signatureexception, unrecoverablekeyexception {//Parameters are public key algorithms, signature algorithms, respectively Provi
		Dername (because you do not know exactly how to use NULL to use both the default provider)//Generate a pair of keys, and provide access to them.

		Certandkeygen Cak = new Certandkeygen ("RSA", "Md5withrsa", null); Sets the source of random numbers used when generating keys.

		Cak.setrandom (SR);
		Generates a random public/private key pair with a given key size.

		Cak.generate (1024); Constructs a name from a conventionally formatted string, such as//"Cn=dave, Ou=javasoft, O=sun Microsystems, C=us" .
		(RFC 1779 or RFC//2253 style)

		X500name subject = new X500name ("CN=ROOTCA,OU=HACKWP,O=WP,L=BJ,S=BJ,C=CN"); Returns a self-signed X.509v3 certificate for the public key. The//certificate is immediately valid.
		No extensions. Such certificates normally are used to identify a "certificate//Authority" (CA). Accordingly, they'll not always is accepted by//other parties. However, such certificates are also useful when I//are bootstrapping security your, or infrastructure deploying EM//prototypes. self-signed root certificate X509Certificate certificate = cak.getselfcertificate (subject, New Date (), 3650 * 24L * 60

		L * 60L);

		X509certificate[] certs = {certificate}; try {savepfx ("ROOTCA",Cak.getprivatekey (), "123456", Certs, "f:\\rootca.pfx");

		catch (Exception e) {e.printstacktrace ();

		The//The latter long parameter represents the period of validity from the current starting time (if you do not want to change the field from now on) base64encoder base64 = new Base64encoder ();

		FileOutputStream fos = new FileOutputStream (New File ("F:\\ROOTCA.CRT"));

		Fos.write (certificate.getencoded ());

		Generate (Save) Cert file base64 Encryption Of course can also not encrypt Base64.encodebuffer (certificate.getencoded (), FOS);

	Fos.close (); public void Signcert () throws NoSuchAlgorithmException, Certificateexception, IOException, Unrecoverablekeyexceptio N, InvalidKeyException, nosuchproviderexception, signatureexception {try {KeyStore KS = Keystore.getinstance ("

			Pkcs12 ");

			FileInputStream Ksfis = new FileInputStream ("f:\\rootca.pfx");

			char[] storepwd = "123456". ToCharArray ();

			char[] keypwd = "123456". ToCharArray ();
			Loads the KeyStore from the given input stream.

			Ks.load (Ksfis, storepwd);

			Ksfis.close (); Returns the key (private key) associated with the given alias and restores it with a given password. Must have been invoked by calling Setkeyentry, or by// Privatekeyentry//or Secretkeyentry is the Setentry Association key and alias for the parameter.

			Privatekey PRIVK = (privatekey) ks.getkey ("RootCA", keypwd); Returns the certificate associated with the given alias. If the given alias identifies an entry created by calling Setcertificateentry, or by calling a Setentry//Created entry with//Trustedcertificateentry as the argument, the trusted certificate contained in the entry is returned.
			If the given alias identifies an entry created by calling Setkeyentry, or an entry created by calling Setentry with//Privatekeyentry as a parameter, the first element of the certificate chain in that entry is returned.

			X509Certificate certificate = (x509certificate) ks. GetCertificate ("ROOTCA");

		Createcert (certificate, PRIVK, Genkey ());
		catch (Keystoreexception e) {//TODO auto-generated catch block E.printstacktrace (); } public KeyPair Genkey () throws nosuchalgorithmexception {Keypairgenerator KPG = keypairgenerator.getinstance ("R

		SA ");

		Kpg.initialize (1024, SR);

		System.out.print (Kpg.getalgorithm ());

		KeyPair KP = Kpg.generatekeypair ();
	return KP;

			public static void Main (string[] args) {try {Genx509cert Gcert = new Genx509cert ();

			GCERT.CREATEROOTCA ();

		Gcert.signcert (); }catch (Exception e) {//TODO auto-generated catch block E.printstacktrace ();
 }
	}
}

Above this pure Java implementation of digital certificate generation Signature Simple example is a small series to share all the content, hope to give you a reference, but also hope that we support cloud habitat community.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.