欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

纯Java实现数字证书生成签名的简单实例

程序员文章站 2024-03-13 20:19:40
package com.ylsoft.cert; import java.io.file; import java.io.fileinputstream...

纯Java实现数字证书生成签名的简单实例

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;

/**
 * 首先生成ca的根证书,然后有ca的根证书签署生成scriptx的证书
 * 
 * @author administrator
 * 
 */
public class genx509cert {
	/** 提供强加密随机数生成器 (rng)* */
	private securerandom sr;

	public genx509cert() throws nosuchalgorithmexception,
			nosuchproviderexception {
		// 返回实现指定随机数生成器 (rng) 算法的 securerandom 对象。
		sr = securerandom.getinstance("sha1prng", "sun");
	}

	public void createcert(x509certificate certificate, privatekey rootprivkey,
			keypair kp) throws certificateexception, ioexception,
			invalidkeyexception, nosuchalgorithmexception,
			nosuchproviderexception, signatureexception {

		// x.509 v1 证书的抽象类。此类提供了一种访问 x.509 v1 证书所有属性的标准方式。
		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 certificateextensions();

		certificateextensions.set("subjectkeyidentifier",
				new subjectkeyidentifierextension((new keyidentifier(kp
						.getpublic())).getidentifier()));

		x509certinfo.set("extensions", certificateextensions);

		// 设置issuer域
		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);

		// 此 signature 类用来为应用程序提供数字签名算法功能。返回实现指定签名算法的 signature 对象。
		signature signature = signature.getinstance("md5withrsa");

		// 初始化这个用于签名的对象。如果使用其他参数再次调用此方法,此调用的结果将无效。
		signature.initsign(kp.getprivate());

		// this class provides a binding between a signature object and an
		// authenticated x.500 name (from an x.509 certificate 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 which may be associated with parameters.
		algorithmid algorithmid = signer.getalgorithmid();

		// this class defines the algorithmid for the certificate.
		x509certinfo
				.set("algorithmid", new certificatealgorithmid(algorithmid));

		// 开始时间
		date bdate = new date();

		// 结束时间
		date edate = new date();

		// 天 小时 分 秒 毫秒
		edate.settime(bdate.gettime() + 3650 * 24l * 60l * 60l * 1000l);

		// validity为有效时间长度 单位为秒,this class defines the interval for which the
		// certificate is valid.证书的有效时间
		certificatevalidity certificatevalidity = new certificatevalidity(
				bdate, edate);

		x509certinfo.set("validity", certificatevalidity);

		// this class defines the serialnumber attribute for the certificate.
		// 设置有效期域(包含开始时间和到期时间)域名等同与x509certinfo.validity
		x509certinfo.set("serialnumber", new certificateserialnumber(
				(int) (new date().gettime() / 1000l)));

		// 设置序列号域,this class defines the version of the x509 certificate.
		certificateversion cv = new certificateversion(certificateversion.v3);

		x509certinfo.set(x509certinfo.version, cv);

		// 设置版本号 只有v1 ,v2,v3这几个合法值
		/**
		 * 以上是证书的基本信息 如果要添加用户扩展信息 则比较麻烦 首先要确定version必须是v3否则不行 然后按照以下步骤
		 */
		objectidentifier oid = new objectidentifier(new int[] { 2, 5, 29, 15 });

		// 生成扩展域的id 是个int数组 第1位最大2 第2位最大39 最多可以几位不明....
		string userdata = "digital signature, non-repudiation, key encipherment, data encipherment (f0)";

