`
沙舟狼客
  • 浏览: 164777 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

利用bouncycastle组装X509证书

阅读更多

CreateCert.java

package com.secpki.jce.demo;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.UnsupportedEncodingException;
import java.math.BigInteger;
import java.security.KeyFactory;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.Security;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import java.security.spec.RSAPrivateCrtKeySpec;
import java.security.spec.RSAPublicKeySpec;
import java.util.Date;
import java.util.Hashtable;
import java.util.Random;
import java.util.Vector;

import org.bouncycastle.asn1.ASN1EncodableVector;
import org.bouncycastle.asn1.DERBitString;
import org.bouncycastle.asn1.DERBoolean;
import org.bouncycastle.asn1.DEREncodable;
import org.bouncycastle.asn1.DERGeneralizedTime;
import org.bouncycastle.asn1.DERInteger;
import org.bouncycastle.asn1.DERObject;
import org.bouncycastle.asn1.DERObjectIdentifier;
import org.bouncycastle.asn1.DERPrintableString;
import org.bouncycastle.asn1.DERSequence;
import org.bouncycastle.asn1.DERSet;
import org.bouncycastle.asn1.DERTaggedObject;
import org.bouncycastle.asn1.DERUTCTime;
import org.bouncycastle.asn1.x500.X500Name;
import org.bouncycastle.asn1.x509.AccessDescription;
import org.bouncycastle.asn1.x509.AlgorithmIdentifier;
import org.bouncycastle.asn1.x509.Attribute;
import org.bouncycastle.asn1.x509.CRLDistPoint;
import org.bouncycastle.asn1.x509.DistributionPoint;
import org.bouncycastle.asn1.x509.DistributionPointName;
import org.bouncycastle.asn1.x509.GeneralName;
import org.bouncycastle.asn1.x509.GeneralNames;
import org.bouncycastle.asn1.x509.GeneralSubtree;
import org.bouncycastle.asn1.x509.KeyPurposeId;
import org.bouncycastle.asn1.x509.KeyUsage;
import org.bouncycastle.asn1.x509.NameConstraints;
import org.bouncycastle.asn1.x509.PolicyMappings;
import org.bouncycastle.asn1.x509.PrivateKeyUsagePeriod;
import org.bouncycastle.asn1.x509.SubjectDirectoryAttributes;
import org.bouncycastle.asn1.x509.SubjectPublicKeyInfo;
import org.bouncycastle.asn1.x509.V3TBSCertificateGenerator;
import org.bouncycastle.asn1.x509.X509CertificateStructure;
import org.bouncycastle.asn1.x509.X509Extensions;
import org.bouncycastle.asn1.x509.X509ExtensionsGenerator;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.jce.provider.X509CertificateObject;

public class CreateCert {

	public BigInteger genCertSerial() {
		// BigInteger bigInteger = new BigInteger(val);
		byte[] b = new byte[32];
		Random random = new Random(new Date().getTime());

		for (int i = 0; i < 32; i++) {
			byte[] tmp = new byte[10];
			random.nextBytes(tmp);
			b[i] = tmp[random.nextInt(tmp.length - 1)];
		}
		return new BigInteger(b);
	}

	public X509Certificate createAcIssuerCert(X500Name issuer,
			BigInteger serial, Date notBefore, Date notAfter, X500Name subject,
			final SubjectPublicKeyInfo publicKeyInfo, PrivateKey privKey)
			throws Exception {
		V3TBSCertificateGenerator certificateGenerator = new V3TBSCertificateGenerator();
		certificateGenerator.setExtensions(getCertGen());
		certificateGenerator.setSignature(publicKeyInfo.getAlgorithmId());

		certificateGenerator.setIssuer(issuer);
		certificateGenerator.setSubject(subject);
		certificateGenerator.setSerialNumber(new DERInteger(serial));
		certificateGenerator.setStartDate(new DERUTCTime(notBefore));
		certificateGenerator.setEndDate(new DERUTCTime(notAfter));
		certificateGenerator.setSubjectPublicKeyInfo(publicKeyInfo);


		System.out.println(certificateGenerator.generateTBSCertificate()
				.getEncoded().length);

		ASN1EncodableVector asn1encodablevector = new ASN1EncodableVector();
		asn1encodablevector.add(certificateGenerator.generateTBSCertificate());
		asn1encodablevector.add(publicKeyInfo.getAlgorithmId());
		
		byte[] pubData = new byte[65];
		pubData[0] = 0;

		for(byte i=1;i<pubData.length;i++){
			pubData[i] = i;
		}

		byte[] signInfo = new byte[69];//.....
		for(byte i=1;i<pubData.length;i++){
			pubData[i] = i;
		}
		
		asn1encodablevector.add(new DERBitString(signInfo));
		X509CertificateObject cert = new X509CertificateObject(new X509CertificateStructure(new DERSequence(asn1encodablevector)));
		return cert;
	}

	@SuppressWarnings("deprecation")
	static X509Extensions getCertGen() {
		// 添加扩展
		X509ExtensionsGenerator certGen = new X509ExtensionsGenerator();

		// 基本限制
		certGen.addExtension(X509Extensions.BasicConstraints, false,
				new DEREncodable() {

					@Override
					public DERObject getDERObject() {
						// TODO Auto-generated method stub
						ASN1EncodableVector bConstraints = new ASN1EncodableVector();
						// 是否是CA证书
						boolean bCA = false;
						bConstraints.add(new DERBoolean(bCA));
						// 证书路径长度限制
						int pathLenConstraint = 3;
						if ((pathLenConstraint >= 0) && (bCA))
							bConstraints.add(new DERInteger(pathLenConstraint));
						return new DERSequence(bConstraints);
					}

				});
		// 密钥用法
		certGen.addExtension(X509Extensions.KeyUsage, false,
				new DEREncodable() {
					@SuppressWarnings("unused")
					public int keyUsage;

					public static final int digitalSignature = (1 << 7);
					public static final int nonRepudiation = (1 << 6);
					public static final int keyEncipherment = (1 << 5);
					public static final int dataEncipherment = (1 << 4);
					public static final int keyAgreement = (1 << 3);
					public static final int keyCertSign = (1 << 2);
					public static final int cRLSign = (1 << 1);
					public static final int encipherOnly = (1 << 0);
					public static final int decipherOnly = (1 << 15);

					@Override
					public DERObject getDERObject() {
						// TODO Auto-generated method stub
						return new KeyUsage(digitalSignature | nonRepudiation
								| keyEncipherment | dataEncipherment
								| keyAgreement | keyCertSign | cRLSign
								| encipherOnly | decipherOnly);
					}

				});
		// 扩展密钥用法
		certGen.addExtension(X509Extensions.ExtendedKeyUsage, false,
				new DEREncodable() {
					private static final String id_kp = "1.3.6.1.5.5.7.3";
					@SuppressWarnings("unused")
					public final KeyPurposeId anyExtendedKeyUsage = new KeyPurposeId(
							X509Extensions.ExtendedKeyUsage.getId() + ".0");
					@SuppressWarnings("unused")
					public final KeyPurposeId id_kp_serverAuth = new KeyPurposeId(
							id_kp + ".1");
					@SuppressWarnings("unused")
					public final KeyPurposeId id_kp_clientAuth = new KeyPurposeId(
							id_kp + ".2");
					@SuppressWarnings("unused")
					public final KeyPurposeId id_kp_codeSigning = new KeyPurposeId(
							id_kp + ".3");
					@SuppressWarnings("unused")
					public final KeyPurposeId id_kp_emailProtection = new KeyPurposeId(
							id_kp + ".4");
					@SuppressWarnings("unused")
					public final KeyPurposeId id_kp_ipsecEndSystem = new KeyPurposeId(
							id_kp + ".5");
					@SuppressWarnings("unused")
					public final KeyPurposeId id_kp_ipsecTunnel = new KeyPurposeId(
							id_kp + ".6");
					@SuppressWarnings("unused")
					public final KeyPurposeId id_kp_ipsecUser = new KeyPurposeId(
							id_kp + ".7");
					@SuppressWarnings("unused")
					public final KeyPurposeId id_kp_timeStamping = new KeyPurposeId(
							id_kp + ".8");
					public final KeyPurposeId id_kp_OCSPSigning = new KeyPurposeId(
							id_kp + ".9");
					@SuppressWarnings("unused")
					public final KeyPurposeId id_kp_dvcs = new KeyPurposeId(
							id_kp + ".10");
					@SuppressWarnings("unused")
					public final KeyPurposeId id_kp_sbgpCertAAServerAuth = new KeyPurposeId(
							id_kp + ".11");
					@SuppressWarnings("unused")
					public final KeyPurposeId id_kp_scvp_responder = new KeyPurposeId(
							id_kp + ".12");
					@SuppressWarnings("unused")
					public final KeyPurposeId id_kp_eapOverPPP = new KeyPurposeId(
							id_kp + ".13");
					@SuppressWarnings("unused")
					public final KeyPurposeId id_kp_eapOverLAN = new KeyPurposeId(
							id_kp + ".14");
					@SuppressWarnings("unused")
					public final KeyPurposeId id_kp_scvpServer = new KeyPurposeId(
							id_kp + ".15");
					@SuppressWarnings("unused")
					public final KeyPurposeId id_kp_scvpClient = new KeyPurposeId(
							id_kp + ".16");
					@SuppressWarnings("unused")
					public final KeyPurposeId id_kp_ipsecIKE = new KeyPurposeId(
							id_kp + ".17");
					public final KeyPurposeId id_kp_capwapAC = new KeyPurposeId(
							id_kp + ".18");
					@SuppressWarnings("unused")
					public final KeyPurposeId id_kp_capwapWTP = new KeyPurposeId(
							id_kp + ".19");
					@SuppressWarnings("unused")
					public final KeyPurposeId id_kp_smartcardlogon = new KeyPurposeId(
							"1.3.6.1.4.1.311.20.2.2");
					ASN1EncodableVector extKeyUsage = new ASN1EncodableVector();

					@Override
					public DERObject getDERObject() {
						// TODO Auto-generated method stub
						extKeyUsage.add(id_kp_OCSPSigning);
						extKeyUsage.add(id_kp_capwapAC);
						return new DERSequence(extKeyUsage);
					}

				});
		// 主题备用名称
		certGen.addExtension(X509Extensions.SubjectAlternativeName, false,
				new DEREncodable() {
					@SuppressWarnings("unused")
					public static final int otherName = 0;
					@SuppressWarnings("unused")
					public static final int rfc822Name = 1;
					@SuppressWarnings("unused")
					public static final int dNSName = 2;
					@SuppressWarnings("unused")
					public static final int x400Address = 3;
					@SuppressWarnings("unused")
					public static final int directoryName = 4;
					@SuppressWarnings("unused")
					public static final int ediPartyName = 5;
					@SuppressWarnings("unused")
					public static final int uniformResourceIdentifier = 6;
					public static final int iPAddress = 7;
					@SuppressWarnings("unused")
					public static final int registeredID = 8;

					@Override
					public DERObject getDERObject() {
						// TODO Auto-generated method stub

						ASN1EncodableVector nameVector = new ASN1EncodableVector();

						nameVector.add(new GeneralName(iPAddress, "127.0.0.1"));
						return new GeneralNames(new DERSequence(nameVector))
								.getDERObject();
					}

				});
		// 颁发者备用别名
		certGen.addExtension(X509Extensions.IssuerAlternativeName, false,
				new DEREncodable() {
					@SuppressWarnings("unused")
					public static final int otherName = 0;
					@SuppressWarnings("unused")
					public static final int rfc822Name = 1;
					@SuppressWarnings("unused")
					public static final int dNSName = 2;
					@SuppressWarnings("unused")
					public static final int x400Address = 3;
					@SuppressWarnings("unused")
					public static final int directoryName = 4;
					@SuppressWarnings("unused")
					public static final int ediPartyName = 5;
					@SuppressWarnings("unused")
					public static final int uniformResourceIdentifier = 6;
					public static final int iPAddress = 7;
					@SuppressWarnings("unused")
					public static final int registeredID = 8;

					@Override
					public DERObject getDERObject() {
						// TODO Auto-generated method stub
						ASN1EncodableVector nameVector = new ASN1EncodableVector();

						nameVector.add(new GeneralName(iPAddress, "127.0.0.1"));
						return new GeneralNames(new DERSequence(nameVector))
								.getDERObject();
					}

				});
		// 秘钥有效期
		certGen.addExtension(X509Extensions.PrivateKeyUsagePeriod, false,
				new DEREncodable() {

					@Override
					public DERObject getDERObject() {
						// TODO Auto-generated method stub
						Date notBefore = new Date();
						Date notAfter = new Date(notBefore.getTime() * 2);
						DERGeneralizedTime keyNotBefore = new DERGeneralizedTime(
								notBefore);
						DERGeneralizedTime keyNotAfter = new DERGeneralizedTime(
								notAfter);
						DERTaggedObject atokeyNotBefore = new DERTaggedObject(
								false, 0, keyNotBefore);
						DERTaggedObject atokeyNotAfter = new DERTaggedObject(
								false, 1, keyNotAfter);
						ASN1EncodableVector periodVector = new ASN1EncodableVector();
						periodVector.add(atokeyNotBefore);
						periodVector.add(atokeyNotAfter);
						return PrivateKeyUsagePeriod.getInstance(
								new DERSequence(periodVector)).getDERObject();
					}

				});
		// 策略限制
		certGen.addExtension(X509Extensions.PolicyConstraints, false,
				new DEREncodable() {
					int requireExplicitPolicy = -1;
					int inhibitPolicyMapping = -1;

					@Override
					public DERObject getDERObject() {
						// TODO Auto-generated method stub
						ASN1EncodableVector pConstraints = new ASN1EncodableVector();
						if (requireExplicitPolicy >= 0)
							pConstraints.add(new DERTaggedObject(false, 0,
									new DERInteger(requireExplicitPolicy)));
						if (inhibitPolicyMapping >= 0)
							pConstraints.add(new DERTaggedObject(false, 1,
									new DERInteger(inhibitPolicyMapping)));
						return new DERSequence(pConstraints);
					}

				});
		// 禁止任意策略
		certGen.addExtension(X509Extensions.InhibitAnyPolicy, false,
				new DEREncodable() {
					public int InhibitAnyPolicy;

					@Override
					public DERObject getDERObject() {
						// TODO Auto-generated method stub
						if (InhibitAnyPolicy >= 0)
							return new DERInteger(InhibitAnyPolicy);
						else
							return null;
					}

				});
		// 证书策略
		certGen.addExtension(X509Extensions.CertificatePolicies, false,
				new CertificatePoliciesInfo());
		// 策略映射
		certGen.addExtension(X509Extensions.PolicyMappings, false,
				new DEREncodable() {
					public Hashtable<String, String> policyMappings = new Hashtable<String, String>();

					@Override
					public DERObject getDERObject() {
						return new PolicyMappings(policyMappings)
								.getDERObject();
					}

					@SuppressWarnings("unused")
					public void add(String policyOID, String mappingPolicyOID) {
						policyMappings.put(policyOID, mappingPolicyOID);

					}
				});
		// 主题密钥标识符
		/*
		 * certGen.addExtension(X509Extensions.SubjectKeyIdentifier, false, new
		 * DEREncodable() { //TODO public需要设置 public PublicKey keyIdentifier;
		 * 
		 * @Override public DERObject getDERObject() { // TODO Auto-generated
		 * method stub return new
		 * SubjectKeyIdentifierStructure(keyIdentifier).getDERObject(); }
		 * 
		 * });
		 */
		// 权威密钥标识符
		// TODO 请参考RFC3093实现
		/*
		 * certGen.addExtension(X509Extensions.AuthorityKeyIdentifier, false,
		 * new DEREncodable() {
		 * 
		 * public PublicKey keyIdentifier; //public ExtensionGeneralName
		 * authorityCertIssuer; public BigInteger authorityCertSerialNumber;
		 * 
		 * @Override public DERObject getDERObject() { // TODO Auto-generated
		 * method stub ASN1EncodableVector apkInfo = new ASN1EncodableVector();
		 * SubjectPublicKeyInfo apki; try { if (keyIdentifier != null) { apki =
		 * new SubjectPublicKeyInfo( (ASN1Sequence) new ASN1InputStream( new
		 * ByteArrayInputStream( keyIdentifier .getEncoded())) .readObject());
		 * Digest digest = new SHA1Digest(); byte[] resBuf = new
		 * byte[digest.getDigestSize()]; byte[] bytes = apki.getPublicKeyData()
		 * .getBytes(); digest.update(bytes, 0, bytes.length);
		 * digest.doFinal(resBuf, 0); apkInfo.add(new DERTaggedObject(false, 0,
		 * new DEROctetString(resBuf))); } if (authorityCertIssuer != null)
		 * apkInfo.add(new DERTaggedObject(false, 1, new GeneralNames(new
		 * GeneralName( authorityCertIssuer.nameType,
		 * authorityCertIssuer.value)))); if (authorityCertSerialNumber != null)
		 * apkInfo.add(new DERTaggedObject(false, 2, new DERInteger(
		 * authorityCertSerialNumber))); return new DERSequence(apkInfo); }
		 * catch (IOException e) { // TODO Auto-generated catch block
		 * e.printStackTrace(); }
		 * 
		 * return null; }
		 * 
		 * });
		 */
		// 主体目录属性
		certGen.addExtension(X509Extensions.SubjectDirectoryAttributes, false,
				new DEREncodable() {
					public String gender;
					public String dateOfBirth;
					public String streetAddress;
					public String telephoneNumber;
					public String mobileTelephoneNumber;

					@Override
					public DERObject getDERObject() {
						String genderOid = "1.3.6.1.5.5.7.9.4";
						String dateOfBirthOid = "1.3.6.1.5.5.7.9.1";
						String streetAddressOid = "2.5.4.9";
						String telephoneNumberOid = "2.5.4.20";
						String mobileTelephoneNumberOid = "0.9.2342.19200300.100.1.41";

						Vector<Attribute> attributes = new Vector<Attribute>();

						try {
							if (gender != null)
								attributes
										.add(makeAttribute(genderOid, gender));
							if (dateOfBirth != null)
								attributes.add(makeAttribute(dateOfBirthOid,
										dateOfBirth));
							if (streetAddress != null)
								attributes.add(makeAttribute(streetAddressOid,
										streetAddress));
							if (telephoneNumber != null)
								attributes.add(makeAttribute(
										telephoneNumberOid, telephoneNumber));
							if (mobileTelephoneNumber != null)
								attributes.add(makeAttribute(
										mobileTelephoneNumberOid,
										mobileTelephoneNumber));
							return new SubjectDirectoryAttributes(attributes)
									.getDERObject();
						} catch (UnsupportedEncodingException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}

						return null;
					}

					private Attribute makeAttribute(String oid, String value)
							throws UnsupportedEncodingException {
						DERSet valueSet = new DERSet(new DERPrintableString(
								value.getBytes("UTF-8")));
						return new Attribute(new DERObjectIdentifier(oid),
								valueSet);
					}

				});
		// 名称限制
		certGen.addExtension(X509Extensions.NameConstraints, false,
				new DEREncodable() {
					private Vector<GeneralSubtree> permittedSubtrees = new Vector<GeneralSubtree>();
					private Vector<GeneralSubtree> excludedSubtrees = new Vector<GeneralSubtree>();

					@Override
					public DERObject getDERObject() {
						// TODO Auto-generated method stub
						return new NameConstraints(permittedSubtrees,
								excludedSubtrees).getDERObject();
					}

					@SuppressWarnings("unused")
					public void addPermitted(
							ExtensionGeneralName permittedName, int minimum,
							int maximum) {
						permittedSubtrees.add(new GeneralSubtree(
								new GeneralName(permittedName.nameType,
										permittedName.value), BigInteger
										.valueOf(minimum), BigInteger
										.valueOf(maximum)));
					}

					@SuppressWarnings("unused")
					public void addExcluded(ExtensionGeneralName excludedName,
							int minimum, int maximum) {
						excludedSubtrees.add(new GeneralSubtree(
								new GeneralName(excludedName.nameType,
										excludedName.value), BigInteger
										.valueOf(minimum), BigInteger
										.valueOf(maximum)));
					}

				});
		// CRL分布点
		certGen.addExtension(X509Extensions.CRLDistributionPoints, false,
				new DEREncodable() {
					private Vector<ExtensionGeneralName> crlDistPoints = new Vector<ExtensionGeneralName>();

					@Override
					public DERObject getDERObject() {
						// TODO Auto-generated method stub
						int iCount = crlDistPoints.size();
						assert (iCount > 0);
						DistributionPoint[] dp = new DistributionPoint[iCount];

						for (int i = 0; i < iCount; ++i) {
							DistributionPointName dpn = new DistributionPointName(
									new GeneralNames(
											new GeneralName(
													crlDistPoints.elementAt(i).nameType,
													crlDistPoints.elementAt(i).value)));
							dp[i] = new DistributionPoint(dpn, null, null);
						}

						return new CRLDistPoint(dp).getDERObject();
					}

					@SuppressWarnings("unused")
					public void add(ExtensionGeneralName info) {
						crlDistPoints.add(info);
					}

				});
		// 最新/增量CRL分布点
		certGen.addExtension(X509Extensions.FreshestCRL, false,
				new DEREncodable() {
					private Vector<ExtensionGeneralName> crlDistPoints = new Vector<ExtensionGeneralName>();

					@Override
					public DERObject getDERObject() {
						// TODO Auto-generated method stub
						int iCount = crlDistPoints.size();
						assert (iCount > 0);
						DistributionPoint[] dp = new DistributionPoint[iCount];

						for (int i = 0; i < iCount; ++i) {
							DistributionPointName dpn = new DistributionPointName(
									new GeneralNames(
											new GeneralName(
													crlDistPoints.elementAt(i).nameType,
													crlDistPoints.elementAt(i).value)));
							dp[i] = new DistributionPoint(dpn, null, null);
						}

						return new CRLDistPoint(dp).getDERObject();
					}

					@SuppressWarnings("unused")
					public void add(ExtensionGeneralName info) {
						crlDistPoints.add(info);
					}

				});
		// 机构信息访问
		certGen.addExtension(X509Extensions.AuthorityInfoAccess, false,
				new DEREncodable() {
					public final DERObjectIdentifier id_ad_caIssuers = new DERObjectIdentifier(
							"1.3.6.1.5.5.7.48.2");
					public final DERObjectIdentifier id_ad_ocsp = new DERObjectIdentifier(
							"1.3.6.1.5.5.7.48.1");
					private ASN1EncodableVector authorityInfoAccessVec = new ASN1EncodableVector();

					@Override
					public DERObject getDERObject() {
						// TODO Auto-generated method stub
						return new DERSequence(authorityInfoAccessVec);
					}

					@SuppressWarnings("unused")
					public void add(DERObjectIdentifier accessMethod,
							ExtensionGeneralName accessLocation) {
						authorityInfoAccessVec.add(new AccessDescription(
								accessMethod, new GeneralName(
										accessLocation.nameType,
										accessLocation.value)));
					}

					@SuppressWarnings("unused")
					public void add(String accessMethod,
							ExtensionGeneralName accessLocation) {
						DERObjectIdentifier am = null;
						if (accessMethod.equalsIgnoreCase("caIssuers"))
							am = id_ad_caIssuers;
						else if (accessMethod.equalsIgnoreCase("ocsp"))
							am = id_ad_ocsp;
						else {
							System.out
									.println("InfoAccessInfo:no supported type!");
							assert (false);
						}
						authorityInfoAccessVec.add(new AccessDescription(am,
								new GeneralName(accessLocation.nameType,
										accessLocation.value)));
					}
				});
		// 主题信息访问
		/*
		 * certGen.addExtension(X509Extensions.AuthorityInfoAccess, false, new
		 * DEREncodable() { public final DERObjectIdentifier id_ad_caIssuers =
		 * new DERObjectIdentifier( "1.3.6.1.5.5.7.48.2"); public final
		 * DERObjectIdentifier id_ad_ocsp = new DERObjectIdentifier(
		 * "1.3.6.1.5.5.7.48.1"); private ASN1EncodableVector
		 * authorityInfoAccessVec = new ASN1EncodableVector();
		 * 
		 * @Override public DERObject getDERObject() { // TODO Auto-generated
		 * method stub return new DERSequence(authorityInfoAccessVec); }
		 * 
		 * @SuppressWarnings("unused") public void add(DERObjectIdentifier
		 * accessMethod, ExtensionGeneralName accessLocation) {
		 * authorityInfoAccessVec.add(new AccessDescription( accessMethod, new
		 * GeneralName( accessLocation.nameType, accessLocation.value))); }
		 * 
		 * @SuppressWarnings("unused") public void add(String accessMethod,
		 * ExtensionGeneralName accessLocation) { DERObjectIdentifier am = null;
		 * if (accessMethod.equalsIgnoreCase("caIssuers")) am = id_ad_caIssuers;
		 * else if (accessMethod.equalsIgnoreCase("ocsp")) am = id_ad_ocsp; else
		 * { System.out .println("InfoAccessInfo:no supported type!"); assert
		 * (false); } authorityInfoAccessVec.add(new AccessDescription(am, new
		 * GeneralName(accessLocation.nameType, accessLocation.value))); } });
		 */
		return certGen.generate();
	}

	public static void main(String args[]) throws Exception {
		Security.addProvider(new BouncyCastleProvider());
		X500Name issuer = new X500Name("O=IBM,OU=CSC,CN=dev");
		X500Name subject = new X500Name("O=IBM,OU=CSC,CN=ligson");
		CreateCert cert = new CreateCert();
		BigInteger serail = cert.genCertSerial();
		RSAPublicKeySpec pubKeySpec = new RSAPublicKeySpec(
				new BigInteger(
						"b4a7e46170574f16a97082b22be58b6a2a629798419be12872a4bdba626cfae9900f76abfb12139dce5de56564fab2b6543165a040c606887420e33d91ed7ed7",
						16), new BigInteger("11", 16));
		RSAPrivateCrtKeySpec privKeySpec = new RSAPrivateCrtKeySpec(
				new BigInteger(
						"b4a7e46170574f16a97082b22be58b6a2a629798419be12872a4bdba626cfae9900f76abfb12139dce5de56564fab2b6543165a040c606887420e33d91ed7ed7",
						16),
				new BigInteger("11", 16),
				new BigInteger(
						"9f66f6b05410cd503b2709e88115d55daced94d1a34d4e32bf824d0dde6028ae79c5f07b580f5dce240d7111f7ddb130a7945cd7d957d1920994da389f490c89",
						16),
				new BigInteger(
						"c0a0758cdf14256f78d4708c86becdead1b50ad4ad6c5c703e2168fbf37884cb",
						16),
				new BigInteger(
						"f01734d7960ea60070f1b06f2bb81bfac48ff192ae18451d5e56c734a5aab8a5",
						16),
				new BigInteger(
						"b54bb9edff22051d9ee60f9351a48591b6500a319429c069a3e335a1d6171391",
						16),
				new BigInteger(
						"d3d83daf2a0cecd3367ae6f8ae1aeb82e9ac2f816c6fc483533d8297dd7884cd",
						16),
				new BigInteger(
						"b8f52fc6f38593dabb661d3f50f8897f8106eee68b1bce78a95b132b4e5b5d19",
						16));
		KeyFactory fact = KeyFactory.getInstance("RSA", "BC");
		PublicKey pkKey = fact.generatePublic(pubKeySpec);
		PrivateKey privateKey = fact.generatePrivate(privKeySpec);
		System.out.println(pkKey);
		AlgorithmIdentifier algorithmIdentifier = AlgorithmIdentifier
				.getInstance(X509Util.getAlgorithmOID("SHA1WITHRSA"));
		SubjectPublicKeyInfo subjectPublicKeyInfo = new SubjectPublicKeyInfo(
				algorithmIdentifier, pkKey.getEncoded());
		X509Certificate certificate = cert.createAcIssuerCert(issuer, serail,
				new Date(), new Date(new Date().getTime() + 10000000), subject,
				subjectPublicKeyInfo, privateKey);

		// certificate.getEncoded();
		FileOutputStream fileOutputStream = new FileOutputStream(new File(
				"E:/code/itrusca/SecPKI/cert/2.cer"));
		fileOutputStream.write(certificate.getEncoded());
		fileOutputStream.close();

	}

}

 ExtensionGeneralName.java

 

package com.secpki.jce.demo;

public class ExtensionGeneralName{
	public int nameType;
	public String value;
	
	public static final int otherName                     = 0;
    public static final int rfc822Name                    = 1;
    public static final int dNSName                       = 2;
    public static final int x400Address                   = 3;
    public static final int directoryName                 = 4;
    public static final int ediPartyName                  = 5;
    public static final int uniformResourceIdentifier     = 6;
    public static final int iPAddress                     = 7;
    public static final int registeredID                  = 8;
    
    public static final String[] typeTable = new String[9];
    public ExtensionGeneralName()
    {
    }
    public ExtensionGeneralName(int nameType,String value)
    {
    	this.nameType = nameType;
    	this.value = value;
    }
    public void setNameType(int nameType)
    {
    	this.nameType = nameType;
    }
    public void setNameType(String nameType)
    {
    	if(nameType.equalsIgnoreCase("otherName"))
    		this.nameType = otherName;
    	else if(nameType.equalsIgnoreCase("rfc822Name"))
    		this.nameType = rfc822Name;
    	else if(nameType.equalsIgnoreCase("dNSName"))
    		this.nameType = dNSName;
    	else if(nameType.equalsIgnoreCase("x400Address"))
    		this.nameType = x400Address;
    	else if(nameType.equalsIgnoreCase("directoryName"))
    		this.nameType = directoryName;
    	else if(nameType.equalsIgnoreCase("ediPartyName"))
    		this.nameType = ediPartyName;
    	else if(nameType.equalsIgnoreCase("uniformResourceIdentifier"))
    		this.nameType = uniformResourceIdentifier;
    	else if(nameType.equalsIgnoreCase("iPAddress"))
    		this.nameType = iPAddress;
    	else if(nameType.equalsIgnoreCase("registeredID"))
    		this.nameType = registeredID;
    	else
    	{
    		System.out.println("ExtensionGeneralName:no supported type!");
    		assert(false);
    	}
    }
}

 X509Util.java

package com.secpki.jce.demo;

import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.PrivateKey;
import java.security.Provider;
import java.security.SecureRandom;
import java.security.Security;
import java.security.Signature;
import java.security.SignatureException;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

import javax.security.auth.x500.X500Principal;

import org.bouncycastle.asn1.ASN1Encodable;
import org.bouncycastle.asn1.DEREncodable;
import org.bouncycastle.asn1.DERInteger;
import org.bouncycastle.asn1.DERNull;
import org.bouncycastle.asn1.DERObjectIdentifier;
import org.bouncycastle.asn1.cryptopro.CryptoProObjectIdentifiers;
import org.bouncycastle.asn1.nist.NISTObjectIdentifiers;
import org.bouncycastle.asn1.oiw.OIWObjectIdentifiers;
import org.bouncycastle.asn1.pkcs.PKCSObjectIdentifiers;
import org.bouncycastle.asn1.pkcs.RSASSAPSSparams;
import org.bouncycastle.asn1.teletrust.TeleTrusTObjectIdentifiers;
import org.bouncycastle.asn1.x509.AlgorithmIdentifier;
import org.bouncycastle.asn1.x9.X9ObjectIdentifiers;
import org.bouncycastle.jce.X509Principal;
import org.bouncycastle.util.Strings;

@SuppressWarnings("unchecked")
class X509Util
{
    @SuppressWarnings("rawtypes")
	public static Hashtable algorithms = new Hashtable();
    @SuppressWarnings("rawtypes")
	private static Hashtable params = new Hashtable();
    @SuppressWarnings("rawtypes")
	private static Set       noParams = new HashSet();
    
    static
    {   
        algorithms.put("MD2WITHRSAENCRYPTION", PKCSObjectIdentifiers.md2WithRSAEncryption);
        algorithms.put("MD2WITHRSA", PKCSObjectIdentifiers.md2WithRSAEncryption);
        algorithms.put("MD5WITHRSAENCRYPTION", PKCSObjectIdentifiers.md5WithRSAEncryption);
        algorithms.put("MD5WITHRSA", PKCSObjectIdentifiers.md5WithRSAEncryption);
        algorithms.put("SHA1WITHRSAENCRYPTION", PKCSObjectIdentifiers.sha1WithRSAEncryption);
        algorithms.put("SHA1WITHRSA", PKCSObjectIdentifiers.sha1WithRSAEncryption);
        algorithms.put("SHA224WITHRSAENCRYPTION", PKCSObjectIdentifiers.sha224WithRSAEncryption);
        algorithms.put("SHA224WITHRSA", PKCSObjectIdentifiers.sha224WithRSAEncryption);
        algorithms.put("SHA256WITHRSAENCRYPTION", PKCSObjectIdentifiers.sha256WithRSAEncryption);
        algorithms.put("SHA256WITHRSA", PKCSObjectIdentifiers.sha256WithRSAEncryption);
        algorithms.put("SHA384WITHRSAENCRYPTION", PKCSObjectIdentifiers.sha384WithRSAEncryption);
        algorithms.put("SHA384WITHRSA", PKCSObjectIdentifiers.sha384WithRSAEncryption);
        algorithms.put("SHA512WITHRSAENCRYPTION", PKCSObjectIdentifiers.sha512WithRSAEncryption);
        algorithms.put("SHA512WITHRSA", PKCSObjectIdentifiers.sha512WithRSAEncryption);
        algorithms.put("SHA1WITHRSAANDMGF1", PKCSObjectIdentifiers.id_RSASSA_PSS);
        algorithms.put("SHA224WITHRSAANDMGF1", PKCSObjectIdentifiers.id_RSASSA_PSS);
        algorithms.put("SHA256WITHRSAANDMGF1", PKCSObjectIdentifiers.id_RSASSA_PSS);
        algorithms.put("SHA384WITHRSAANDMGF1", PKCSObjectIdentifiers.id_RSASSA_PSS);
        algorithms.put("SHA512WITHRSAANDMGF1", PKCSObjectIdentifiers.id_RSASSA_PSS);
        algorithms.put("RIPEMD160WITHRSAENCRYPTION", TeleTrusTObjectIdentifiers.rsaSignatureWithripemd160);
        algorithms.put("RIPEMD160WITHRSA", TeleTrusTObjectIdentifiers.rsaSignatureWithripemd160);
        algorithms.put("RIPEMD128WITHRSAENCRYPTION", TeleTrusTObjectIdentifiers.rsaSignatureWithripemd128);
        algorithms.put("RIPEMD128WITHRSA", TeleTrusTObjectIdentifiers.rsaSignatureWithripemd128);
        algorithms.put("RIPEMD256WITHRSAENCRYPTION", TeleTrusTObjectIdentifiers.rsaSignatureWithripemd256);
        algorithms.put("RIPEMD256WITHRSA", TeleTrusTObjectIdentifiers.rsaSignatureWithripemd256);
        algorithms.put("SHA1WITHDSA", X9ObjectIdentifiers.id_dsa_with_sha1);
        algorithms.put("DSAWITHSHA1", X9ObjectIdentifiers.id_dsa_with_sha1);
        algorithms.put("SHA224WITHDSA", NISTObjectIdentifiers.dsa_with_sha224);
        algorithms.put("SHA256WITHDSA", NISTObjectIdentifiers.dsa_with_sha256);
        algorithms.put("SHA384WITHDSA", NISTObjectIdentifiers.dsa_with_sha384);
        algorithms.put("SHA512WITHDSA", NISTObjectIdentifiers.dsa_with_sha512);
        algorithms.put("SHA1WITHECDSA", X9ObjectIdentifiers.ecdsa_with_SHA1);
        algorithms.put("ECDSAWITHSHA1", X9ObjectIdentifiers.ecdsa_with_SHA1);
        algorithms.put("SHA224WITHECDSA", X9ObjectIdentifiers.ecdsa_with_SHA224);
        algorithms.put("SHA256WITHECDSA", X9ObjectIdentifiers.ecdsa_with_SHA256);
        algorithms.put("SHA384WITHECDSA", X9ObjectIdentifiers.ecdsa_with_SHA384);
        algorithms.put("SHA512WITHECDSA", X9ObjectIdentifiers.ecdsa_with_SHA512);
        algorithms.put("GOST3411WITHGOST3410", CryptoProObjectIdentifiers.gostR3411_94_with_gostR3410_94);
        algorithms.put("GOST3411WITHGOST3410-94", CryptoProObjectIdentifiers.gostR3411_94_with_gostR3410_94);
        algorithms.put("GOST3411WITHECGOST3410", CryptoProObjectIdentifiers.gostR3411_94_with_gostR3410_2001);
        algorithms.put("GOST3411WITHECGOST3410-2001", CryptoProObjectIdentifiers.gostR3411_94_with_gostR3410_2001);
        algorithms.put("GOST3411WITHGOST3410-2001", CryptoProObjectIdentifiers.gostR3411_94_with_gostR3410_2001);

        //
        // According to RFC 3279, the ASN.1 encoding SHALL (id-dsa-with-sha1) or MUST (ecdsa-with-SHA*) omit the parameters field. 
        // The parameters field SHALL be NULL for RSA based signature algorithms.
        //
        noParams.add(X9ObjectIdentifiers.ecdsa_with_SHA1);
        noParams.add(X9ObjectIdentifiers.ecdsa_with_SHA224);
        noParams.add(X9ObjectIdentifiers.ecdsa_with_SHA256);
        noParams.add(X9ObjectIdentifiers.ecdsa_with_SHA384);
        noParams.add(X9ObjectIdentifiers.ecdsa_with_SHA512);
        noParams.add(X9ObjectIdentifiers.id_dsa_with_sha1);
        noParams.add(NISTObjectIdentifiers.dsa_with_sha224);
        noParams.add(NISTObjectIdentifiers.dsa_with_sha256);
        noParams.add(NISTObjectIdentifiers.dsa_with_sha384);
        noParams.add(NISTObjectIdentifiers.dsa_with_sha512);
        
        //
        // RFC 4491
        //
        noParams.add(CryptoProObjectIdentifiers.gostR3411_94_with_gostR3410_94);
        noParams.add(CryptoProObjectIdentifiers.gostR3411_94_with_gostR3410_2001);

        //
        // explicit params
        //
        AlgorithmIdentifier sha1AlgId = new AlgorithmIdentifier(OIWObjectIdentifiers.idSHA1, new DERNull());
        params.put("SHA1WITHRSAANDMGF1", creatPSSParams(sha1AlgId, 20));

        AlgorithmIdentifier sha224AlgId = new AlgorithmIdentifier(NISTObjectIdentifiers.id_sha224, new DERNull());
        params.put("SHA224WITHRSAANDMGF1", creatPSSParams(sha224AlgId, 28));

        AlgorithmIdentifier sha256AlgId = new AlgorithmIdentifier(NISTObjectIdentifiers.id_sha256, new DERNull());
        params.put("SHA256WITHRSAANDMGF1", creatPSSParams(sha256AlgId, 32));

        AlgorithmIdentifier sha384AlgId = new AlgorithmIdentifier(NISTObjectIdentifiers.id_sha384, new DERNull());
        params.put("SHA384WITHRSAANDMGF1", creatPSSParams(sha384AlgId, 48));

        AlgorithmIdentifier sha512AlgId = new AlgorithmIdentifier(NISTObjectIdentifiers.id_sha512, new DERNull());
        params.put("SHA512WITHRSAANDMGF1", creatPSSParams(sha512AlgId, 64));
    }

    private static RSASSAPSSparams creatPSSParams(AlgorithmIdentifier hashAlgId, int saltSize)
    {
        return new RSASSAPSSparams(
            hashAlgId,
            new AlgorithmIdentifier(PKCSObjectIdentifiers.id_mgf1, hashAlgId),
            new DERInteger(saltSize),
            new DERInteger(1));
    }

    static DERObjectIdentifier getAlgorithmOID(
        String algorithmName)
    {
        algorithmName = Strings.toUpperCase(algorithmName);
        
        if (algorithms.containsKey(algorithmName))
        {
            return (DERObjectIdentifier)algorithms.get(algorithmName);
        }
        
        return new DERObjectIdentifier(algorithmName);
    }
    
    static AlgorithmIdentifier getSigAlgID(
        DERObjectIdentifier sigOid,
        String              algorithmName)
    {
        if (noParams.contains(sigOid))
        {
            return new AlgorithmIdentifier(sigOid);
        }

        algorithmName = Strings.toUpperCase(algorithmName);

        if (params.containsKey(algorithmName))
        {
            return new AlgorithmIdentifier(sigOid, (DEREncodable)params.get(algorithmName));
        }
        else
        {
            return new AlgorithmIdentifier(sigOid, new DERNull());
        }
    }
    
    @SuppressWarnings("rawtypes")
	static Iterator getAlgNames()
    {
        Enumeration e = algorithms.keys();
        List        l = new ArrayList();
        
        while (e.hasMoreElements())
        {
            l.add(e.nextElement());
        }
        
        return l.iterator();
    }

    static Signature getSignatureInstance(
        String algorithm)
        throws NoSuchAlgorithmException
    {
        return Signature.getInstance(algorithm);
    }

    static Signature getSignatureInstance(
        String algorithm,
        String provider)
        throws NoSuchProviderException, NoSuchAlgorithmException
    {
        if (provider != null)
        {
            return Signature.getInstance(algorithm, provider);
        }
        else
        {
            return Signature.getInstance(algorithm);
        }
    }

    static byte[] calculateSignature(
        DERObjectIdentifier sigOid,
        String              sigName,
        PrivateKey          key,
        SecureRandom        random,
        ASN1Encodable       object)
        throws IOException, NoSuchAlgorithmException, InvalidKeyException, SignatureException
    {
        Signature sig;

        if (sigOid == null)
        {
            throw new IllegalStateException("no signature algorithm specified");
        }

        sig = X509Util.getSignatureInstance(sigName);

        if (random != null)
        {
            sig.initSign(key, random);
        }
        else
        {
            sig.initSign(key);
        }

        sig.update(object.getEncoded(ASN1Encodable.DER));

        return sig.sign();
    }

    static byte[] calculateSignature(
        DERObjectIdentifier sigOid,
        String              sigName,
        String              provider,
        PrivateKey          key,
        SecureRandom        random,
        ASN1Encodable       object)
        throws IOException, NoSuchProviderException, NoSuchAlgorithmException, InvalidKeyException, SignatureException
    {
        Signature sig;

        if (sigOid == null)
        {
            throw new IllegalStateException("no signature algorithm specified");
        }

        sig = X509Util.getSignatureInstance(sigName, provider);

        if (random != null)
        {
            sig.initSign(key, random);
        }
        else
        {
            sig.initSign(key);
        }

        sig.update(object.getEncoded(ASN1Encodable.DER));

        return sig.sign();
    }

    static X509Principal convertPrincipal(
        X500Principal principal)
    {
        try
        {
            return new X509Principal(principal.getEncoded());
        }
        catch (IOException e)
        {
            throw new IllegalArgumentException("cannot convert principal");
        }
    }

    static class Implementation
    {
        Object      engine;
        Provider provider;

        Implementation(
            Object      engine,
            Provider    provider)
        {
            this.engine = engine;
            this.provider = provider;
        }

        Object getEngine()
        {
            return engine;
        }

        Provider getProvider()
        {
            return provider;
        }
    }

    /**
     * see if we can find an algorithm (or its alias and what it represents) in
     * the property table for the given provider.
     */
    static Implementation getImplementation(
        String      baseName,
        String      algorithm,
        Provider    prov)
        throws NoSuchAlgorithmException
    {
        algorithm = Strings.toUpperCase(algorithm);

        String      alias;

        while ((alias = prov.getProperty("Alg.Alias." + baseName + "." + algorithm)) != null)
        {
            algorithm = alias;
        }

        String      className = prov.getProperty(baseName + "." + algorithm);

        if (className != null)
        {
            try
            {
                @SuppressWarnings("rawtypes")
				Class       cls;
                ClassLoader clsLoader = prov.getClass().getClassLoader();

                if (clsLoader != null)
                {
                    cls = clsLoader.loadClass(className);
                }
                else
                {
                    cls = Class.forName(className);
                }

                return new Implementation(cls.newInstance(), prov);
            }
            catch (ClassNotFoundException e)
            {
                throw new IllegalStateException(
                    "algorithm " + algorithm + " in provider " + prov.getName() + " but no class \"" + className + "\" found!");
            }
            catch (Exception e)
            {
                throw new IllegalStateException(
                    "algorithm " + algorithm + " in provider " + prov.getName() + " but class \"" + className + "\" inaccessible!");
            }
        }

        throw new NoSuchAlgorithmException("cannot find implementation " + algorithm + " for provider " + prov.getName());
    }

    /**
     * return an implementation for a given algorithm/provider.
     * If the provider is null, we grab the first avalaible who has the required algorithm.
     */
    static Implementation getImplementation(
        String      baseName,
        String      algorithm)
        throws NoSuchAlgorithmException
    {
        Provider[] prov = Security.getProviders();

        //
        // search every provider looking for the algorithm we want.
        //
        for (int i = 0; i != prov.length; i++)
        {
            //
            // try case insensitive
            //
            Implementation imp = getImplementation(baseName, Strings.toUpperCase(algorithm), prov[i]);
            if (imp != null)
            {
                return imp;
            }

            try
            {
                imp = getImplementation(baseName, algorithm, prov[i]);
            }
            catch (NoSuchAlgorithmException e)
            {
                // continue
            }
        }

        throw new NoSuchAlgorithmException("cannot find implementation " + algorithm);
    }

    static Provider getProvider(String provider)
        throws NoSuchProviderException
    {
        Provider prov = Security.getProvider(provider);

        if (prov == null)
        {
            throw new NoSuchProviderException("Provider " + provider + " not found");
        }

        return prov;
    }
}
 

CertificatePoliciesInfo.java

package com.secpki.jce.demo;

/**
 * 
 */

import java.util.Enumeration;
import java.util.Vector;

import org.bouncycastle.asn1.ASN1EncodableVector;
import org.bouncycastle.asn1.ASN1Sequence;
import org.bouncycastle.asn1.DEREncodable;
import org.bouncycastle.asn1.DERInteger;
import org.bouncycastle.asn1.DERObject;
import org.bouncycastle.asn1.DERObjectIdentifier;
import org.bouncycastle.asn1.DERSequence;
import org.bouncycastle.asn1.x509.DisplayText;
import org.bouncycastle.asn1.x509.NoticeReference;
import org.bouncycastle.asn1.x509.PolicyInformation;
import org.bouncycastle.asn1.x509.PolicyQualifierId;
import org.bouncycastle.asn1.x509.PolicyQualifierInfo;
import org.bouncycastle.asn1.x509.UserNotice;

/**
 * @author TBear
 *
 */
public class CertificatePoliciesInfo implements DEREncodable{
	public CertificatePoliciesInfo(){
		certPolicies = new ASN1EncodableVector();
	}
	public void add(String policy)
	{
		certPolicies.add(new PolicyInformation(new DERObjectIdentifier(policy)));
	}
	public void add(String policy,String cps)
	{
		ASN1EncodableVector policyQualifiers = new ASN1EncodableVector();
		PolicyQualifierInfo qualifierInfo = new PolicyQualifierInfo(cps);
		policyQualifiers.add(qualifierInfo.getDERObject());
		certPolicies.add(new PolicyInformation(new DERObjectIdentifier(policy),new DERSequence(policyQualifiers)));
	}
	public void add(String policy,Vector<String> cpss,Vector<UserNotice> userNotices)
	{
		ASN1EncodableVector policyQualifiers = new ASN1EncodableVector();
		
		for(int i=0;i<cpss.size();i++)
		{
			String cps = cpss.elementAt(i);
			PolicyQualifierInfo qualifierInfo = new PolicyQualifierInfo(cps);
			policyQualifiers.add(qualifierInfo.toASN1Object());
		}
		
		for(int i=0;i<userNotices.size();i++)
		{
			UserNotice userNotice = userNotices.elementAt(i);
			PolicyQualifierInfo qualifierInfo = new PolicyQualifierInfo(PolicyQualifierId.id_qt_unotice,userNotice.toASN1Object());
			policyQualifiers.add(qualifierInfo.toASN1Object());
		}
		if(policyQualifiers.size()==0){
			certPolicies.add(new PolicyInformation(new DERObjectIdentifier(policy)));
		}
		else{
			certPolicies.add(new PolicyInformation(new DERObjectIdentifier(policy),new DERSequence(policyQualifiers)));
		}
	}
	public void add(String policy,ASN1Sequence qualifierInfo)
	{
		certPolicies.add(new PolicyInformation(new DERObjectIdentifier(policy),qualifierInfo));
	}
	public DERObject getDERObject()
	{
		return new DERSequence(certPolicies);
	}
	public static UserNotice makeUserNotice(String orgType,String org,Vector<Integer> nums,String displayTextType,String displayText)
	{
		NoticeReference noticeReference = null;
		DisplayText text = null;
		int iType = 2;
		if((org!=null)&&(nums.size()>0)){
			if(orgType!=null){
				if(displayTextType.equalsIgnoreCase("IA5STRING")){
					iType = 0;
				}
				else if(displayTextType.equalsIgnoreCase("BMPSTRING")){
					iType = 1;
				}
				else if(displayTextType.equalsIgnoreCase("UTF8STRING")){
					iType = 2;
				}
				else if(displayTextType.equalsIgnoreCase("VISIBLESTRING")){
					iType = 3;
				}	
			}
	        ASN1EncodableVector asn1encodablevector = new ASN1EncodableVector();
	        DERInteger derinteger;
	        for(Enumeration<Integer> enumeration = nums.elements(); enumeration.hasMoreElements(); asn1encodablevector.add(derinteger))
	        {
	            Integer integer = enumeration.nextElement();
	            derinteger = new DERInteger(integer.intValue());
	        }
			noticeReference = new NoticeReference(iType,org, new DERSequence(asn1encodablevector));
		}
		
		if(displayText!=null){
			if(displayTextType==null){
				text = new DisplayText(displayText);
			}
			else{
				if(displayTextType.equalsIgnoreCase("IA5STRING")){
					text = new DisplayText(DisplayText.CONTENT_TYPE_IA5STRING,displayText);
				}
				else if(displayTextType.equalsIgnoreCase("BMPSTRING")){
					text = new DisplayText(DisplayText.CONTENT_TYPE_BMPSTRING,displayText);
				}
				else if(displayTextType.equalsIgnoreCase("UTF8STRING")){
					text = new DisplayText(DisplayText.CONTENT_TYPE_UTF8STRING,displayText);
				}
				else if(displayTextType.equalsIgnoreCase("VISIBLESTRING")){
					text = new DisplayText(DisplayText.CONTENT_TYPE_VISIBLESTRING,displayText);
				}
				else{
					text = new DisplayText(displayText);
				}		
			}
		}
		
		UserNotice un = new UserNotice(noticeReference,text);
		return un;
	}
	public static UserNotice makeUserNotice(String displayText)
	{
		UserNotice un = new UserNotice(null,displayText);
		return un;
	}
	
	private ASN1EncodableVector certPolicies;
}

  • 大小: 17 KB
1
2
分享到:
评论
1 楼 leaow567 2012-03-09  
好长的代码啊

相关推荐

    Java基于BC生成X509v3证书,以及部分扩展Extension的使用

    Java基于BC生成X509v3证书,以及部分扩展Extension的使用,如:BasicConstraints、CRLDIstPoint、CertificatePolicies、PolicyMappings、KeyUsage、ExtendedKeyUsage、SubjectAlternativeName、AuthorityInfoAccess...

    java-sm2 - 副本.zip

    实现了SM2中如下5部分1.生成密钥对2.签名与验签3....利用BC的X509v3CertificateBuilder组装X509国密证书生成证书,,,杂凑算法采用SM3 密钥派生算法参考国密办文档中的KDF实现具体可查看resouces中三个文档

    Dify智能体:JSON 修复.yml

    Dify智能体:JSON 修复.yml

    陕西省2025年初中学业水平考试实验操作考试试题及评分细则.zip

    陕西省2025年初中学业水平考试实验操作考试试题及评分细则.zip

    西门子S7-1200 PLC污水处理系统:博途V17版KTp1200屏程序设计与优化

    内容概要:本文详细介绍了西门子S7-1200 PLC在污水处理项目中的应用,涵盖模拟量处理、设备轮换、Modbus通讯以及事件记录等多个方面。文中展示了如何利用博途V17进行程序设计,包括具体的SCL代码实例,如液位检测的滑动窗口滤波法、提升泵的轮换逻辑、Modbus TCP对变频器的控制以及报警信息管理等。此外,还分享了一些实用技巧,如防止信号跳变、避免设备过度磨损、确保通讯稳定性和提高报警记录效率的方法。 适合人群:从事工业自动化领域的工程师和技术人员,尤其是熟悉西门子PLC和博途软件的从业者。 使用场景及目标:适用于污水处理项目的PLC编程和系统集成,旨在提高系统的稳定性和可靠性,减少维护成本并优化设备性能。 其他说明:文中不仅提供了详细的代码示例,还分享了许多来自实际项目的经验教训,帮助读者更好地理解和应用相关技术。

    基于PLC的自动药片装瓶机控制系统设计与仿真

    内容概要:本文详细介绍了基于PLC(西门子S7-1200)的自动药片装瓶机控制系统的设计与仿真过程。涵盖了硬件选型(伺服电机、光电传感器)、软件编程(梯形图、结构化文本)、关键算法(传送带定位、振动盘控制、药片计数)、异常处理以及仿真测试等方面的内容。重点讨论了如何通过精确的硬件配置和优化的控制逻辑来确保系统的稳定性和高效性。 适合人群:从事工业自动化领域的工程师和技术人员,尤其是对PLC编程和机电一体化感兴趣的读者。 使用场景及目标:适用于制药行业及其他需要自动化包装设备的企业。主要目标是提高生产效率、减少人工干预、提升产品质量和稳定性。 其他说明:文中提供了大量实际案例和调试经验,帮助读者更好地理解和应用相关技术和方法。同时强调了仿真测试的重要性,为后续的实际部署提供了宝贵的经验和改进建议。

    基于元启发式算法优化四级倒立摆系统的LQR控制器设计与应用

    内容概要:本文介绍了一种利用元启发式算法(如粒子群优化,PSO)优化线性二次调节器(LQR)控制器加权矩阵的方法,专门针对复杂的四级倒立摆系统。传统的LQR控制器设计中,加权矩阵Q的选择往往依赖于经验和试错,而这种方法难以应对高维度非线性系统的复杂性。文中详细描述了如何将控制器参数优化问题转化为多维空间搜索问题,并通过MATLAB代码展示了具体实施步骤。关键点包括:构建非线性系统的动力学模型、设计适应度函数、采用对数缩放技术避免局部最优、以及通过实验验证优化效果。结果显示,相比传统方法,PSO优化后的LQR控制器不仅提高了稳定性,还显著减少了最大控制力,同时缩短了稳定时间。 适合人群:控制系统研究人员、自动化工程专业学生、从事机器人控制或高级控制算法开发的技术人员。 使用场景及目标:适用于需要精确控制高度动态和不确定性的机械系统,特别是在处理多自由度、强耦合特性的情况下。目标是通过引入智能化的参数寻优手段,改善现有控制策略的效果,降低人为干预的需求,提高系统的鲁棒性和性能。 其他说明:文章强调了在实际应用中应注意的问题,如避免过拟合、考虑硬件限制等,并提出了未来研究方向,例如探索非对角Q矩阵的可能性。此外,还分享了一些实践经验,如如何处理高频抖动现象,以及如何结合不同类型的元启发式算法以获得更好的优化结果。

    LLC谐振变换器设计与仿真的关键技术解析及实战工具应用

    内容概要:本文详细介绍了LLC谐振变换器的设计方法及其仿真模型的应用。首先,通过参数设计程序,如Excel表格和Matlab脚本,进行关键参数的计算,确保设计符合预期性能。其次,利用Matlab/Simulink构建闭环控制仿真模型,优化PID控制器和PWM生成模块,提高系统的稳定性和响应速度。最后,提供了详细的模态分析和波形解读,帮助理解和规避常见设计陷阱。文中强调了参数选择的重要性,如电感比k值、死区时间和谐振元件的实际测量值,并分享了多个实战经验和调试技巧。 适合人群:从事电力电子设计的技术人员,尤其是对LLC谐振变换器感兴趣的工程师。 使用场景及目标:适用于需要高效、稳定的电源转换解决方案的研发项目。主要目标是掌握LLC谐振变换器的设计原理和技术要点,能够独立完成从参数计算到闭环调试的全过程。 其他说明:文中提供的工具和方法不仅有助于初学者快速入门,也能为有经验的工程师提供宝贵的参考资料。特别提到了一些容易忽视的细节和常见的错误,帮助读者避免不必要的损失。

    深度强化学习在电力系统中的应用:多智能体自主电压控制框架的Python实现

    内容概要:本文探讨了利用深度强化学习(DRL)解决现代电网复杂控制问题的方法,特别是针对自主电压控制(AVC)的应用。文中介绍了多智能体系统(MAS)与深度确定性策略梯度(MADDPG)相结合的MA-AVC算法,展示了如何将电网划分为多个子区域,每个子区域由一个智能体负责,通过集中训练和分散执行的方式进行电压控制。文章详细解释了智能体网络的设计、训练过程、奖励机制以及在伊利诺伊200总线系统上的实验验证。结果显示,相比传统方法,该算法在处理负荷突变、N-1故障和通信延迟等方面表现出显著优势。 适合人群:对深度强化学习、电力系统自动化感兴趣的科研人员和技术开发者,尤其是希望了解如何将AI应用于实际工业场景的研究者。 使用场景及目标:适用于需要提高电网稳定性和响应速度的实际应用场景,特别是在可再生能源接入和快速需求响应的要求下。目标是通过智能化手段提升电网的自适应能力和鲁棒性。 其他说明:文章提供了详细的代码示例和实验结果,帮助读者理解和复现相关算法。特别强调了奖励函数设计和电网仿真的重要性,指出了一些常见的实现陷阱及其解决方案。

    MIMO通信系统中空间编码、系统容量与信道仿真的Matlab实现

    内容概要:本文详细介绍了MIMO通信系统的三个重要方面:空间编码、系统容量计算以及信道特性仿真。首先探讨了Alamouti空时编码的具体实现方法及其在接收端的解码过程,展示了如何通过共轭转置排列实现分集增益。其次,深入讲解了MIMO系统容量公式的推导及其在Matlab中的高效实现,特别强调了使用奇异值分解提高数值稳定性的技巧。最后,讨论了信道矩阵的条件数对系统性能的影响,并提出了应对病态信道的方法如MMSE检测。 适合人群:具备一定通信理论基础和技术背景的研究人员、工程师及高校学生。 使用场景及目标:适用于希望深入了解MIMO通信系统内部机制的人群,帮助他们掌握空间编码、系统容量计算和信道建模的实际应用技能,为后续研究提供理论支持和技术储备。 其他说明:文中提供了大量实用的Matlab代码片段,便于读者快速理解和实践。同时提醒读者注意实际工程中可能遇到的问题,如数值稳定性、信道相关性和噪声增强等。

    【工业自动化】西门子PLC与测量光栅Modbus通讯实现:硬件配置、软件调试及参数设置详解文档的主要内容

    内容概要:本文档详细介绍了西门子PLC与意普测量光栅通过Modbus RTU协议进行通信的方法。硬件方面,使用了1214DC/DC/DC PLC、CB1214通讯板、ESM4810NQ-2测量光栅以及USB转485串口线缆等设备。软件部分采用博图V18进行编程,并利用调试助手modbuSCAN和sscom来辅助配置与测试。文中具体描述了创建MASTER_COMM_LOAD指令、添加MB_MASTER主站指令及轮询程序编写的步骤,包括详细的报文格式解析如站号、功能码、寄存器地址、内容及CRC校验码等信息。此外,还提供了针对光栅的初始化、波特率、奇偶校验和停止位等参数配置示例及其对应的报文解释。; 适合人群:熟悉PLC编程并希望深入了解Modbus通讯协议的应用工程师和技术人员。; 使用场景及目标:①实现PLC作为主站与测量光栅之间的稳定通信;②掌握Modbus RTU协议的具体应用细节,包括报文结构的理解与配置;③解决实际项目中可能遇到的通信问题,如线路连接、参数设置等。; 阅读建议:建议读者在阅读时结合实际硬件设备进行操作练习,同时注意文中提到的一些常见问题及其解决方案,如线序连接错误导致的乱码现象等。

    工业通信基于Qt的Modbus协议开发详解:涵盖协议原理、开发流程及应用案例

    内容概要:本文详细介绍了基于Qt的Modbus协议开发,涵盖协议原理、Qt框架支持、开发流程、代码示例及常见问题解决方案。Modbus协议支持串行通信(RTU/ASCII)和以太网(TCP/IP)两种传输方式,具有功能码定义、数据模型和通信模式等核心功能。Qt通过Qt Serial Bus模块提供对Modbus的支持,主要类有QModbusDevice、QModbusClient(含QModbusTcpClient和QModbusRtuSerialMaster)、QModbusDataUnit和QModbusReply。开发环境配置需在Qt项目的.pro文件中添加相应模块,并准备硬件设备。文中给出了Modbus客户端(TCP)的连接、读取和写入寄存器的代码示例,以及Modbus服务器的实现步骤。还列举了常见的问题与调试技巧,包括通讯不稳定、数据异常和性能优化的方法。最后介绍了该技术在工业自动化、能源管理和智能家居的应用场景。; 适合人群:具备一定Qt编程基础,对工业通信协议感兴趣的开发者。; 使用场景及目标:①学习Modbus协议的基本原理及其在Qt中的实现方法;②掌握Qt Modbus框架的核心类及其用法;③能够独立开发Modbus客户端和服务器程序,解决常见问题。; 阅读建议:本文内容详实,涉及多个知识点和技术细节,在阅读过程中应结合实际开发环境进行实践操作,以便更好地理解和掌握相关技术。

    2021 SEO新手入门:掌握谷歌优化策略

    本书《SEO for Beginners 2021》旨在向读者介绍如何使用搜索引擎优化(SEO)技术,在谷歌上提升网站排名,吸引新客户,从而实现业务增长。作者加里·戈丁和阿伦·肯尼迪通过实例和策略指导,帮助读者了解SEO的基础知识,包括关键词研究、网站设置、链接构建、社交媒体SEO优化以及如何使用谷歌分析工具来监控SEO效果。书中还特别强调了SEO在商业世界中的重要性,并提供了在谷歌广告平台上进行有效广告投放的技巧和策略。此外,作者还分享了如何通过解决SEO常见问题、设置广告账户、撰写广告文案、创建着陆页以及监控转化率等方法,进一步优化搜索引擎营销效果。

    基于Logistic映射的混沌系统图像加密算法:循环移位扰乱与扩散技术的应用

    内容概要:本文详细介绍了利用混沌系统进行图像加密的方法,重点探讨了Logistic映射生成混沌序列用于图像加密的具体实现。首先,通过Python代码生成混沌序列,确保其随机性和不可预测性。然后,采用循环移位扰乱技术对图像像素进行重新排列,使图像的像素位置发生改变。接着,通过水平和垂直扩散技术进一步打乱像素之间的关联性,增加加密强度。文中还展示了加密效果评估方法,如直方图分析、信息熵计算以及相关系数测量,验证了加密算法的有效性。 适合人群:对图像加密技术和混沌系统感兴趣的科研人员、信息安全专家及有一定编程基础的研究者。 使用场景及目标:适用于需要高强度图像加密保护的场合,如军事、医疗等领域的重要图像资料保护。目标是提供一种高效、安全的图像加密解决方案。 其他说明:文中提供了详细的Python代码示例,便于读者理解和实践。同时强调了实际应用中需要注意的问题,如参数选择和性能优化等。

    FLAC3D中双线隧道与临近基坑开挖的数值模拟及关键技术实现

    内容概要:本文详细介绍了利用FLAC3D软件进行双线隧道开挖和临近既有隧道的基坑开挖的数值模拟方法和技术要点。首先,针对隧道开挖部分,采用反力支撑法控制应力释放,并使用shell壳单元模拟喷射混凝土支护结构。其次,在基坑开挖过程中,采用了地连墙加对撑的方式,分层开挖并及时安装水平对撑。文中还提供了多个关键代码片段,展示了具体的实现步骤。此外,文章强调了监测点数据采集和处理的重要性,以及如何通过调整接触面参数解决潜在问题。最后,作者分享了一些实用技巧,如固定云图色标范围、正确设置接触面摩擦系数等。 适合人群:从事地下工程、岩土工程及相关领域的研究人员和工程师。 使用场景及目标:适用于需要进行复杂地质条件下隧道和基坑开挖数值模拟的研究人员和工程师,旨在帮助他们更好地理解和掌握FLAC3D软件的应用,提高模拟精度和效率。 其他说明:文章不仅提供了详细的代码示例,还结合实际案例进行了深入分析,有助于读者将理论知识应用于实际工程项目中。

    Android多数据类型传输(数据的交互)

    实现多数据类型的传输

    《2024年中国物联网产业创新白皮书》

    内容概要:《2024年中国物联网产业创新白皮书》由深圳市物联网产业协会与AIoT星图研究院联合编制,汇集了全国30多个省市物联网组织的智慧。白皮书系统梳理了中国物联网产业的发展历程、现状及未来趋势,涵盖了物联网的概念、产业结构、市场规模、投融资情况、面临的问题与机遇。书中详细分析了感知层、传输层、平台层及应用层的关键技术,探讨了智慧城市、智能工业、车联网、智慧医疗等九大产业物联网应用领域,以及消费物联网的发展特征与热门单品。此外,白皮书还关注了物联网数据安全、法规遵从、人才短缺等挑战,并提出了相应的解决方案。 适用人群:物联网从业者、企业决策者、政策制定者及相关研究机构。 使用场景及目标:①帮助从业者深入了解物联网产业的现状和发展趋势;②为企业决策者提供战略规划依据;③为政策制定者提供政策支持和法规制定参考;④为研究机构提供详尽的数据和案例支持。 其他说明:白皮书不仅限于技术科普,更从宏观角度结合市场情况,多维度讨论了物联网产业生态,旨在为物联网企业、从业者找到最适合的技术应用场景,促进产业健康发展。报告还特别鸣谢了参与市场调研的企业,感谢他们提供的宝贵行业信息。由于时间和资源的限制,报告可能存在信息不充分之处,欢迎各界人士提出宝贵意见。

    车辆动力学中质心侧偏角-横摆角速度相平面法的Simulink实现与应用

    内容概要:本文介绍了如何利用Simulink实现‘质心侧偏角-横摆角速度’相平面法,用于分析车辆的动力学行为。作者详细描述了模型的构建过程,包括输入模块、车辆动力学模型以及相平面生成模块的设计。通过调整车辆速度、路面附着系数和前轮转角等参数,可以直观地观察到车辆稳定性的变化。此外,文中还提供了详细的代码示例和结果分析,帮助读者更好地理解和应用这一方法。 适合人群:对车辆动力学感兴趣的工程师和技术人员,特别是那些希望通过Simulink进行车辆稳定性分析的人。 使用场景及目标:适用于需要评估车辆在不同行驶条件下稳定性的场合,如汽车制造商的研发部门、交通安全研究机构等。目标是通过相平面法直观展示车辆动态响应,辅助优化车辆设计和改进驾驶安全性能。 其他说明:附带完整代码和Simulink模型文件,便于读者动手实践。同时,文中提到的一些调试技巧和常见问题解决方法也非常有价值。

    Minecraft PEB 1.21.90.20 v8a原版.apks

    Minecraft PEB 1.21.90.20 v8a原版.apks

    【Python毕设】p116基于Flask的酒类数据分析可视化系统.zip

    项目资源包含:可运行源码+sql文件+; mysql5.7+Flask+html+jieba+pandas+pillow+scikit-learn+wordcloud+matplotlib 适用人群:学习不同技术领域的小白或进阶学习者;可作为毕设项目、课程设计、大作业、工程实训或初期项目立项。 系统功能介绍: 数据可视化:品牌数据可视化、城市价格可视化、地址销量可视化、品牌付款可视化 词云图:商品、地址、商家词云图 价格预测:模型训练、参数调整、模型预测、线性回归预测 用户模块:用户登陆/注册、个人信息修改、添加日志 管理员模块:登陆、个人信息修改、用户管理、日志管理、价格预测、酒类数据维护

Global site tag (gtag.js) - Google Analytics