`
沙舟狼客
  • 浏览: 164806 次
  • 性别: 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中三个文档

    基于模糊故障树的工业控制系统可靠性分析与Python实现

    内容概要:本文探讨了模糊故障树(FFTA)在工业控制系统可靠性分析中的应用,解决了传统故障树方法无法处理不确定数据的问题。文中介绍了模糊数的基本概念和实现方式,如三角模糊数和梯形模糊数,并展示了如何用Python实现模糊与门、或门运算以及系统故障率的计算。此外,还详细讲解了最小割集的查找方法、单元重要度的计算,并通过实例说明了这些方法的实际应用场景。最后,讨论了模糊运算在处理语言变量方面的优势,强调了在可靠性分析中处理模糊性和优化计算效率的重要性。 适合人群:从事工业控制系统设计、维护的技术人员,以及对模糊数学和可靠性分析感兴趣的科研人员。 使用场景及目标:适用于需要评估复杂系统可靠性的场合,特别是在面对不确定数据时,能够提供更准确的风险评估。目标是帮助工程师更好地理解和预测系统故障,从而制定有效的预防措施。 其他说明:文中提供的代码片段和方法可用于初步方案验证和技术探索,但在实际工程项目中还需进一步优化和完善。

    风力发电领域双馈风力发电机(DFIG)Simulink模型的构建与电流电压波形分析

    内容概要:本文详细探讨了双馈风力发电机(DFIG)在Simulink环境下的建模方法及其在不同风速条件下的电流与电压波形特征。首先介绍了DFIG的基本原理,即定子直接接入电网,转子通过双向变流器连接电网的特点。接着阐述了Simulink模型的具体搭建步骤,包括风力机模型、传动系统模型、DFIG本体模型和变流器模型的建立。文中强调了变流器控制算法的重要性,特别是在应对风速变化时,通过实时调整转子侧的电压和电流,确保电流和电压波形的良好特性。此外,文章还讨论了模型中的关键技术和挑战,如转子电流环控制策略、低电压穿越性能、直流母线电压脉动等问题,并提供了具体的解决方案和技术细节。最终,通过对故障工况的仿真测试,验证了所建模型的有效性和优越性。 适用人群:从事风力发电研究的技术人员、高校相关专业师生、对电力电子控制系统感兴趣的工程技术人员。 使用场景及目标:适用于希望深入了解DFIG工作原理、掌握Simulink建模技能的研究人员;旨在帮助读者理解DFIG在不同风速条件下的动态响应机制,为优化风力发电系统的控制策略提供理论依据和技术支持。 其他说明:文章不仅提供了详细的理论解释,还附有大量Matlab/Simulink代码片段,便于读者进行实践操作。同时,针对一些常见问题给出了实用的调试技巧,有助于提高仿真的准确性和可靠性。

    基于西门子S7-200 PLC和组态王的八层电梯控制系统设计与实现

    内容概要:本文详细介绍了基于西门子S7-200 PLC和组态王软件构建的八层电梯控制系统。首先阐述了系统的硬件配置,包括PLC的IO分配策略,如输入输出信号的具体分配及其重要性。接着深入探讨了梯形图编程逻辑,涵盖外呼信号处理、轿厢运动控制以及楼层判断等关键环节。随后讲解了组态王的画面设计,包括动画效果的实现方法,如楼层按钮绑定、轿厢移动动画和门开合效果等。最后分享了一些调试经验和注意事项,如模拟困人场景、防抖逻辑、接线艺术等。 适合人群:从事自动化控制领域的工程师和技术人员,尤其是对PLC编程和组态软件有一定基础的人群。 使用场景及目标:适用于需要设计和实施小型电梯控制系统的工程项目。主要目标是帮助读者掌握PLC编程技巧、组态画面设计方法以及系统联调经验,从而提高项目的成功率。 其他说明:文中提供了详细的代码片段和调试技巧,有助于读者更好地理解和应用相关知识点。此外,还强调了安全性和可靠性方面的考量,如急停按钮的正确接入和硬件互锁设计等。

    CarSim与Simulink联合仿真:基于MPC模型预测控制实现智能超车换道

    内容概要:本文介绍了如何将CarSim的动力学模型与Simulink的智能算法相结合,利用模型预测控制(MPC)实现车辆的智能超车换道。主要内容包括MPC控制器的设计、路径规划算法、联合仿真的配置要点以及实际应用效果。文中提供了详细的代码片段和技术细节,如权重矩阵设置、路径跟踪目标函数、安全超车条件判断等。此外,还强调了仿真过程中需要注意的关键参数配置,如仿真步长、插值设置等,以确保系统的稳定性和准确性。 适合人群:从事自动驾驶研究的技术人员、汽车工程领域的研究人员、对联合仿真感兴趣的开发者。 使用场景及目标:适用于需要进行自动驾驶车辆行为模拟的研究机构和企业,旨在提高超车换道的安全性和效率,为自动驾驶技术研发提供理论支持和技术验证。 其他说明:随包提供的案例文件已调好所有参数,可以直接导入并运行,帮助用户快速上手。文中提到的具体参数和配置方法对于初学者非常友好,能够显著降低入门门槛。

    基于单片机的鱼缸监测设计(51+1602+AD0809+18B20+UART+JKx2)#0107

    包括:源程序工程文件、Proteus仿真工程文件、论文材料、配套技术手册等 1、采用51单片机作为主控; 2、采用AD0809(仿真0808)检测"PH、氨、亚硝酸盐、硝酸盐"模拟传感; 3、采用DS18B20检测温度; 4、采用1602液晶显示检测值; 5、检测值同时串口上传,调试助手监看; 6、亦可通过串口指令对加热器、制氧机进行控制;

    风电领域双馈永磁风电机组并网仿真及短路故障分析与MPPT控制

    内容概要:本文详细介绍了双馈永磁风电机组并网仿真模型及其短路故障分析方法。首先构建了一个9MW风电场模型,由6台1.5MW双馈风机构成,通过升压变压器连接到120kV电网。文中探讨了风速模块的设计,包括渐变风、阵风和随疾风的组合形式,并提供了相应的Python和MATLAB代码示例。接着讨论了双闭环控制策略,即功率外环和电流内环的具体实现细节,以及MPPT控制用于最大化风能捕获的方法。此外,还涉及了短路故障模块的建模,包括三相电压电流特性和离散模型与phasor模型的应用。最后,强调了永磁同步机并网模型的特点和注意事项。 适合人群:从事风电领域研究的技术人员、高校相关专业师生、对风电并网仿真感兴趣的工程技术人员。 使用场景及目标:适用于风电场并网仿真研究,帮助研究人员理解和优化风电机组在不同风速条件下的性能表现,特别是在短路故障情况下的应对措施。目标是提高风电系统的稳定性和可靠性。 其他说明:文中提供的代码片段和具体参数设置有助于读者快速上手并进行实验验证。同时提醒了一些常见的错误和需要注意的地方,如离散化步长的选择、初始位置对齐等。

    空手道训练测试系统BLE106版本

    适用于空手道训练和测试场景

    【音乐创作领域AI提示词】AI音乐提示词(deepseek,豆包,kimi,chatGPT,扣子空间,manus,AI训练师)

    内容概要:本文介绍了金牌音乐作词大师的角色设定、背景经历、偏好特点、创作目标、技能优势以及工作流程。金牌音乐作词大师凭借深厚的音乐文化底蕴和丰富的创作经验,能够为不同风格的音乐创作歌词,擅长将传统文化元素与现代流行文化相结合,创作出既富有情感又触动人心的歌词。在创作过程中,会严格遵守社会主义核心价值观,尊重用户需求,提供专业修改建议,确保歌词内容健康向上。; 适合人群:有歌词创作需求的音乐爱好者、歌手或音乐制作人。; 使用场景及目标:①为特定主题或情感创作歌词,如爱情、励志等;②融合传统与现代文化元素创作独特风格的歌词;③对已有歌词进行润色和优化。; 阅读建议:阅读时可以重点关注作词大师的创作偏好、技能优势以及工作流程,有助于更好地理解如何创作出高质量的歌词。同时,在提出创作需求时,尽量详细描述自己的情感背景和期望,以便获得更贴合心意的作品。

    linux之用户管理教程.md

    linux之用户管理教程.md

    基于单片机的搬运机器人设计(51+1602+L298+BZ+KEY6)#0096

    包括:源程序工程文件、Proteus仿真工程文件、配套技术手册等 1、采用51/52单片机作为主控芯片; 2、采用1602液晶显示设置及状态; 3、采用L298驱动两个电机,模拟机械臂动力、移动底盘动力; 3、首先按键配置-待搬运物块的高度和宽度(为0不能开始搬运); 4、按下启动键开始搬运,搬运流程如下: 机械臂先把物块抓取到机器车上, 机械臂减速 机器车带着物块前往目的地 机器车减速 机械臂把物块放下来 机械臂减速 机器车回到物块堆积处(此时机器车是空车) 机器车减速 蜂鸣器提醒 按下复位键,结束本次搬运

    基于下垂控制的三相逆变器电压电流双闭环仿真及MATLAB/Simulink/PLECS实现

    内容概要:本文详细介绍了基于下垂控制的三相逆变器电压电流双闭环控制的仿真方法及其在MATLAB/Simulink和PLECS中的具体实现。首先解释了下垂控制的基本原理,即有功调频和无功调压,并给出了相应的数学表达式。随后讨论了电压环和电流环的设计与参数整定,强调了两者带宽的差异以及PI控制器的参数选择。文中还提到了一些常见的调试技巧,如锁相环的响应速度、LC滤波器的谐振点处理、死区时间设置等。此外,作者分享了一些实用的经验,如避免过度滤波、合理设置采样周期和下垂系数等。最后,通过突加负载测试展示了系统的动态响应性能。 适合人群:从事电力电子、微电网研究的技术人员,尤其是有一定MATLAB/Simulink和PLECS使用经验的研发人员。 使用场景及目标:适用于希望深入了解三相逆变器下垂控制机制的研究人员和技术人员,旨在帮助他们掌握电压电流双闭环控制的具体实现方法,提高仿真的准确性和效率。 其他说明:本文不仅提供了详细的理论讲解,还结合了大量的实战经验和调试技巧,有助于读者更好地理解和应用相关技术。

    光伏并网逆变器全栈开发资料:硬件设计、控制算法及实战经验

    内容概要:本文详细介绍了光伏并网逆变器的全栈开发资料,涵盖了从硬件设计到控制算法的各个方面。首先,文章深入探讨了功率接口板的设计,包括IGBT缓冲电路、PCB布局以及EMI滤波器的具体参数和设计思路。接着,重点讲解了主控DSP板的核心控制算法,如MPPT算法的实现及其注意事项。此外,还详细描述了驱动扩展板的门极驱动电路设计,特别是光耦隔离和驱动电阻的选择。同时,文章提供了并联仿真的具体实现方法,展示了环流抑制策略的效果。最后,分享了许多宝贵的实战经验和调试技巧,如主变压器绕制、PWM输出滤波、电流探头使用等。 适合人群:从事电力电子、光伏系统设计的研发工程师和技术爱好者。 使用场景及目标:①帮助工程师理解和掌握光伏并网逆变器的硬件设计和控制算法;②提供详细的实战经验和调试技巧,提升产品的可靠性和性能;③适用于希望深入了解光伏并网逆变器全栈开发的技术人员。 其他说明:文中不仅提供了具体的电路设计和代码实现,还分享了许多宝贵的实际操作经验和常见问题的解决方案,有助于提高开发效率和产品质量。

    机器人轨迹规划中粒子群优化与3-5-3多项式结合的时间最优路径规划

    内容概要:本文详细介绍了粒子群优化(PSO)算法与3-5-3多项式相结合的方法,在机器人轨迹规划中的应用。首先解释了粒子群算法的基本原理及其在优化轨迹参数方面的作用,随后阐述了3-5-3多项式的数学模型,特别是如何利用不同阶次的多项式确保轨迹的平滑过渡并满足边界条件。文中还提供了具体的Python代码实现,展示了如何通过粒子群算法优化时间分配,使3-5-3多项式生成的轨迹达到时间最优。此外,作者分享了一些实践经验,如加入惩罚项以避免超速,以及使用随机扰动帮助粒子跳出局部最优。 适合人群:对机器人运动规划感兴趣的科研人员、工程师和技术爱好者,尤其是有一定编程基础并对优化算法有初步了解的人士。 使用场景及目标:适用于需要精确控制机器人运动的应用场合,如工业自动化生产线、无人机导航等。主要目标是在保证轨迹平滑的前提下,尽可能缩短运动时间,提高工作效率。 其他说明:文中不仅给出了理论讲解,还有详细的代码示例和调试技巧,便于读者理解和实践。同时强调了实际应用中需要注意的问题,如系统的建模精度和安全性考量。

    【KUKA 机器人资料】:kuka机器人压铸欧洲标准.pdf

    KUKA机器人相关资料

    光子晶体中BIC与OAM激发的模拟及三维Q值计算

    内容概要:本文详细探讨了光子晶体中的束缚态在连续谱中(BIC)及其与轨道角动量(OAM)激发的关系。首先介绍了光子晶体的基本概念和BIC的独特性质,随后展示了如何通过Python代码模拟二维光子晶体中的BIC,并解释了BIC在光学器件中的潜在应用。接着讨论了OAM激发与BIC之间的联系,特别是BIC如何增强OAM激发效率。文中还提供了使用有限差分时域(FDTD)方法计算OAM的具体步骤,并介绍了计算本征态和三维Q值的方法。此外,作者分享了一些实验中的有趣发现,如特定条件下BIC表现出OAM特征,以及不同参数设置对Q值的影响。 适合人群:对光子晶体、BIC和OAM感兴趣的科研人员和技术爱好者,尤其是从事微纳光子学研究的专业人士。 使用场景及目标:适用于希望通过代码模拟深入了解光子晶体中BIC和OAM激发机制的研究人员。目标是掌握BIC和OAM的基础理论,学会使用Python和其他工具进行模拟,并理解这些现象在实际应用中的潜力。 其他说明:文章不仅提供了详细的代码示例,还分享了许多实验心得和技巧,帮助读者避免常见错误,提高模拟精度。同时,强调了物理离散化方式对数值计算结果的重要影响。

    C#联合Halcon 17.12构建工业视觉项目的配置与应用

    内容概要:本文详细介绍了如何使用C#和Halcon 17.12构建一个功能全面的工业视觉项目。主要内容涵盖项目配置、Halcon脚本的选择与修改、相机调试、模板匹配、生产履历管理、历史图像保存以及与三菱FX5U PLC的以太网通讯。文中不仅提供了具体的代码示例,还讨论了实际项目中常见的挑战及其解决方案,如环境配置、相机控制、模板匹配参数调整、PLC通讯细节、生产数据管理和图像存储策略等。 适合人群:从事工业视觉领域的开发者和技术人员,尤其是那些希望深入了解C#与Halcon结合使用的专业人士。 使用场景及目标:适用于需要开发复杂视觉检测系统的工业应用场景,旨在提高检测精度、自动化程度和数据管理效率。具体目标包括但不限于:实现高效的视觉处理流程、确保相机与PLC的无缝协作、优化模板匹配算法、有效管理生产和检测数据。 其他说明:文中强调了框架整合的重要性,并提供了一些实用的技术提示,如避免不同版本之间的兼容性问题、处理实时图像流的最佳实践、确保线程安全的操作等。此外,还提到了一些常见错误及其规避方法,帮助开发者少走弯路。

    基于Matlab的9节点配电网中分布式电源接入对节点电压影响的研究

    内容概要:本文探讨了分布式电源(DG)接入对9节点配电网节点电压的影响。首先介绍了9节点配电网模型的搭建方法,包括定义节点和线路参数。然后,通过在特定节点接入分布式电源,利用Matlab进行潮流计算,模拟DG对接入点及其周围节点电压的影响。最后,通过绘制电压波形图,直观展示了不同DG容量和接入位置对配电网电压分布的具体影响。此外,还讨论了电压越限问题以及不同线路参数对电压波动的影响。 适合人群:电力系统研究人员、电气工程学生、从事智能电网和分布式能源研究的专业人士。 使用场景及目标:适用于研究分布式电源接入对配电网电压稳定性的影响,帮助优化分布式电源的规划和配置,确保电网安全稳定运行。 其他说明:文中提供的Matlab代码和图表有助于理解和验证理论分析,同时也为后续深入研究提供了有价值的参考资料。

    电力市场领域中基于CVaR风险评估的省间交易商最优购电模型研究与实现

    内容概要:本文探讨了在两级电力市场环境中,针对省间交易商的最优购电模型的研究。文中提出了一个双层非线性优化模型,用于处理省内电力市场和省间电力交易的出清问题。该模型采用CVaR(条件风险价值)方法来评估和管理由新能源和负荷不确定性带来的风险。通过KKT条件和对偶理论,将复杂的双层非线性问题转化为更易求解的线性单层问题。此外,还通过实际案例验证了模型的有效性,展示了不同风险偏好设置对购电策略的影响。 适合人群:从事电力系统规划、运营以及风险管理的专业人士,尤其是对电力市场机制感兴趣的学者和技术专家。 使用场景及目标:适用于希望深入了解电力市场运作机制及其风险控制手段的研究人员和技术开发者。主要目标是为省间交易商提供一种科学有效的购电策略,以降低风险并提高经济效益。 其他说明:文章不仅介绍了理论模型的构建过程,还包括具体的数学公式推导和Python代码示例,便于读者理解和实践。同时强调了模型在实际应用中存在的挑战,如数据精度等问题,并指出了未来改进的方向。

Global site tag (gtag.js) - Google Analytics