		byte l = (byte) userdata.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);

		// 生成一个extension对象 参数分别为 oid,是否关键扩展,byte[]型的内容值
		// 其中内容的格式比较怪异 第一位是flag 这里取4暂时没出错 估计用来说明数据的用处的 第2位是后面的实际数据的长度,然后就是数据
		// 密钥用法
		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);

		// 增强密钥用法
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);

		// 如果有多个extension则都放入certificateextensions 类中,
		x509certinfo.set(x509certinfo.extensions, exts);
		// 设置extensions域

		x509certimpl x509certimpl1 = new x509certimpl(x509certinfo);

		x509certimpl1.sign(rootprivkey, "md5withrsa");
		// 使用另一个证书的私钥来签名此证书 这里使用 md5散列 用rsa来加密

		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();
		}

		// 生成文件
		x509certimpl1.verify(certificate.getpublickey(), null);

	}

	/**
	 * 保存此根证书信息keystore personal information exchange
	 * 
	 * @param alias
	 * @param privkey
	 * @param pwd
	 * @param certchain
	 * @param filepath
	 * @throws exception
	 */
	public void savepfx(string alias, privatekey privkey, string pwd,
			certificate[] certchain, string filepath) throws exception {
		// 此类表示密钥和证书的存储设施。
		// 返回指定类型的 keystore 对象。此方法从首选 provider 开始遍历已注册安全提供者列表。返回一个封装 keystorespi
		// 实现的新 keystore 对象,该实现取自第一个支持指定类型的 provider。
		keystore outputkeystore = keystore.getinstance("pkcs12");

		system.out.println("keystore类型:" + outputkeystore.gettype());

		// 从给定输入流中加载此 keystore。可以给定一个密码来解锁 keystore(例如,驻留在硬件标记设备上的 keystore)或检验
		// keystore 数据的完整性。如果没有指定用于完整性检验的密码,则不会执行完整性检验。如果要创建空
		// keystore,或者不能从流中初始化 keystore,则传递 null 作为 stream 的参数。注意,如果此 keystore
		// 已经被加载,那么它将被重新初始化,并再次从给定输入流中加载。
		outputkeystore.load(null, pwd.tochararray());

		// 将给定密钥(已经被保护)分配给给定别名。如果受保护密钥的类型为
		// java.security.privatekey,则它必须附带证明相应公钥的证书链。如果底层 keystore 实现的类型为
		// jks,则必须根据 pkcs #8 标准中的定义将 key 编码为
		// encryptedprivatekeyinfo。如果给定别名已经存在,则与别名关联的 keystore
		// 信息将被给定密钥(还可能包括证书链)重写。
		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);

		// 将此 keystore 存储到给定输出流,并用给定密码保护其完整性。
		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();
	}

	/**
	 * 颁布根证书,自己作为ca
	 * 
	 * @throws nosuchalgorithmexception
	 * @throws nosuchproviderexception
	 * @throws invalidkeyexception
	 * @throws ioexception
	 * @throws certificateexception
	 * @throws signatureexception
	 * @throws unrecoverablekeyexception
	 */
	public void createrootca() throws nosuchalgorithmexception,
			nosuchproviderexception, invalidkeyexception, ioexception,
			certificateexception, signatureexception, unrecoverablekeyexception {

		// 参数分别为公钥算法、签名算法 providername(因为不知道确切的 只好使用null 既使用默认的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 will not always be accepted by
		// other parties. however, such certificates are also useful when you
		// are bootstrapping your security infrastructure, or deploying system
		// prototypes.自签名的根证书
		x509certificate certificate = cak.getselfcertificate(subject,
				new date(), 3650 * 24l * 60l * 60l);

		x509certificate[] certs = { certificate };

		try {

			savepfx("rootca", cak.getprivatekey(), "123456", certs,
					"f:\\rootca.pfx");

		} catch (exception e) {

			e.printstacktrace();

		}

		// 后一个long型参数代表从现在开始的有效期 单位为秒(如果不想从现在开始算 可以在后面改这个域)
		base64encoder base64 = new base64encoder();

		fileoutputstream fos = new fileoutputstream(new file("f:\\rootca.crt"));

		// fos.write(certificate.getencoded());

		// 生成(保存)cert文件 base64加密 当然也可以不加密
		base64.encodebuffer(certificate.getencoded(), fos);

		fos.close();

	}

	public void signcert() throws nosuchalgorithmexception,
			certificateexception, ioexception, unrecoverablekeyexception,
			invalidkeyexception, nosuchproviderexception, signatureexception {

		try {

			keystore ks = keystore.getinstance("pkcs12");

			fileinputstream ksfis = new fileinputstream("f:\\rootca.pfx");

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

			char[] keypwd = "123456".tochararray();

			// 从给定输入流中加载此 keystore。
			ks.load(ksfis, storepwd);

			ksfis.close();

			// 返回与给定别名关联的密钥(私钥),并用给定密码来恢复它。必须已经通过调用 setkeyentry,或者以
			// privatekeyentry
			// 或 secretkeyentry 为参数的 setentry 关联密钥与别名。
			privatekey privk = (privatekey) ks.getkey("rootca", keypwd);

			// 返回与给定别名关联的证书。如果给定的别名标识通过调用 setcertificateentry 创建的条目,或者通过调用以
			// trustedcertificateentry 为参数的 setentry
			// 创建的条目,则返回包含在该条目中的可信证书。如果给定的别名标识通过调用 setkeyentry 创建的条目,或者通过调用以
			// privatekeyentry 为参数的 setentry 创建的条目,则返回该条目中证书链的第一个元素。
			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("rsa");

		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();
		}
	}
}

以上这篇纯java实现数字证书生成签名的简单实例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持。