Java Examples for org.bouncycastle.asn1.x509.ExtendedKeyUsage
The following java examples will help you to understand the usage of org.bouncycastle.asn1.x509.ExtendedKeyUsage. These source code samples are taken from different open source projects.
Example 1
| Project: opensc-java-master File: Usage.java View source code |
/**
* @param obj The ASN.1 object to decode.
* @return An instance of CommonObjectAttributes.
*/
public static Usage getInstance(Object obj) {
if (obj instanceof Usage)
return (Usage) obj;
if (obj instanceof ASN1Sequence) {
ASN1Sequence seq = (ASN1Sequence) obj;
Enumeration<Object> objs = seq.getObjects();
Usage ret = new Usage();
while (objs.hasMoreElements()) {
Object o = objs.nextElement();
if (o instanceof ASN1Sequence) {
ret.setExtKeyUsage(ExtendedKeyUsage.getInstance(o));
} else if (o instanceof DERBitString) {
ret.setUsage((KeyUsage) KeyUsage.getInstance(o));
} else
throw new IllegalArgumentException("Invalid member [" + o + "] in Usage ASN.1 SEQUENCE.");
}
return ret;
}
throw new IllegalArgumentException("CommonKeyAttributes must be encoded as an ASN.1 SEQUENCE.");
}Example 2
| Project: bc-java-master File: GetInstanceTest.java View source code |
public void testGetInstance() throws Exception {
doFullGetInstanceTest(DERPrintableString.class, new DERPrintableString("hello world"));
doFullGetInstanceTest(DERBMPString.class, new DERBMPString("hello world"));
doFullGetInstanceTest(DERUTF8String.class, new DERUTF8String("hello world"));
doFullGetInstanceTest(DERUniversalString.class, new DERUniversalString(new byte[20]));
doFullGetInstanceTest(DERIA5String.class, new DERIA5String("hello world"));
doFullGetInstanceTest(DERGeneralString.class, new DERGeneralString("hello world"));
doFullGetInstanceTest(DERNumericString.class, new DERNumericString("hello world"));
doFullGetInstanceTest(DERNumericString.class, new DERNumericString("99999", true));
doFullGetInstanceTest(DERT61String.class, new DERT61String("hello world"));
doFullGetInstanceTest(DERVisibleString.class, new DERVisibleString("hello world"));
doFullGetInstanceTest(ASN1Integer.class, new ASN1Integer(1));
doFullGetInstanceTest(ASN1GeneralizedTime.class, new ASN1GeneralizedTime(new Date()));
doFullGetInstanceTest(ASN1UTCTime.class, new ASN1UTCTime(new Date()));
doFullGetInstanceTest(ASN1Enumerated.class, new ASN1Enumerated(1));
CMPCertificate cmpCert = new CMPCertificate(Certificate.getInstance(cert1));
CertificateList crl = CertificateList.getInstance(v2CertList);
AttributeCertificate attributeCert = AttributeCertificate.getInstance(attrCert);
doFullGetInstanceTest(CAKeyUpdAnnContent.class, new CAKeyUpdAnnContent(cmpCert, cmpCert, cmpCert));
CertConfirmContent.getInstance(null);
CertifiedKeyPair.getInstance(null);
CertOrEncCert.getInstance(null);
CertRepMessage.getInstance(null);
doFullGetInstanceTest(CertResponse.class, new CertResponse(new ASN1Integer(1), new PKIStatusInfo(PKIStatus.granted)));
doFullGetInstanceTest(org.bouncycastle.asn1.cmp.CertStatus.class, new org.bouncycastle.asn1.cmp.CertStatus(new byte[10], BigInteger.valueOf(1), new PKIStatusInfo(PKIStatus.granted)));
doFullGetInstanceTest(Challenge.class, new Challenge(new AlgorithmIdentifier(OIWObjectIdentifiers.idSHA1, DERNull.INSTANCE), new byte[10], new byte[10]));
doFullGetInstanceTest(CMPCertificate.class, cmpCert);
doFullGetInstanceTest(CRLAnnContent.class, new CRLAnnContent(crl));
doFullGetInstanceTest(ErrorMsgContent.class, new ErrorMsgContent(new PKIStatusInfo(PKIStatus.granted), new ASN1Integer(1), new PKIFreeText("fred")));
GenMsgContent.getInstance(null);
GenRepContent.getInstance(null);
InfoTypeAndValue.getInstance(null);
KeyRecRepContent.getInstance(null);
OOBCertHash.getInstance(null);
PBMParameter.getInstance(null);
PKIBody.getInstance(null);
PKIConfirmContent.getInstance(null);
PKIFreeText.getInstance(null);
doFullGetInstanceTest(PKIFreeText.class, new PKIFreeText("hello world"));
doFullGetInstanceTest(PKIFreeText.class, new PKIFreeText(new String[] { "hello", "world" }));
doFullGetInstanceTest(PKIFreeText.class, new PKIFreeText(new DERUTF8String[] { new DERUTF8String("hello"), new DERUTF8String("world") }));
PKIHeader.getInstance(null);
PKIMessage.getInstance(null);
PKIMessages.getInstance(null);
doFullGetInstanceTest(PKIStatusInfo.class, new PKIStatusInfo(PKIStatus.rejection, new PKIFreeText("hello world"), new PKIFailureInfo(PKIFailureInfo.badAlg)));
doFullGetInstanceTest(PKIStatusInfo.class, new PKIStatusInfo(PKIStatus.granted, new PKIFreeText("hello world")));
PKIStatus.getInstance(null);
PollRepContent.getInstance(null);
PollReqContent.getInstance(null);
POPODecKeyChallContent.getInstance(null);
POPODecKeyRespContent.getInstance(null);
ProtectedPart.getInstance(null);
RevAnnContent.getInstance(null);
RevDetails.getInstance(null);
RevRepContent.getInstance(null);
RevReqContent.getInstance(null);
Attribute.getInstance(null);
Attributes.getInstance(null);
AuthenticatedData.getInstance(null);
AuthenticatedData.getInstance(null);
AuthEnvelopedData.getInstance(null);
AuthEnvelopedData.getInstance(null);
CompressedData.getInstance(null);
CompressedData.getInstance(null);
ContentInfo.getInstance(null);
EncryptedContentInfo.getInstance(null);
EncryptedData.getInstance(null);
EnvelopedData.getInstance(null);
EnvelopedData.getInstance(null);
Evidence.getInstance(null);
IssuerAndSerialNumber.getInstance(null);
KEKIdentifier.getInstance(null);
KEKIdentifier.getInstance(null);
KEKRecipientInfo.getInstance(null);
KEKRecipientInfo.getInstance(null);
KeyAgreeRecipientIdentifier.getInstance(null);
KeyAgreeRecipientIdentifier.getInstance(null);
KeyAgreeRecipientInfo.getInstance(null);
KeyAgreeRecipientInfo.getInstance(null);
KeyTransRecipientInfo.getInstance(null);
MetaData.getInstance(null);
OriginatorIdentifierOrKey.getInstance(null);
OriginatorIdentifierOrKey.getInstance(null);
OriginatorInfo.getInstance(null);
OriginatorInfo.getInstance(null);
OriginatorPublicKey.getInstance(null);
OriginatorPublicKey.getInstance(null);
OtherKeyAttribute.getInstance(null);
OtherRecipientInfo.getInstance(null);
OtherRecipientInfo.getInstance(null);
PasswordRecipientInfo.getInstance(null);
PasswordRecipientInfo.getInstance(null);
RecipientEncryptedKey.getInstance(null);
RecipientIdentifier.getInstance(null);
RecipientInfo.getInstance(null);
RecipientKeyIdentifier.getInstance(null);
RecipientKeyIdentifier.getInstance(null);
SignedData.getInstance(null);
SignerIdentifier.getInstance(null);
SignerInfo.getInstance(null);
Time.getInstance(null);
Time.getInstance(null);
TimeStampAndCRL.getInstance(null);
TimeStampedData.getInstance(null);
TimeStampTokenEvidence.getInstance(null);
AttributeTypeAndValue.getInstance(null);
doFullGetInstanceTest(CertId.class, new CertId(new GeneralName(new X500Name("CN=Test")), BigInteger.valueOf(1)));
CertReqMessages.getInstance(null);
CertReqMsg.getInstance(null);
CertRequest.getInstance(null);
CertTemplate.getInstance(null);
Controls.getInstance(null);
EncKeyWithID.getInstance(null);
EncryptedKey.getInstance(null);
EncryptedValue.getInstance(null);
OptionalValidity.getInstance(null);
PKIArchiveOptions.getInstance(null);
PKIPublicationInfo.getInstance(null);
PKMACValue.getInstance(null);
PKMACValue.getInstance(null);
POPOPrivKey.getInstance(null);
POPOSigningKeyInput.getInstance(null);
POPOSigningKey.getInstance(null);
POPOSigningKey.getInstance(null);
ProofOfPossession.getInstance(null);
SinglePubInfo.getInstance(null);
ECGOST3410ParamSetParameters.getInstance(null);
ECGOST3410ParamSetParameters.getInstance(null);
GOST28147Parameters.getInstance(null);
GOST28147Parameters.getInstance(null);
GOST3410ParamSetParameters.getInstance(null);
GOST3410ParamSetParameters.getInstance(null);
GOST3410PublicKeyAlgParameters.getInstance(null);
GOST3410PublicKeyAlgParameters.getInstance(null);
CertificateBody.getInstance(null);
CVCertificate.getInstance(null);
CVCertificateRequest.getInstance(null);
PublicKeyDataObject.getInstance(null);
UnsignedInteger.getInstance(null);
CommitmentTypeIndication.getInstance(null);
CommitmentTypeQualifier.getInstance(null);
OcspIdentifier ocspIdentifier = new OcspIdentifier(new ResponderID(new X500Name("CN=Test")), new ASN1GeneralizedTime(new Date()));
CrlListID crlListID = new CrlListID(new CrlValidatedID[] { new CrlValidatedID(new OtherHash(new byte[20])) });
OcspListID ocspListID = new OcspListID(new OcspResponsesID[] { new OcspResponsesID(ocspIdentifier) });
OtherRevRefs otherRevRefs = new OtherRevRefs(new ASN1ObjectIdentifier("1.2.1"), new DERSequence());
OtherRevVals otherRevVals = new OtherRevVals(new ASN1ObjectIdentifier("1.2.1"), new DERSequence());
CrlOcspRef crlOcspRef = new CrlOcspRef(crlListID, ocspListID, otherRevRefs);
doFullGetInstanceTest(CompleteRevocationRefs.class, new CompleteRevocationRefs(new CrlOcspRef[] { crlOcspRef, crlOcspRef }));
doFullGetInstanceTest(CrlIdentifier.class, new CrlIdentifier(new X500Name("CN=Test"), new ASN1UTCTime(new Date()), BigInteger.valueOf(1)));
doFullGetInstanceTest(CrlListID.class, crlListID);
doFullGetInstanceTest(CrlOcspRef.class, crlOcspRef);
doFullGetInstanceTest(CrlValidatedID.class, new CrlValidatedID(new OtherHash(new byte[20])));
doFullGetInstanceTest(OcspIdentifier.class, ocspIdentifier);
doFullGetInstanceTest(OcspListID.class, ocspListID);
doFullGetInstanceTest(OcspResponsesID.class, new OcspResponsesID(ocspIdentifier));
OtherHashAlgAndValue otherHashAlgAndValue = new OtherHashAlgAndValue(new AlgorithmIdentifier(OIWObjectIdentifiers.idSHA1, DERNull.INSTANCE), new DEROctetString(new byte[10]));
doFullGetInstanceTest(OtherHashAlgAndValue.class, otherHashAlgAndValue);
OtherHash.getInstance(null);
doFullGetInstanceTest(OtherRevRefs.class, otherRevRefs);
doFullGetInstanceTest(OtherRevVals.class, otherRevVals);
doFullGetInstanceTest(RevocationValues.class, new RevocationValues(new CertificateList[] { crl }, null, otherRevVals));
SignaturePolicyId signaturePolicyId = new SignaturePolicyId(new ASN1ObjectIdentifier("1.2.1"), otherHashAlgAndValue);
doFullGetInstanceTest(SignaturePolicyIdentifier.class, new SignaturePolicyIdentifier());
doFullGetInstanceTest(SignaturePolicyIdentifier.class, new SignaturePolicyIdentifier(signaturePolicyId));
doFullGetInstanceTest(SignaturePolicyId.class, signaturePolicyId);
doFullGetInstanceTest(SignerAttribute.class, new SignerAttribute(new org.bouncycastle.asn1.x509.Attribute[] { new org.bouncycastle.asn1.x509.Attribute(new ASN1ObjectIdentifier("1.2.1"), new DERSet()) }));
doFullGetInstanceTest(SignerAttribute.class, new SignerAttribute(attributeCert));
ASN1EncodableVector postalAddr = new ASN1EncodableVector();
postalAddr.add(new DERUTF8String("line 1"));
postalAddr.add(new DERUTF8String("line 2"));
doFullGetInstanceTest(SignerLocation.class, new SignerLocation(new DERUTF8String("AU"), new DERUTF8String("Melbourne"), new DERSequence(postalAddr)));
doFullGetInstanceTest(SigPolicyQualifierInfo.class, new SigPolicyQualifierInfo(new ASN1ObjectIdentifier("1.2.1"), new DERSequence()));
SigPolicyQualifiers.getInstance(null);
SPuri.getInstance(null);
Vector v = new Vector();
v.add(Integers.valueOf(1));
v.add(BigInteger.valueOf(2));
NoticeReference noticeReference = new NoticeReference("BC", v);
doFullGetInstanceTest(SPUserNotice.class, new SPUserNotice(noticeReference, new DisplayText("hello world")));
ContentHints.getInstance(null);
ContentIdentifier.getInstance(null);
ESSCertID.getInstance(null);
ESSCertIDv2.getInstance(null);
OtherCertID.getInstance(null);
OtherSigningCertificate.getInstance(null);
SigningCertificate.getInstance(null);
SigningCertificateV2.getInstance(null);
CscaMasterList.getInstance(null);
DataGroupHash.getInstance(null);
LDSSecurityObject.getInstance(null);
LDSVersionInfo.getInstance(null);
CAST5CBCParameters.getInstance(null);
IDEACBCPar.getInstance(null);
PublicKeyAndChallenge.getInstance(null);
BasicOCSPResponse.getInstance(null);
BasicOCSPResponse.getInstance(null);
doFullGetInstanceTest(CertID.class, new CertID(new AlgorithmIdentifier(OIWObjectIdentifiers.idSHA1, DERNull.INSTANCE), new DEROctetString(new byte[1]), new DEROctetString(new byte[1]), new ASN1Integer(1)));
CertStatus.getInstance(null);
CertStatus.getInstance(null);
CrlID.getInstance(null);
OCSPRequest.getInstance(null);
OCSPRequest.getInstance(null);
OCSPResponse.getInstance(null);
OCSPResponse.getInstance(null);
OCSPResponseStatus.getInstance(null);
Request.getInstance(null);
Request.getInstance(null);
ResponderID.getInstance(null);
ResponderID.getInstance(null);
ResponseBytes.getInstance(null);
ResponseBytes.getInstance(null);
ResponseData.getInstance(null);
ResponseData.getInstance(null);
RevokedInfo.getInstance(null);
RevokedInfo.getInstance(null);
Signature.getInstance(null);
Signature.getInstance(null);
SingleResponse.getInstance(null);
SingleResponse.getInstance(null);
TBSRequest.getInstance(null);
TBSRequest.getInstance(null);
Attribute.getInstance(null);
AuthenticatedSafe.getInstance(null);
CertificationRequestInfo.getInstance(null);
CertificationRequest.getInstance(null);
ContentInfo.getInstance(null);
DHParameter.getInstance(null);
EncryptedData.getInstance(null);
EncryptedPrivateKeyInfo.getInstance(null);
AlgorithmIdentifier.getInstance(null);
IssuerAndSerialNumber.getInstance(null);
MacData.getInstance(null);
PBEParameter.getInstance(null);
PBES2Parameters.getInstance(null);
PBKDF2Params.getInstance(null);
Pfx.getInstance(null);
PKCS12PBEParams.getInstance(null);
PrivateKeyInfo.getInstance(null);
PrivateKeyInfo.getInstance(null);
RC2CBCParameter.getInstance(null);
RSAESOAEPparams.getInstance(null);
RSAPrivateKey.getInstance(null);
RSAPrivateKey.getInstance(null);
RSAPublicKey.getInstance(null);
RSAPublicKey.getInstance(null);
RSASSAPSSparams.getInstance(null);
SafeBag.getInstance(null);
SignedData.getInstance(null);
SignerInfo.getInstance(null);
ECPrivateKey.getInstance(null);
SMIMECapabilities.getInstance(null);
SMIMECapability.getInstance(null);
Accuracy.getInstance(null);
MessageImprint.getInstance(null);
TimeStampReq.getInstance(null);
TimeStampResp.getInstance(null);
TSTInfo.getInstance(null);
AttributeTypeAndValue.getInstance(null);
DirectoryString.getInstance(null);
DirectoryString.getInstance(null);
RDN.getInstance(null);
X500Name.getInstance(null);
X500Name.getInstance(null);
AccessDescription.getInstance(null);
AlgorithmIdentifier.getInstance(null);
AlgorithmIdentifier.getInstance(null);
AttCertIssuer.getInstance(null);
AttCertIssuer.getInstance(null);
AttCertValidityPeriod.getInstance(null);
AttributeCertificateInfo.getInstance(null);
AttributeCertificateInfo.getInstance(null);
AttributeCertificate.getInstance(null);
Attribute.getInstance(null);
AuthorityInformationAccess.getInstance(null);
AuthorityKeyIdentifier.getInstance(null);
AuthorityKeyIdentifier.getInstance(null);
BasicConstraints.getInstance(null);
BasicConstraints.getInstance(null);
Certificate.getInstance(null);
Certificate.getInstance(null);
CertificateList.getInstance(null);
CertificateList.getInstance(null);
CertificatePair.getInstance(null);
CertificatePolicies.getInstance(null);
CertificatePolicies.getInstance(null);
CRLDistPoint.getInstance(null);
CRLDistPoint.getInstance(null);
CRLNumber.getInstance(null);
CRLReason.getInstance(null);
DigestInfo.getInstance(null);
DigestInfo.getInstance(null);
DisplayText.getInstance(null);
DisplayText.getInstance(null);
DistributionPoint.getInstance(null);
DistributionPoint.getInstance(null);
DistributionPointName.getInstance(null);
DistributionPointName.getInstance(null);
DSAParameter.getInstance(null);
DSAParameter.getInstance(null);
ExtendedKeyUsage.getInstance(null);
ExtendedKeyUsage.getInstance(null);
Extensions.getInstance(null);
Extensions.getInstance(null);
GeneralName.getInstance(null);
GeneralName.getInstance(null);
GeneralNames.getInstance(null);
GeneralNames.getInstance(null);
GeneralSubtree generalSubtree = new GeneralSubtree(new GeneralName(new X500Name("CN=Test")));
ASN1ObjectIdentifier algOid = new ASN1ObjectIdentifier("1.2.1");
ObjectDigestInfo objectDigestInfo = new ObjectDigestInfo(ObjectDigestInfo.otherObjectDigest, algOid, new AlgorithmIdentifier(algOid), new byte[20]);
doFullGetInstanceTest(GeneralSubtree.class, generalSubtree);
doFullGetInstanceTest(Holder.class, new Holder(objectDigestInfo));
IetfAttrSyntax.getInstance(null);
IssuerSerial.getInstance(null);
IssuerSerial.getInstance(null);
IssuingDistributionPoint.getInstance(null);
IssuingDistributionPoint.getInstance(null);
DERBitString.getInstance(null);
v.clear();
v.add(generalSubtree);
doFullGetInstanceTest(NameConstraints.class, new NameConstraints(null, null));
doFullGetInstanceTest(NoticeReference.class, noticeReference);
doFullGetInstanceTest(ObjectDigestInfo.class, objectDigestInfo);
PolicyInformation.getInstance(null);
PolicyMappings.getInstance(null);
PolicyQualifierInfo.getInstance(null);
PrivateKeyUsagePeriod.getInstance(null);
doFullGetInstanceTest(RoleSyntax.class, new RoleSyntax(new GeneralNames(new GeneralName(new X500Name("CN=Test"))), new GeneralName(GeneralName.uniformResourceIdentifier, "http://bc")));
org.bouncycastle.asn1.pkcs.RSAPublicKey.getInstance(null);
RSAPublicKey.getInstance(null);
SubjectDirectoryAttributes.getInstance(null);
SubjectKeyIdentifier.getInstance(null);
SubjectKeyIdentifier.getInstance(null);
SubjectPublicKeyInfo.getInstance(null);
SubjectPublicKeyInfo.getInstance(null);
TargetInformation.getInstance(null);
Target.getInstance(null);
Targets.getInstance(null);
TBSCertificate.getInstance(null);
TBSCertificate.getInstance(null);
TBSCertificateStructure.getInstance(null);
TBSCertificateStructure.getInstance(null);
TBSCertList.CRLEntry.getInstance(null);
TBSCertList.getInstance(null);
TBSCertList.getInstance(null);
Time.getInstance(null);
Time.getInstance(null);
doFullGetInstanceTest(UserNotice.class, new UserNotice(noticeReference, "hello world"));
V2Form.getInstance(null);
V2Form.getInstance(null);
X509CertificateStructure.getInstance(null);
X509CertificateStructure.getInstance(null);
X509Extensions.getInstance(null);
X509Extensions.getInstance(null);
X500Name.getInstance(null);
X500Name.getInstance(null);
DHDomainParameters.getInstance(null);
DHDomainParameters.getInstance(null);
DHPublicKey.getInstance(null);
DHPublicKey.getInstance(null);
DHValidationParms.getInstance(null);
DHValidationParms.getInstance(null);
X962Parameters.getInstance(null);
X962Parameters.getInstance(null);
X9ECParameters.getInstance(null);
MQVuserKeyingMaterial.getInstance(null);
MQVuserKeyingMaterial.getInstance(null);
CertHash.getInstance(null);
RequestedCertificate.getInstance(null);
RequestedCertificate.getInstance(null);
AdditionalInformationSyntax.getInstance(null);
Admissions.getInstance(null);
AdmissionSyntax.getInstance(null);
DeclarationOfMajority.getInstance(null);
MonetaryLimit.getInstance(null);
NamingAuthority.getInstance(null);
NamingAuthority.getInstance(null);
ProcurationSyntax.getInstance(null);
ProfessionInfo.getInstance(null);
Restriction.getInstance(null);
BiometricData.getInstance(null);
Iso4217CurrencyCode.getInstance(null);
MonetaryValue.getInstance(null);
QCStatement.getInstance(null);
SemanticsInformation.getInstance(null);
TypeOfBiometricData.getInstance(null);
NameOrPseudonym.getInstance(null);
PersonalData.getInstance(null);
}Example 3
| Project: bergamot-master File: RSAUtil.java View source code |
public static CertificatePair generateCertificate(String DN, SerialNum serial, int days, int keySize, KeyType type, PublicKey key, CertificatePair issuer) throws Exception {
// validate
if ((KeyType.INTERMEDIATE == type || KeyType.CLIENT == type || KeyType.SERVER == type) && issuer == null)
throw new IllegalArgumentException("Issue must be given to sign requested key type");
if (issuer == null && key != null)
throw new IllegalArgumentException("When signing a given public key, an issuer must be given");
// generate the key pair
KeyPair pair = null;
if (key == null) {
pair = generateRSAKeyPair(keySize);
key = pair.getPublic();
}
// not before
Calendar now = Calendar.getInstance();
// not after
Calendar expiry = Calendar.getInstance();
expiry.add(Calendar.DAY_OF_YEAR, days);
// subject DN
X500Principal subjectDN = new X500Principal(DN);
// issuer DN
X500Principal issuerDN = issuer == null ? subjectDN : issuer.getCertificate().getSubjectX500Principal();
// build the certificate
JcaX509v3CertificateBuilder builder = new JcaX509v3CertificateBuilder(issuerDN, serial.toBigInt(), now.getTime(), expiry.getTime(), subjectDN, key);
// set extensions
JcaX509ExtensionUtils utils = new JcaX509ExtensionUtils();
// subject public key
builder.addExtension(Extension.subjectKeyIdentifier, false, utils.createSubjectKeyIdentifier(key));
// issuer public key
if (issuer == null) {
builder.addExtension(Extension.authorityKeyIdentifier, false, utils.createAuthorityKeyIdentifier(key));
} else {
builder.addExtension(Extension.authorityKeyIdentifier, false, utils.createAuthorityKeyIdentifier(issuer.getCertificate()));
}
// constraints
if (KeyType.CA == type || KeyType.INTERMEDIATE == type) {
builder.addExtension(Extension.basicConstraints, true, new BasicConstraints(true));
builder.addExtension(Extension.keyUsage, true, new KeyUsage(KeyUsage.keyEncipherment | KeyUsage.cRLSign | KeyUsage.dataEncipherment | KeyUsage.digitalSignature | KeyUsage.keyCertSign));
builder.addExtension(Extension.extendedKeyUsage, true, new ExtendedKeyUsage(KeyPurposeId.anyExtendedKeyUsage));
} else if (KeyType.SERVER == type) {
builder.addExtension(Extension.basicConstraints, true, new BasicConstraints(false));
builder.addExtension(Extension.extendedKeyUsage, true, new ExtendedKeyUsage(KeyPurposeId.id_kp_serverAuth));
} else if (KeyType.CLIENT == type) {
builder.addExtension(Extension.basicConstraints, true, new BasicConstraints(false));
builder.addExtension(Extension.extendedKeyUsage, true, new ExtendedKeyUsage(KeyPurposeId.id_kp_clientAuth));
}
// the signer
ContentSigner signer = new JcaContentSignerBuilder("SHA256WithRSA").build(issuer == null ? pair.getPrivate() : issuer.getKey());
// go go go
X509CertificateHolder theCertHolder = builder.build(signer);
// extract the actual fucking certificate
X509Certificate theCert = new JcaX509CertificateConverter().getCertificate(theCertHolder);
// check
theCert.verify(issuer == null ? key : issuer.getCertificate().getPublicKey());
// encode
return new CertificatePair(theCert, pair == null ? null : pair.getPrivate());
}Example 4
| Project: capedwarf-blue-master File: CertificateGenerator.java View source code |
public X509Certificate generateCertificate(KeyPair pair, String dn) {
try {
X509v3CertificateBuilder builder = new X509v3CertificateBuilder(new X500Name("CN=" + dn), BigInteger.valueOf(new SecureRandom().nextLong()), new Date(System.currentTimeMillis() - 10000), new Date(System.currentTimeMillis() + 24L * 3600 * 1000), new X500Name("CN=" + dn), SubjectPublicKeyInfo.getInstance(pair.getPublic().getEncoded()));
builder.addExtension(X509Extension.basicConstraints, true, new BasicConstraints(false));
builder.addExtension(X509Extension.keyUsage, true, new KeyUsage(KeyUsage.digitalSignature));
builder.addExtension(X509Extension.extendedKeyUsage, true, new ExtendedKeyUsage(KeyPurposeId.id_kp_clientAuth));
X509CertificateHolder holder = builder.build(createContentSigner(pair));
Certificate certificate = holder.toASN1Structure();
return convertToJavaCertificate(certificate);
} catch (CertificateEncodingException e) {
throw new RuntimeException("Cannot generate X509 certificate", e);
} catch (OperatorCreationException e) {
throw new RuntimeException("Cannot generate X509 certificate", e);
} catch (CertIOException e) {
throw new RuntimeException("Cannot generate X509 certificate", e);
} catch (IOException e) {
throw new RuntimeException("Cannot generate X509 certificate", e);
} catch (CertificateException e) {
throw new RuntimeException("Cannot generate X509 certificate", e);
}
}Example 5
| Project: irma_future_id-master File: GetInstanceTest.java View source code |
public void testGetInstance() throws Exception {
doFullGetInstanceTest(DERPrintableString.class, new DERPrintableString("hello world"));
doFullGetInstanceTest(DERBMPString.class, new DERBMPString("hello world"));
doFullGetInstanceTest(DERUTF8String.class, new DERUTF8String("hello world"));
doFullGetInstanceTest(DERUniversalString.class, new DERUniversalString(new byte[20]));
doFullGetInstanceTest(DERIA5String.class, new DERIA5String("hello world"));
doFullGetInstanceTest(DERGeneralString.class, new DERGeneralString("hello world"));
doFullGetInstanceTest(DERNumericString.class, new DERNumericString("hello world"));
doFullGetInstanceTest(DERNumericString.class, new DERNumericString("99999", true));
doFullGetInstanceTest(DERT61String.class, new DERT61String("hello world"));
doFullGetInstanceTest(DERVisibleString.class, new DERVisibleString("hello world"));
doFullGetInstanceTest(ASN1Integer.class, new ASN1Integer(1));
doFullGetInstanceTest(ASN1GeneralizedTime.class, new ASN1GeneralizedTime(new Date()));
doFullGetInstanceTest(ASN1UTCTime.class, new ASN1UTCTime(new Date()));
doFullGetInstanceTest(ASN1Enumerated.class, new ASN1Enumerated(1));
CMPCertificate cmpCert = new CMPCertificate(Certificate.getInstance(cert1));
CertificateList crl = CertificateList.getInstance(v2CertList);
AttributeCertificate attributeCert = AttributeCertificate.getInstance(attrCert);
doFullGetInstanceTest(CAKeyUpdAnnContent.class, new CAKeyUpdAnnContent(cmpCert, cmpCert, cmpCert));
CertConfirmContent.getInstance(null);
CertifiedKeyPair.getInstance(null);
CertOrEncCert.getInstance(null);
CertRepMessage.getInstance(null);
doFullGetInstanceTest(CertResponse.class, new CertResponse(new ASN1Integer(1), new PKIStatusInfo(PKIStatus.granted)));
doFullGetInstanceTest(org.bouncycastle.asn1.cmp.CertStatus.class, new org.bouncycastle.asn1.cmp.CertStatus(new byte[10], BigInteger.valueOf(1), new PKIStatusInfo(PKIStatus.granted)));
doFullGetInstanceTest(Challenge.class, new Challenge(new AlgorithmIdentifier(OIWObjectIdentifiers.idSHA1, DERNull.INSTANCE), new byte[10], new byte[10]));
doFullGetInstanceTest(CMPCertificate.class, cmpCert);
doFullGetInstanceTest(CRLAnnContent.class, new CRLAnnContent(crl));
doFullGetInstanceTest(ErrorMsgContent.class, new ErrorMsgContent(new PKIStatusInfo(PKIStatus.granted), new ASN1Integer(1), new PKIFreeText("fred")));
GenMsgContent.getInstance(null);
GenRepContent.getInstance(null);
InfoTypeAndValue.getInstance(null);
KeyRecRepContent.getInstance(null);
OOBCertHash.getInstance(null);
PBMParameter.getInstance(null);
PKIBody.getInstance(null);
PKIConfirmContent.getInstance(null);
PKIFreeText.getInstance(null);
doFullGetInstanceTest(PKIFreeText.class, new PKIFreeText("hello world"));
doFullGetInstanceTest(PKIFreeText.class, new PKIFreeText(new String[] { "hello", "world" }));
doFullGetInstanceTest(PKIFreeText.class, new PKIFreeText(new DERUTF8String[] { new DERUTF8String("hello"), new DERUTF8String("world") }));
PKIHeader.getInstance(null);
PKIMessage.getInstance(null);
PKIMessages.getInstance(null);
doFullGetInstanceTest(PKIStatusInfo.class, new PKIStatusInfo(PKIStatus.rejection, new PKIFreeText("hello world"), new PKIFailureInfo(PKIFailureInfo.badAlg)));
doFullGetInstanceTest(PKIStatusInfo.class, new PKIStatusInfo(PKIStatus.granted, new PKIFreeText("hello world")));
PKIStatus.getInstance(null);
PollRepContent.getInstance(null);
PollReqContent.getInstance(null);
POPODecKeyChallContent.getInstance(null);
POPODecKeyRespContent.getInstance(null);
ProtectedPart.getInstance(null);
RevAnnContent.getInstance(null);
RevDetails.getInstance(null);
RevRepContent.getInstance(null);
RevReqContent.getInstance(null);
Attribute.getInstance(null);
Attributes.getInstance(null);
AuthenticatedData.getInstance(null);
AuthenticatedData.getInstance(null);
AuthEnvelopedData.getInstance(null);
AuthEnvelopedData.getInstance(null);
CompressedData.getInstance(null);
CompressedData.getInstance(null);
ContentInfo.getInstance(null);
EncryptedContentInfo.getInstance(null);
EncryptedData.getInstance(null);
EnvelopedData.getInstance(null);
EnvelopedData.getInstance(null);
Evidence.getInstance(null);
IssuerAndSerialNumber.getInstance(null);
KEKIdentifier.getInstance(null);
KEKIdentifier.getInstance(null);
KEKRecipientInfo.getInstance(null);
KEKRecipientInfo.getInstance(null);
KeyAgreeRecipientIdentifier.getInstance(null);
KeyAgreeRecipientIdentifier.getInstance(null);
KeyAgreeRecipientInfo.getInstance(null);
KeyAgreeRecipientInfo.getInstance(null);
KeyTransRecipientInfo.getInstance(null);
MetaData.getInstance(null);
OriginatorIdentifierOrKey.getInstance(null);
OriginatorIdentifierOrKey.getInstance(null);
OriginatorInfo.getInstance(null);
OriginatorInfo.getInstance(null);
OriginatorPublicKey.getInstance(null);
OriginatorPublicKey.getInstance(null);
OtherKeyAttribute.getInstance(null);
OtherRecipientInfo.getInstance(null);
OtherRecipientInfo.getInstance(null);
PasswordRecipientInfo.getInstance(null);
PasswordRecipientInfo.getInstance(null);
RecipientEncryptedKey.getInstance(null);
RecipientIdentifier.getInstance(null);
RecipientInfo.getInstance(null);
RecipientKeyIdentifier.getInstance(null);
RecipientKeyIdentifier.getInstance(null);
SignedData.getInstance(null);
SignerIdentifier.getInstance(null);
SignerInfo.getInstance(null);
Time.getInstance(null);
Time.getInstance(null);
TimeStampAndCRL.getInstance(null);
TimeStampedData.getInstance(null);
TimeStampTokenEvidence.getInstance(null);
AttributeTypeAndValue.getInstance(null);
doFullGetInstanceTest(CertId.class, new CertId(new GeneralName(new X500Name("CN=Test")), BigInteger.valueOf(1)));
CertReqMessages.getInstance(null);
CertReqMsg.getInstance(null);
CertRequest.getInstance(null);
CertTemplate.getInstance(null);
Controls.getInstance(null);
EncKeyWithID.getInstance(null);
EncryptedKey.getInstance(null);
EncryptedValue.getInstance(null);
OptionalValidity.getInstance(null);
PKIArchiveOptions.getInstance(null);
PKIPublicationInfo.getInstance(null);
PKMACValue.getInstance(null);
PKMACValue.getInstance(null);
POPOPrivKey.getInstance(null);
POPOSigningKeyInput.getInstance(null);
POPOSigningKey.getInstance(null);
POPOSigningKey.getInstance(null);
ProofOfPossession.getInstance(null);
SinglePubInfo.getInstance(null);
ECGOST3410ParamSetParameters.getInstance(null);
ECGOST3410ParamSetParameters.getInstance(null);
GOST28147Parameters.getInstance(null);
GOST28147Parameters.getInstance(null);
GOST3410ParamSetParameters.getInstance(null);
GOST3410ParamSetParameters.getInstance(null);
GOST3410PublicKeyAlgParameters.getInstance(null);
GOST3410PublicKeyAlgParameters.getInstance(null);
CertificateBody.getInstance(null);
CVCertificate.getInstance(null);
CVCertificateRequest.getInstance(null);
PublicKeyDataObject.getInstance(null);
UnsignedInteger.getInstance(null);
CommitmentTypeIndication.getInstance(null);
CommitmentTypeQualifier.getInstance(null);
OcspIdentifier ocspIdentifier = new OcspIdentifier(new ResponderID(new X500Name("CN=Test")), new ASN1GeneralizedTime(new Date()));
CrlListID crlListID = new CrlListID(new CrlValidatedID[] { new CrlValidatedID(new OtherHash(new byte[20])) });
OcspListID ocspListID = new OcspListID(new OcspResponsesID[] { new OcspResponsesID(ocspIdentifier) });
OtherRevRefs otherRevRefs = new OtherRevRefs(new ASN1ObjectIdentifier("1.2.1"), new DERSequence());
OtherRevVals otherRevVals = new OtherRevVals(new ASN1ObjectIdentifier("1.2.1"), new DERSequence());
CrlOcspRef crlOcspRef = new CrlOcspRef(crlListID, ocspListID, otherRevRefs);
doFullGetInstanceTest(CompleteRevocationRefs.class, new CompleteRevocationRefs(new CrlOcspRef[] { crlOcspRef, crlOcspRef }));
doFullGetInstanceTest(CrlIdentifier.class, new CrlIdentifier(new X500Name("CN=Test"), new ASN1UTCTime(new Date()), BigInteger.valueOf(1)));
doFullGetInstanceTest(CrlListID.class, crlListID);
doFullGetInstanceTest(CrlOcspRef.class, crlOcspRef);
doFullGetInstanceTest(CrlValidatedID.class, new CrlValidatedID(new OtherHash(new byte[20])));
doFullGetInstanceTest(OcspIdentifier.class, ocspIdentifier);
doFullGetInstanceTest(OcspListID.class, ocspListID);
doFullGetInstanceTest(OcspResponsesID.class, new OcspResponsesID(ocspIdentifier));
OtherHashAlgAndValue otherHashAlgAndValue = new OtherHashAlgAndValue(new AlgorithmIdentifier(OIWObjectIdentifiers.idSHA1, DERNull.INSTANCE), new DEROctetString(new byte[10]));
doFullGetInstanceTest(OtherHashAlgAndValue.class, otherHashAlgAndValue);
OtherHash.getInstance(null);
doFullGetInstanceTest(OtherRevRefs.class, otherRevRefs);
doFullGetInstanceTest(OtherRevVals.class, otherRevVals);
doFullGetInstanceTest(RevocationValues.class, new RevocationValues(new CertificateList[] { crl }, null, otherRevVals));
SignaturePolicyId signaturePolicyId = new SignaturePolicyId(new ASN1ObjectIdentifier("1.2.1"), otherHashAlgAndValue);
doFullGetInstanceTest(SignaturePolicyIdentifier.class, new SignaturePolicyIdentifier());
doFullGetInstanceTest(SignaturePolicyIdentifier.class, new SignaturePolicyIdentifier(signaturePolicyId));
doFullGetInstanceTest(SignaturePolicyId.class, signaturePolicyId);
doFullGetInstanceTest(SignerAttribute.class, new SignerAttribute(new org.bouncycastle.asn1.x509.Attribute[] { new org.bouncycastle.asn1.x509.Attribute(new ASN1ObjectIdentifier("1.2.1"), new DERSet()) }));
doFullGetInstanceTest(SignerAttribute.class, new SignerAttribute(attributeCert));
ASN1EncodableVector postalAddr = new ASN1EncodableVector();
postalAddr.add(new DERUTF8String("line 1"));
postalAddr.add(new DERUTF8String("line 2"));
doFullGetInstanceTest(SignerLocation.class, new SignerLocation(new DERUTF8String("AU"), new DERUTF8String("Melbourne"), new DERSequence(postalAddr)));
doFullGetInstanceTest(SigPolicyQualifierInfo.class, new SigPolicyQualifierInfo(new ASN1ObjectIdentifier("1.2.1"), new DERSequence()));
SigPolicyQualifiers.getInstance(null);
SPuri.getInstance(null);
Vector v = new Vector();
v.add(Integers.valueOf(1));
v.add(BigInteger.valueOf(2));
NoticeReference noticeReference = new NoticeReference("BC", v);
doFullGetInstanceTest(SPUserNotice.class, new SPUserNotice(noticeReference, new DisplayText("hello world")));
ContentHints.getInstance(null);
ContentIdentifier.getInstance(null);
ESSCertID.getInstance(null);
ESSCertIDv2.getInstance(null);
OtherCertID.getInstance(null);
OtherSigningCertificate.getInstance(null);
SigningCertificate.getInstance(null);
SigningCertificateV2.getInstance(null);
CscaMasterList.getInstance(null);
DataGroupHash.getInstance(null);
LDSSecurityObject.getInstance(null);
LDSVersionInfo.getInstance(null);
CAST5CBCParameters.getInstance(null);
IDEACBCPar.getInstance(null);
PublicKeyAndChallenge.getInstance(null);
BasicOCSPResponse.getInstance(null);
BasicOCSPResponse.getInstance(null);
doFullGetInstanceTest(CertID.class, new CertID(new AlgorithmIdentifier(OIWObjectIdentifiers.idSHA1, DERNull.INSTANCE), new DEROctetString(new byte[1]), new DEROctetString(new byte[1]), new ASN1Integer(1)));
CertStatus.getInstance(null);
CertStatus.getInstance(null);
CrlID.getInstance(null);
OCSPRequest.getInstance(null);
OCSPRequest.getInstance(null);
OCSPResponse.getInstance(null);
OCSPResponse.getInstance(null);
OCSPResponseStatus.getInstance(null);
Request.getInstance(null);
Request.getInstance(null);
ResponderID.getInstance(null);
ResponderID.getInstance(null);
ResponseBytes.getInstance(null);
ResponseBytes.getInstance(null);
ResponseData.getInstance(null);
ResponseData.getInstance(null);
RevokedInfo.getInstance(null);
RevokedInfo.getInstance(null);
Signature.getInstance(null);
Signature.getInstance(null);
SingleResponse.getInstance(null);
SingleResponse.getInstance(null);
TBSRequest.getInstance(null);
TBSRequest.getInstance(null);
Attribute.getInstance(null);
AuthenticatedSafe.getInstance(null);
CertificationRequestInfo.getInstance(null);
CertificationRequest.getInstance(null);
ContentInfo.getInstance(null);
DHParameter.getInstance(null);
EncryptedData.getInstance(null);
EncryptedPrivateKeyInfo.getInstance(null);
AlgorithmIdentifier.getInstance(null);
IssuerAndSerialNumber.getInstance(null);
MacData.getInstance(null);
PBEParameter.getInstance(null);
PBES2Parameters.getInstance(null);
PBKDF2Params.getInstance(null);
Pfx.getInstance(null);
PKCS12PBEParams.getInstance(null);
PrivateKeyInfo.getInstance(null);
PrivateKeyInfo.getInstance(null);
RC2CBCParameter.getInstance(null);
RSAESOAEPparams.getInstance(null);
RSAPrivateKey.getInstance(null);
RSAPrivateKey.getInstance(null);
RSAPublicKey.getInstance(null);
RSAPublicKey.getInstance(null);
RSASSAPSSparams.getInstance(null);
SafeBag.getInstance(null);
SignedData.getInstance(null);
SignerInfo.getInstance(null);
ECPrivateKey.getInstance(null);
SMIMECapabilities.getInstance(null);
SMIMECapability.getInstance(null);
Accuracy.getInstance(null);
MessageImprint.getInstance(null);
TimeStampReq.getInstance(null);
TimeStampResp.getInstance(null);
TSTInfo.getInstance(null);
AttributeTypeAndValue.getInstance(null);
DirectoryString.getInstance(null);
DirectoryString.getInstance(null);
RDN.getInstance(null);
X500Name.getInstance(null);
X500Name.getInstance(null);
AccessDescription.getInstance(null);
AlgorithmIdentifier.getInstance(null);
AlgorithmIdentifier.getInstance(null);
AttCertIssuer.getInstance(null);
AttCertIssuer.getInstance(null);
AttCertValidityPeriod.getInstance(null);
AttributeCertificateInfo.getInstance(null);
AttributeCertificateInfo.getInstance(null);
AttributeCertificate.getInstance(null);
Attribute.getInstance(null);
AuthorityInformationAccess.getInstance(null);
AuthorityKeyIdentifier.getInstance(null);
AuthorityKeyIdentifier.getInstance(null);
BasicConstraints.getInstance(null);
BasicConstraints.getInstance(null);
Certificate.getInstance(null);
Certificate.getInstance(null);
CertificateList.getInstance(null);
CertificateList.getInstance(null);
CertificatePair.getInstance(null);
CertificatePolicies.getInstance(null);
CertificatePolicies.getInstance(null);
CRLDistPoint.getInstance(null);
CRLDistPoint.getInstance(null);
CRLNumber.getInstance(null);
CRLReason.getInstance(null);
DigestInfo.getInstance(null);
DigestInfo.getInstance(null);
DisplayText.getInstance(null);
DisplayText.getInstance(null);
DistributionPoint.getInstance(null);
DistributionPoint.getInstance(null);
DistributionPointName.getInstance(null);
DistributionPointName.getInstance(null);
DSAParameter.getInstance(null);
DSAParameter.getInstance(null);
ExtendedKeyUsage.getInstance(null);
ExtendedKeyUsage.getInstance(null);
Extensions.getInstance(null);
Extensions.getInstance(null);
GeneralName.getInstance(null);
GeneralName.getInstance(null);
GeneralNames.getInstance(null);
GeneralNames.getInstance(null);
GeneralSubtree generalSubtree = new GeneralSubtree(new GeneralName(new X500Name("CN=Test")));
ASN1ObjectIdentifier algOid = new ASN1ObjectIdentifier("1.2.1");
ObjectDigestInfo objectDigestInfo = new ObjectDigestInfo(ObjectDigestInfo.otherObjectDigest, algOid, new AlgorithmIdentifier(algOid), new byte[20]);
doFullGetInstanceTest(GeneralSubtree.class, generalSubtree);
doFullGetInstanceTest(Holder.class, new Holder(objectDigestInfo));
IetfAttrSyntax.getInstance(null);
IssuerSerial.getInstance(null);
IssuerSerial.getInstance(null);
IssuingDistributionPoint.getInstance(null);
IssuingDistributionPoint.getInstance(null);
DERBitString.getInstance(null);
v.clear();
v.add(generalSubtree);
doFullGetInstanceTest(NameConstraints.class, new NameConstraints(null, null));
doFullGetInstanceTest(NoticeReference.class, noticeReference);
doFullGetInstanceTest(ObjectDigestInfo.class, objectDigestInfo);
PolicyInformation.getInstance(null);
PolicyMappings.getInstance(null);
PolicyQualifierInfo.getInstance(null);
PrivateKeyUsagePeriod.getInstance(null);
doFullGetInstanceTest(RoleSyntax.class, new RoleSyntax(new GeneralNames(new GeneralName(new X500Name("CN=Test"))), new GeneralName(GeneralName.uniformResourceIdentifier, "http://bc")));
RSAPublicKeyStructure.getInstance(null);
RSAPublicKeyStructure.getInstance(null);
SubjectDirectoryAttributes.getInstance(null);
SubjectKeyIdentifier.getInstance(null);
SubjectKeyIdentifier.getInstance(null);
SubjectPublicKeyInfo.getInstance(null);
SubjectPublicKeyInfo.getInstance(null);
TargetInformation.getInstance(null);
Target.getInstance(null);
Targets.getInstance(null);
TBSCertificate.getInstance(null);
TBSCertificate.getInstance(null);
TBSCertificateStructure.getInstance(null);
TBSCertificateStructure.getInstance(null);
TBSCertList.CRLEntry.getInstance(null);
TBSCertList.getInstance(null);
TBSCertList.getInstance(null);
Time.getInstance(null);
Time.getInstance(null);
doFullGetInstanceTest(UserNotice.class, new UserNotice(noticeReference, "hello world"));
V2Form.getInstance(null);
V2Form.getInstance(null);
X509CertificateStructure.getInstance(null);
X509CertificateStructure.getInstance(null);
X509Extensions.getInstance(null);
X509Extensions.getInstance(null);
X509Name.getInstance(null);
X509Name.getInstance(null);
DHDomainParameters.getInstance(null);
DHDomainParameters.getInstance(null);
DHPublicKey.getInstance(null);
DHPublicKey.getInstance(null);
DHValidationParms.getInstance(null);
DHValidationParms.getInstance(null);
X962Parameters.getInstance(null);
X962Parameters.getInstance(null);
X9ECParameters.getInstance(null);
MQVuserKeyingMaterial.getInstance(null);
MQVuserKeyingMaterial.getInstance(null);
CertHash.getInstance(null);
RequestedCertificate.getInstance(null);
RequestedCertificate.getInstance(null);
AdditionalInformationSyntax.getInstance(null);
Admissions.getInstance(null);
AdmissionSyntax.getInstance(null);
DeclarationOfMajority.getInstance(null);
MonetaryLimit.getInstance(null);
NamingAuthority.getInstance(null);
NamingAuthority.getInstance(null);
ProcurationSyntax.getInstance(null);
ProfessionInfo.getInstance(null);
Restriction.getInstance(null);
BiometricData.getInstance(null);
Iso4217CurrencyCode.getInstance(null);
MonetaryValue.getInstance(null);
QCStatement.getInstance(null);
SemanticsInformation.getInstance(null);
TypeOfBiometricData.getInstance(null);
NameOrPseudonym.getInstance(null);
PersonalData.getInstance(null);
}Example 6
| Project: OWASP-WebScarab-master File: SunCertificateUtilsTest.java View source code |
@Test
public void testSign() throws Exception {
// setup
KeyPair caKeyPair = generateKeyPair();
KeyPair entityKeyPair = generateKeyPair();
X500Principal subject = new X500Principal("CN=Test");
PublicKey pubKey = entityKeyPair.getPublic();
X500Principal issuer = new X500Principal("CN=CA");
PublicKey caPubKey = caKeyPair.getPublic();
PrivateKey caKey = caKeyPair.getPrivate();
Date begin = new Date();
Date ends = new Date(begin.getTime() + (long) 1000 * 60 * 60 * 24 * 30);
BigInteger serialNo = BigInteger.valueOf(1234);
JcaX509ExtensionUtils jxeu = new JcaX509ExtensionUtils();
// operate
X509Certificate resultCert = SunCertificateUtils.sign(subject, pubKey, issuer, caPubKey, caKey, begin, ends, serialNo, null);
// verify
assertNotNull(resultCert);
LOG.debug("result certificate: " + resultCert);
resultCert.verify(caPubKey);
assertEquals(subject, resultCert.getSubjectX500Principal());
assertEquals(issuer, resultCert.getIssuerX500Principal());
assertEquals(serialNo, resultCert.getSerialNumber());
assertEquals(pubKey, resultCert.getPublicKey());
LOG.debug("expected begin: " + begin.getTime());
LOG.debug("actual begin: " + resultCert.getNotBefore().getTime());
/*
* BouncyCastle drops the milliseconds.
*/
assertTrue(Math.abs(begin.getTime() - resultCert.getNotBefore().getTime()) < 1000);
assertTrue(Math.abs(ends.getTime() - resultCert.getNotAfter().getTime()) < 1000);
byte[] subjectKeyIdentifierExtValue = resultCert.getExtensionValue(X509Extension.subjectKeyIdentifier.getId());
assertNotNull(subjectKeyIdentifierExtValue);
ASN1Primitive subjectKeyIdentifier = JcaX509ExtensionUtils.parseExtensionValue(subjectKeyIdentifierExtValue);
ASN1Primitive expSKI = jxeu.createSubjectKeyIdentifier(pubKey).toASN1Primitive();
assertArrayEquals(expSKI.getEncoded(), subjectKeyIdentifier.getEncoded());
byte[] authorityKeyIdentifierExtValue = resultCert.getExtensionValue(X509Extension.authorityKeyIdentifier.getId());
ASN1Primitive authorityKeyIdentifier = JcaX509ExtensionUtils.parseExtensionValue(authorityKeyIdentifierExtValue);
ASN1Primitive expAKI = jxeu.createAuthorityKeyIdentifier(caPubKey).toASN1Primitive();
assertArrayEquals(expAKI.getEncoded(), authorityKeyIdentifier.getEncoded());
assertEquals(-1, resultCert.getBasicConstraints());
byte[] netscapeCertTypeExtValue = resultCert.getExtensionValue(MiscObjectIdentifiers.netscapeCertType.getId());
assertNotNull(netscapeCertTypeExtValue);
DERBitString netscapeCertTypeExt = (DERBitString) X509ExtensionUtil.fromExtensionValue(netscapeCertTypeExtValue);
NetscapeCertType netscapeCertType = new NetscapeCertType(netscapeCertTypeExt);
assertEquals(NetscapeCertType.sslClient, netscapeCertType.intValue() & NetscapeCertType.sslClient);
assertEquals(NetscapeCertType.sslServer, netscapeCertType.intValue() & NetscapeCertType.sslServer);
assertTrue(resultCert.getKeyUsage()[0]);
assertTrue(resultCert.getKeyUsage()[2]);
byte[] extendedKeyUsageExtValue = resultCert.getExtensionValue(X509Extension.extendedKeyUsage.getId());
assertNotNull(extendedKeyUsageExtValue);
ExtendedKeyUsage extendedKeyUsage = ExtendedKeyUsage.getInstance(X509ExtensionUtil.fromExtensionValue(extendedKeyUsageExtValue));
assertTrue(extendedKeyUsage.hasKeyPurposeId(KeyPurposeId.id_kp_clientAuth));
assertTrue(extendedKeyUsage.hasKeyPurposeId(KeyPurposeId.id_kp_serverAuth));
}Example 7
| Project: Scarab-master File: SunCertificateUtilsTest.java View source code |
@Test
public void testSign() throws Exception {
// setup
KeyPair caKeyPair = generateKeyPair();
KeyPair entityKeyPair = generateKeyPair();
X500Principal subject = new X500Principal("CN=Test");
PublicKey pubKey = entityKeyPair.getPublic();
X500Principal issuer = new X500Principal("CN=CA");
PublicKey caPubKey = caKeyPair.getPublic();
PrivateKey caKey = caKeyPair.getPrivate();
Date begin = new Date();
Date ends = new Date(begin.getTime() + (long) 1000 * 60 * 60 * 24 * 30);
BigInteger serialNo = BigInteger.valueOf(1234);
JcaX509ExtensionUtils jxeu = new JcaX509ExtensionUtils();
// operate
X509Certificate resultCert = SunCertificateUtils.sign(subject, pubKey, issuer, caPubKey, caKey, begin, ends, serialNo, null);
// verify
assertNotNull(resultCert);
LOG.debug("result certificate: " + resultCert);
resultCert.verify(caPubKey);
assertEquals(subject, resultCert.getSubjectX500Principal());
assertEquals(issuer, resultCert.getIssuerX500Principal());
assertEquals(serialNo, resultCert.getSerialNumber());
assertEquals(pubKey, resultCert.getPublicKey());
LOG.debug("expected begin: " + begin.getTime());
LOG.debug("actual begin: " + resultCert.getNotBefore().getTime());
/*
* BouncyCastle drops the milliseconds.
*/
assertTrue(Math.abs(begin.getTime() - resultCert.getNotBefore().getTime()) < 1000);
assertTrue(Math.abs(ends.getTime() - resultCert.getNotAfter().getTime()) < 1000);
byte[] subjectKeyIdentifierExtValue = resultCert.getExtensionValue(X509Extension.subjectKeyIdentifier.getId());
assertNotNull(subjectKeyIdentifierExtValue);
ASN1Primitive subjectKeyIdentifier = JcaX509ExtensionUtils.parseExtensionValue(subjectKeyIdentifierExtValue);
ASN1Primitive expSKI = jxeu.createSubjectKeyIdentifier(pubKey).toASN1Primitive();
assertArrayEquals(expSKI.getEncoded(), subjectKeyIdentifier.getEncoded());
byte[] authorityKeyIdentifierExtValue = resultCert.getExtensionValue(X509Extension.authorityKeyIdentifier.getId());
ASN1Primitive authorityKeyIdentifier = JcaX509ExtensionUtils.parseExtensionValue(authorityKeyIdentifierExtValue);
ASN1Primitive expAKI = jxeu.createAuthorityKeyIdentifier(caPubKey).toASN1Primitive();
assertArrayEquals(expAKI.getEncoded(), authorityKeyIdentifier.getEncoded());
assertEquals(-1, resultCert.getBasicConstraints());
byte[] netscapeCertTypeExtValue = resultCert.getExtensionValue(MiscObjectIdentifiers.netscapeCertType.getId());
assertNotNull(netscapeCertTypeExtValue);
DERBitString netscapeCertTypeExt = (DERBitString) X509ExtensionUtil.fromExtensionValue(netscapeCertTypeExtValue);
NetscapeCertType netscapeCertType = new NetscapeCertType(netscapeCertTypeExt);
assertEquals(NetscapeCertType.sslClient, netscapeCertType.intValue() & NetscapeCertType.sslClient);
assertEquals(NetscapeCertType.sslServer, netscapeCertType.intValue() & NetscapeCertType.sslServer);
assertTrue(resultCert.getKeyUsage()[0]);
assertTrue(resultCert.getKeyUsage()[2]);
byte[] extendedKeyUsageExtValue = resultCert.getExtensionValue(X509Extension.extendedKeyUsage.getId());
assertNotNull(extendedKeyUsageExtValue);
ExtendedKeyUsage extendedKeyUsage = ExtendedKeyUsage.getInstance(X509ExtensionUtil.fromExtensionValue(extendedKeyUsageExtValue));
assertTrue(extendedKeyUsage.hasKeyPurposeId(KeyPurposeId.id_kp_clientAuth));
assertTrue(extendedKeyUsage.hasKeyPurposeId(KeyPurposeId.id_kp_serverAuth));
}Example 8
| Project: scotty-master File: SunCertificateUtils.java View source code |
public static X509Certificate sign(X500Principal subject, PublicKey pubKey, X500Principal issuer, PublicKey caPubKey, PrivateKey caKey, Date begin, Date ends, BigInteger serialNo) throws GeneralSecurityException {
X509V3CertificateGenerator certificateGenerator = new X509V3CertificateGenerator();
certificateGenerator.reset();
certificateGenerator.setPublicKey(pubKey);
certificateGenerator.setSignatureAlgorithm(SIGALG);
certificateGenerator.setNotBefore(begin);
certificateGenerator.setNotAfter(ends);
certificateGenerator.setIssuerDN(issuer);
certificateGenerator.setSubjectDN(subject);
certificateGenerator.setSerialNumber(serialNo);
if (subject.equals(issuer)) {
certificateGenerator.addExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(5));
} else {
SubjectKeyIdentifierStructure subjectKeyIdentifier = new SubjectKeyIdentifierStructure(pubKey);
certificateGenerator.addExtension(X509Extensions.SubjectKeyIdentifier, false, subjectKeyIdentifier);
AuthorityKeyIdentifierStructure authorityKeyIdentifier = new AuthorityKeyIdentifierStructure(caPubKey);
certificateGenerator.addExtension(X509Extensions.AuthorityKeyIdentifier, false, authorityKeyIdentifier);
certificateGenerator.addExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(false));
NetscapeCertType netscapeCertType = new NetscapeCertType(NetscapeCertType.sslClient | NetscapeCertType.sslServer);
certificateGenerator.addExtension(MiscObjectIdentifiers.netscapeCertType, false, netscapeCertType);
KeyUsage keyUsage = new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyEncipherment);
certificateGenerator.addExtension(X509Extensions.KeyUsage, true, keyUsage);
Vector keyPurposeIds = new Vector();
keyPurposeIds.add(KeyPurposeId.id_kp_clientAuth);
keyPurposeIds.add(KeyPurposeId.id_kp_serverAuth);
ExtendedKeyUsage extendedKeyUsage = new ExtendedKeyUsage(keyPurposeIds);
certificateGenerator.addExtension(X509Extensions.ExtendedKeyUsage, false, extendedKeyUsage);
}
X509Certificate certificate = certificateGenerator.generate(caKey);
/*
* Next certificate factory trick is needed to make sure that the
* certificate delivered to the caller is provided by the default
* security provider instead of BouncyCastle. If we don't do this trick
* we might run into trouble when trying to use the CertPath validator.
*/
CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
certificate = (X509Certificate) certificateFactory.generateCertificate(new ByteArrayInputStream(certificate.getEncoded()));
return certificate;
}Example 9
| Project: atlas-lb-master File: SignedMailValidator.java View source code |
protected void checkSignerCert(X509Certificate cert, List errors, List notifications) {
// get key length
PublicKey key = cert.getPublicKey();
int keyLenght = -1;
if (key instanceof RSAPublicKey) {
keyLenght = ((RSAPublicKey) key).getModulus().bitLength();
} else if (key instanceof DSAPublicKey) {
keyLenght = ((DSAPublicKey) key).getParams().getP().bitLength();
}
if (keyLenght != -1 && keyLenght <= shortKeyLength) {
ErrorBundle msg = new ErrorBundle(RESOURCE_NAME, "SignedMailValidator.shortSigningKey", new Object[] { new Integer(keyLenght) });
notifications.add(msg);
}
// warn if certificate has very long validity period
long validityPeriod = cert.getNotAfter().getTime() - cert.getNotBefore().getTime();
if (validityPeriod > THIRTY_YEARS_IN_MILLI_SEC) {
ErrorBundle msg = new ErrorBundle(RESOURCE_NAME, "SignedMailValidator.longValidity", new Object[] { new TrustedInput(cert.getNotBefore()), new TrustedInput(cert.getNotAfter()) });
notifications.add(msg);
}
// check key usage if digitalSignature or nonRepudiation is set
boolean[] keyUsage = cert.getKeyUsage();
if (keyUsage != null && !keyUsage[0] && !keyUsage[1]) {
ErrorBundle msg = new ErrorBundle(RESOURCE_NAME, "SignedMailValidator.signingNotPermitted");
errors.add(msg);
}
// check extended key usage
try {
byte[] ext = cert.getExtensionValue(EXT_KEY_USAGE);
if (ext != null) {
ExtendedKeyUsage extKeyUsage = ExtendedKeyUsage.getInstance(getObject(ext));
if (!extKeyUsage.hasKeyPurposeId(KeyPurposeId.anyExtendedKeyUsage) && !extKeyUsage.hasKeyPurposeId(KeyPurposeId.id_kp_emailProtection)) {
ErrorBundle msg = new ErrorBundle(RESOURCE_NAME, "SignedMailValidator.extKeyUsageNotPermitted");
errors.add(msg);
}
}
} catch (Exception e) {
ErrorBundle msg = new ErrorBundle(RESOURCE_NAME, "SignedMailValidator.extKeyUsageError", new Object[] { e.getMessage(), e, e.getClass().getName() });
errors.add(msg);
}
// cert has an email address
try {
Set certEmails = getEmailAddresses(cert);
if (certEmails.isEmpty()) {
// error no email address in signing certificate
ErrorBundle msg = new ErrorBundle(RESOURCE_NAME, "SignedMailValidator.noEmailInCert");
errors.add(msg);
} else {
// check if email in cert is equal to the from address in the
// message
boolean equalsFrom = false;
for (int i = 0; i < fromAddresses.length; i++) {
if (certEmails.contains(fromAddresses[i].toLowerCase())) {
equalsFrom = true;
break;
}
}
if (!equalsFrom) {
ErrorBundle msg = new ErrorBundle(RESOURCE_NAME, "SignedMailValidator.emailFromCertMismatch", new Object[] { new UntrustedInput(addressesToString(fromAddresses)), new UntrustedInput(certEmails) });
errors.add(msg);
}
}
} catch (Exception e) {
ErrorBundle msg = new ErrorBundle(RESOURCE_NAME, "SignedMailValidator.certGetEmailError", new Object[] { e.getMessage(), e, e.getClass().getName() });
errors.add(msg);
}
}Example 10
| Project: cattle-master File: SshKeyGen.java View source code |
public static X509Certificate generateClientCert(String subject, PublicKey entityKey, PrivateKey caKey, X509Certificate caCert, String... sans) throws NoSuchAlgorithmException, CertIOException, OperatorCreationException, CertificateException {
X509v3CertificateBuilder certBldr = new JcaX509v3CertificateBuilder(caCert.getSubjectX500Principal(), BigInteger.valueOf(Math.abs(RANDOM.nextLong())), new Date(System.currentTimeMillis()), new Date(System.currentTimeMillis() + EXPIRATION.get() * 24 * 60 * 60 * 1000), new X500Principal("CN=" + subject), entityKey);
List<GeneralName> sanNameList = new ArrayList<>();
for (String san : sans) {
if (san.startsWith("IP:")) {
sanNameList.add(new GeneralName(GeneralName.iPAddress, san.substring(3)));
sanNameList.add(new GeneralName(GeneralName.dNSName, san.substring(3)));
} else {
sanNameList.add(new GeneralName(GeneralName.dNSName, san));
}
}
GeneralName[] sanNames = sanNameList.toArray(new GeneralName[sanNameList.size()]);
certBldr.addExtension(Extension.subjectAlternativeName, false, new GeneralNames(sanNames)).addExtension(Extension.basicConstraints, true, new BasicConstraints(false)).addExtension(Extension.keyUsage, true, new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyEncipherment)).addExtension(Extension.extendedKeyUsage, true, ExtendedKeyUsage.getInstance(new DERSequence(new ASN1Encodable[] { KeyPurposeId.id_kp_clientAuth, KeyPurposeId.id_kp_serverAuth })));
ContentSigner signer = new JcaContentSignerBuilder("SHA256withRSA").setProvider("BC").build(caKey);
return new JcaX509CertificateConverter().setProvider("BC").getCertificate(certBldr.build(signer));
}Example 11
| Project: ebics-java-master File: X509Generator.java View source code |
/**
* Returns an <code>X509Certificate</code> from a given
* <code>KeyPair</code> and limit dates validations
* @param keypair the given key pair
* @param issuer the certificate issuer
* @param notBefore the begin validity date
* @param notAfter the end validity date
* @param keyusage the certificate key usage
* @return the X509 certificate
* @throws GeneralSecurityException
* @throws IOException
*/
public X509Certificate generate(KeyPair keypair, String issuer, Date notBefore, Date notAfter, int keyusage) throws GeneralSecurityException, IOException {
X509V3CertificateGenerator generator;
BigInteger serial;
X509Certificate certificate;
ASN1EncodableVector vector;
serial = BigInteger.valueOf(generateSerial());
generator = new X509V3CertificateGenerator();
generator.setSerialNumber(serial);
generator.setIssuerDN(new X509Principal(issuer));
generator.setNotBefore(notBefore);
generator.setNotAfter(notAfter);
generator.setSubjectDN(new X509Principal(issuer));
generator.setPublicKey(keypair.getPublic());
generator.setSignatureAlgorithm(X509Constants.SIGNATURE_ALGORITHM);
generator.addExtension(X509Extensions.BasicConstraints, false, new BasicConstraints(true));
generator.addExtension(X509Extensions.SubjectKeyIdentifier, false, getSubjectKeyIdentifier(keypair.getPublic()));
generator.addExtension(X509Extensions.AuthorityKeyIdentifier, false, getAuthorityKeyIdentifier(keypair.getPublic(), issuer, serial));
vector = new ASN1EncodableVector();
vector.add(KeyPurposeId.id_kp_emailProtection);
generator.addExtension(X509Extensions.ExtendedKeyUsage, false, new ExtendedKeyUsage(new DERSequence(vector)));
switch(keyusage) {
case X509Constants.SIGNATURE_KEY_USAGE:
generator.addExtension(X509Extensions.KeyUsage, false, new KeyUsage(KeyUsage.nonRepudiation));
break;
case X509Constants.AUTHENTICATION_KEY_USAGE:
generator.addExtension(X509Extensions.KeyUsage, false, new KeyUsage(KeyUsage.digitalSignature));
break;
case X509Constants.ENCRYPTION_KEY_USAGE:
generator.addExtension(X509Extensions.KeyUsage, false, new KeyUsage(KeyUsage.keyAgreement));
break;
default:
generator.addExtension(X509Extensions.KeyUsage, false, new KeyUsage(KeyUsage.keyEncipherment | KeyUsage.digitalSignature));
break;
}
certificate = generator.generate(keypair.getPrivate(), "BC", new SecureRandom());
certificate.checkValidity(new Date());
certificate.verify(keypair.getPublic());
return certificate;
}Example 12
| Project: ebics-master File: X509Generator.java View source code |
/**
* Returns an <code>X509Certificate</code> from a given
* <code>KeyPair</code> and limit dates validations
* @param keypair the given key pair
* @param issuer the certificate issuer
* @param notBefore the begin validity date
* @param notAfter the end validity date
* @param keyusage the certificate key usage
* @return the X509 certificate
* @throws GeneralSecurityException
* @throws IOException
*/
public X509Certificate generate(KeyPair keypair, String issuer, Date notBefore, Date notAfter, int keyusage) throws GeneralSecurityException, IOException {
X509V3CertificateGenerator generator;
BigInteger serial;
X509Certificate certificate;
ASN1EncodableVector vector;
serial = BigInteger.valueOf(generateSerial());
generator = new X509V3CertificateGenerator();
generator.setSerialNumber(serial);
generator.setIssuerDN(new X509Principal(issuer));
generator.setNotBefore(notBefore);
generator.setNotAfter(notAfter);
generator.setSubjectDN(new X509Principal(issuer));
generator.setPublicKey(keypair.getPublic());
generator.setSignatureAlgorithm(X509Constants.SIGNATURE_ALGORITHM);
generator.addExtension(X509Extensions.BasicConstraints, false, new BasicConstraints(true));
generator.addExtension(X509Extensions.SubjectKeyIdentifier, false, getSubjectKeyIdentifier(keypair.getPublic()));
generator.addExtension(X509Extensions.AuthorityKeyIdentifier, false, getAuthorityKeyIdentifier(keypair.getPublic(), issuer, serial));
vector = new ASN1EncodableVector();
vector.add(KeyPurposeId.id_kp_emailProtection);
generator.addExtension(X509Extensions.ExtendedKeyUsage, false, new ExtendedKeyUsage(new DERSequence(vector)));
switch(keyusage) {
case X509Constants.SIGNATURE_KEY_USAGE:
generator.addExtension(X509Extensions.KeyUsage, false, new KeyUsage(KeyUsage.nonRepudiation));
break;
case X509Constants.AUTHENTICATION_KEY_USAGE:
generator.addExtension(X509Extensions.KeyUsage, false, new KeyUsage(KeyUsage.digitalSignature));
break;
case X509Constants.ENCRYPTION_KEY_USAGE:
generator.addExtension(X509Extensions.KeyUsage, false, new KeyUsage(KeyUsage.keyAgreement));
break;
default:
generator.addExtension(X509Extensions.KeyUsage, false, new KeyUsage(KeyUsage.keyEncipherment | KeyUsage.digitalSignature));
break;
}
certificate = generator.generate(keypair.getPrivate(), "BC", new SecureRandom());
certificate.checkValidity(new Date());
certificate.verify(keypair.getPublic());
return certificate;
}Example 13
| Project: keycloak-master File: CertificateUtils.java View source code |
/**
* Generates version 3 {@link java.security.cert.X509Certificate}.
*
* @param keyPair the key pair
* @param caPrivateKey the CA private key
* @param caCert the CA certificate
* @param subject the subject name
*
* @return the x509 certificate
*
* @throws Exception the exception
*/
public static X509Certificate generateV3Certificate(KeyPair keyPair, PrivateKey caPrivateKey, X509Certificate caCert, String subject) throws Exception {
try {
X500Name subjectDN = new X500Name("CN=" + subject);
// Serial Number
SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
BigInteger serialNumber = BigInteger.valueOf(Math.abs(random.nextInt()));
// Validity
Date notBefore = new Date(System.currentTimeMillis());
Date notAfter = new Date(System.currentTimeMillis() + (((1000L * 60 * 60 * 24 * 30)) * 12) * 3);
// SubjectPublicKeyInfo
SubjectPublicKeyInfo subjPubKeyInfo = new SubjectPublicKeyInfo(ASN1Sequence.getInstance(keyPair.getPublic().getEncoded()));
X509v3CertificateBuilder certGen = new X509v3CertificateBuilder(new X500Name(caCert.getSubjectDN().getName()), serialNumber, notBefore, notAfter, subjectDN, subjPubKeyInfo);
DigestCalculator digCalc = new BcDigestCalculatorProvider().get(new AlgorithmIdentifier(OIWObjectIdentifiers.idSHA1));
X509ExtensionUtils x509ExtensionUtils = new X509ExtensionUtils(digCalc);
// Subject Key Identifier
certGen.addExtension(Extension.subjectKeyIdentifier, false, x509ExtensionUtils.createSubjectKeyIdentifier(subjPubKeyInfo));
// Authority Key Identifier
certGen.addExtension(Extension.authorityKeyIdentifier, false, x509ExtensionUtils.createAuthorityKeyIdentifier(subjPubKeyInfo));
// Key Usage
certGen.addExtension(Extension.keyUsage, false, new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyCertSign | KeyUsage.cRLSign));
// Extended Key Usage
KeyPurposeId[] EKU = new KeyPurposeId[2];
EKU[0] = KeyPurposeId.id_kp_emailProtection;
EKU[1] = KeyPurposeId.id_kp_serverAuth;
certGen.addExtension(Extension.extendedKeyUsage, false, new ExtendedKeyUsage(EKU));
// Basic Constraints
certGen.addExtension(Extension.basicConstraints, true, new BasicConstraints(0));
// Content Signer
ContentSigner sigGen = new JcaContentSignerBuilder("SHA1WithRSAEncryption").setProvider("BC").build(caPrivateKey);
// Certificate
return new JcaX509CertificateConverter().setProvider("BC").getCertificate(certGen.build(sigGen));
} catch (Exception e) {
throw new RuntimeException("Error creating X509v3Certificate.", e);
}
}Example 14
| Project: org.glite.slcs.common-master File: CertificateExtensionFactory.java View source code |
/**
* Creates a CertificateExtension. The id can be the OID or the name as
* defined below. The values is a comma separated list of value(s)
* <p>
* Valid names and values:
* <ul>
* <li>KeyUsage
* <ul>
* <li>DigitalSignature
* <li>NonRepudiation
* <li>KeyEncipherment
* <li>DataEncipherment
* <li>KeyAgreement
* <li>KeyCertSign
* <li>CRLSign
* <li>EncipherOnly
* <li>DecipherOnly
* </ul>
* <li>ExtendedKeyUsage
* <ul>
* <li>AnyExtendedKeyUsage
* <li>ServerAuth
* <li>ClientAuth
* <li>CodeSigning
* <li>EmailProtection
* <li>IPSecEndSystem
* <li>IPSecTunnel
* <li>IPSecUser
* <li>OCSPSigning
* <li>Smartcardlogon
* </ul>
* <li>CertificatePolicies
* <ul>
* <li>The policy OID(s)
* </ul>
* <li>SubjectAltName
* <ul>
* <li>email:EMAIL_ADDRESS
* <li>dns:HOSTNAME
* </ul>
* </ul>
* <p>
* Example:
* <pre>
* CertificateExtension keyUsageExtension =
* CertificateExtensionFactory.createCertificateExtension("KeyUsage", "DigitalSignature,KeyEncipherment");
* CertificateExtension subjectAltNameExtension =
* CertificateExtensionFactory.createCertificateExtension("SubjectAltName", "email:john.doe@example.com,dns:www.exmaple.com");
* </pre>
*
* @param id
* The name or the OID of the extension.
* @param values
* A comma separated list of extension value(s).
* @return The corresponding CertificateExtension or <code>null</code> if
* the id (name or oid) is not supported.
*/
public static CertificateExtension createCertificateExtension(String id, String values) {
if (LOG.isDebugEnabled()) {
LOG.debug("id:" + id + " value(s):" + values);
}
if (id.equals(X509Extensions.KeyUsage.getId()) || id.equalsIgnoreCase("KeyUsage")) {
// parse the comma separated list of key usage
int usage = 0;
StringTokenizer st = new StringTokenizer(values, ",");
while (st.hasMoreElements()) {
String keyUsage = (String) st.nextElement();
keyUsage = keyUsage.trim();
if (keyUsage.equalsIgnoreCase("DigitalSignature")) {
usage += KeyUsage.digitalSignature;
} else if (keyUsage.equalsIgnoreCase("NonRepudiation")) {
usage += KeyUsage.nonRepudiation;
} else if (keyUsage.equalsIgnoreCase("KeyEncipherment")) {
usage += KeyUsage.keyEncipherment;
} else if (keyUsage.equalsIgnoreCase("DataEncipherment")) {
usage += KeyUsage.dataEncipherment;
} else if (keyUsage.equalsIgnoreCase("KeyAgreement")) {
usage += KeyUsage.keyAgreement;
} else if (keyUsage.equalsIgnoreCase("KeyCertSign")) {
usage += KeyUsage.keyCertSign;
} else if (keyUsage.equalsIgnoreCase("CRLSign")) {
usage += KeyUsage.cRLSign;
} else if (keyUsage.equalsIgnoreCase("EncipherOnly")) {
usage += KeyUsage.encipherOnly;
} else if (keyUsage.equalsIgnoreCase("DecipherOnly")) {
usage += KeyUsage.decipherOnly;
} else {
LOG.error("Unknown KeyUsage: " + keyUsage);
}
}
return createKeyUsageExtension(usage, values);
} else if (id.equals(X509Extensions.ExtendedKeyUsage.getId()) || id.equalsIgnoreCase("ExtendedKeyUsage")) {
// value is a comma separated list of keyPurpose
Vector keyPurposeIds = new Vector();
StringTokenizer st = new StringTokenizer(values, ",");
while (st.hasMoreElements()) {
String keyPurpose = (String) st.nextElement();
keyPurpose = keyPurpose.trim();
if (keyPurpose.equalsIgnoreCase("AnyExtendedKeyUsage")) {
keyPurposeIds.add(KeyPurposeId.anyExtendedKeyUsage);
} else if (keyPurpose.equalsIgnoreCase("ServerAuth")) {
keyPurposeIds.add(KeyPurposeId.id_kp_serverAuth);
} else if (keyPurpose.equalsIgnoreCase("ClientAuth")) {
keyPurposeIds.add(KeyPurposeId.id_kp_clientAuth);
} else if (keyPurpose.equalsIgnoreCase("CodeSigning")) {
keyPurposeIds.add(KeyPurposeId.id_kp_codeSigning);
} else if (keyPurpose.equalsIgnoreCase("EmailProtection")) {
keyPurposeIds.add(KeyPurposeId.id_kp_emailProtection);
} else if (keyPurpose.equalsIgnoreCase("IPSecEndSystem")) {
keyPurposeIds.add(KeyPurposeId.id_kp_ipsecEndSystem);
} else if (keyPurpose.equalsIgnoreCase("IPSecTunnel")) {
keyPurposeIds.add(KeyPurposeId.id_kp_ipsecTunnel);
} else if (keyPurpose.equalsIgnoreCase("IPSecUser")) {
keyPurposeIds.add(KeyPurposeId.id_kp_ipsecUser);
} else if (keyPurpose.equalsIgnoreCase("TimeStamping")) {
keyPurposeIds.add(KeyPurposeId.id_kp_timeStamping);
} else if (keyPurpose.equalsIgnoreCase("OCSPSigning")) {
keyPurposeIds.add(KeyPurposeId.id_kp_OCSPSigning);
} else if (keyPurpose.equalsIgnoreCase("Smartcardlogon")) {
keyPurposeIds.add(KeyPurposeId.id_kp_smartcardlogon);
} else {
LOG.error("Unknown ExtendedKeyUsage: " + keyPurpose);
}
}
return createExtendedKeyUsageExtension(keyPurposeIds, values);
} else if (id.equals(X509Extensions.CertificatePolicies.getId()) || id.equalsIgnoreCase("CertificatePolicies")) {
// values is a comma separated list of policyOIDs
Vector policyOIDs = new Vector();
StringTokenizer st = new StringTokenizer(values, ",");
while (st.hasMoreElements()) {
String policyOID = (String) st.nextElement();
policyOID = policyOID.trim();
policyOIDs.add(policyOID);
}
return createCertificatePoliciesExtension(policyOIDs, values);
} else if (id.equals(X509Extensions.SubjectAlternativeName.getId()) || id.equalsIgnoreCase("SubjectAltName")) {
// values is a comma separated list of altername names prefixed with
// the type (email: or dns:)
Vector typedSubjectAltNames = new Vector();
StringTokenizer st = new StringTokenizer(values, ",");
while (st.hasMoreElements()) {
String typedAltName = (String) st.nextElement();
typedAltName = typedAltName.trim();
typedSubjectAltNames.add(typedAltName);
}
return createSubjectAltNameExtension(typedSubjectAltNames, values);
}
LOG.error("Unsupported CertificateExtension: " + id);
return null;
}Example 15
| Project: Tank-master File: BouncyCastleCertificateUtils.java View source code |
private static void addCertificateExtensions(PublicKey pubKey, PublicKey caPubKey, X509V3CertificateGenerator certGen) throws IOException, InvalidKeyException {
// CertificateExtensions ext = new CertificateExtensions();
//
// ext.set(SubjectKeyIdentifierExtension.NAME,
// new SubjectKeyIdentifierExtension(new KeyIdentifier(pubKey)
// .getIdentifier()));
certGen.addExtension(X509Extensions.SubjectKeyIdentifier, false, new SubjectKeyIdentifierStructure(pubKey));
//
// ext.set(AuthorityKeyIdentifierExtension.NAME,
// new AuthorityKeyIdentifierExtension(
// new KeyIdentifier(caPubKey), null, null));
//
certGen.addExtension(X509Extensions.AuthorityKeyIdentifier, false, new AuthorityKeyIdentifierStructure(caPubKey));
// // Basic Constraints
// ext.set(BasicConstraintsExtension.NAME, new
// BasicConstraintsExtension(
// /* isCritical */true, /* isCA */false, /* pathLen */5));
//
certGen.addExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(false));
// Netscape Cert Type Extension
// boolean[] ncteOk = new boolean[8];
// ncteOk[0] = true; // SSL_CLIENT
// ncteOk[1] = true; // SSL_SERVER
// NetscapeCertTypeExtension ncte = new
// NetscapeCertTypeExtension(ncteOk);
// ncte = new NetscapeCertTypeExtension(false,
// ncte.getExtensionValue());
// ext.set(NetscapeCertTypeExtension.NAME, ncte);
// Key Usage Extension
// boolean[] kueOk = new boolean[9];
// kueOk[0] = true;
// kueOk[2] = true;
// "digitalSignature", // (0),
// "nonRepudiation", // (1)
// "keyEncipherment", // (2),
// "dataEncipherment", // (3),
// "keyAgreement", // (4),
// "keyCertSign", // (5),
// "cRLSign", // (6),
// "encipherOnly", // (7),
// "decipherOnly", // (8)
// "contentCommitment" // also (1)
// KeyUsageExtension kue = new KeyUsageExtension(kueOk);
// ext.set(KeyUsageExtension.NAME, kue);
certGen.addExtension(X509Extensions.KeyUsage, true, new X509KeyUsage(X509KeyUsage.digitalSignature + X509KeyUsage.keyEncipherment));
// Extended Key Usage Extension
// int[] serverAuthOidData = { 1, 3, 6, 1, 5, 5, 7, 3, 1 };
// ObjectIdentifier serverAuthOid = new
// ObjectIdentifier(serverAuthOidData);
// int[] clientAuthOidData = { 1, 3, 6, 1, 5, 5, 7, 3, 2 };
// ObjectIdentifier clientAuthOid = new
// ObjectIdentifier(clientAuthOidData);
// Vector<ObjectIdentifier> v = new Vector<ObjectIdentifier>();
// v.add(serverAuthOid);
// v.add(clientAuthOid);
// ExtendedKeyUsageExtension ekue = new ExtendedKeyUsageExtension(false,
// v);
// ext.set(ExtendedKeyUsageExtension.NAME, ekue);
// ExtendedKeyUsage extendedKeyUsage = new
// ExtendedKeyUsage(KeyPurposeId.anyExtendedKeyUsage);
Vector<KeyPurposeId> usages = new Vector<KeyPurposeId>();
usages.add(KeyPurposeId.id_kp_serverAuth);
usages.add(KeyPurposeId.id_kp_clientAuth);
certGen.addExtension(X509Extensions.ExtendedKeyUsage, true, new ExtendedKeyUsage(usages));
}Example 16
| Project: candlepin-master File: BouncyCastlePKIUtility.java View source code |
@Override
public X509Certificate createX509Certificate(String dn, Set<X509ExtensionWrapper> extensions, Set<X509ByteExtensionWrapper> byteExtensions, Date startDate, Date endDate, KeyPair clientKeyPair, BigInteger serialNumber, String alternateName) throws GeneralSecurityException, IOException {
X509V3CertificateGenerator certGen = new X509V3CertificateGenerator();
X509Certificate caCert = reader.getCACert();
// set cert fields
certGen.setSerialNumber(serialNumber);
certGen.setIssuerDN(caCert.getSubjectX500Principal());
certGen.setNotBefore(startDate);
certGen.setNotAfter(endDate);
X500Principal subjectPrincipal = new X500Principal(dn);
certGen.setSubjectDN(subjectPrincipal);
certGen.setPublicKey(clientKeyPair.getPublic());
certGen.setSignatureAlgorithm(SIGNATURE_ALGO);
// set key usage - required for proper x509 function
KeyUsage keyUsage = new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyEncipherment | KeyUsage.dataEncipherment);
// add SSL extensions - required for proper x509 function
NetscapeCertType certType = new NetscapeCertType(NetscapeCertType.sslClient | NetscapeCertType.smime);
certGen.addExtension(MiscObjectIdentifiers.netscapeCertType.toString(), false, certType);
certGen.addExtension(X509Extensions.KeyUsage.toString(), false, keyUsage);
certGen.addExtension(X509Extensions.AuthorityKeyIdentifier, false, new AuthorityKeyIdentifierStructure(caCert));
certGen.addExtension(X509Extensions.SubjectKeyIdentifier, false, subjectKeyWriter.getSubjectKeyIdentifier(clientKeyPair, extensions));
certGen.addExtension(X509Extensions.ExtendedKeyUsage, false, new ExtendedKeyUsage(KeyPurposeId.id_kp_clientAuth));
// Add an additional alternative name if provided.
if (alternateName != null) {
/*
Why add the certificate subject again as an alternative name? RFC 6125 Section 6.4.4
stipulates that if SANs are provided, a validator MUST use them instead of the certificate
subject. If no SANs are present, the RFC allows the validator to use the subject field. So,
if we do have an SAN to add, we need to add the subject field again as an SAN.
See http://stackoverflow.com/questions/5935369 and
https://tools.ietf.org/html/rfc6125#section-6.4.4 and
NB: These extensions should *not* be marked critical since the subject field is not empty.
*/
GeneralName subject = new GeneralName(GeneralName.directoryName, dn);
GeneralName name = new GeneralName(GeneralName.directoryName, "CN=" + alternateName);
ASN1Encodable[] altNameArray = { subject, name };
GeneralNames altNames = new GeneralNames(new DERSequence(altNameArray));
certGen.addExtension(X509Extensions.SubjectAlternativeName, false, altNames);
}
if (extensions != null) {
for (X509ExtensionWrapper wrapper : extensions) {
// Bouncycastle hates null values. So, set them to blank
// if they are null
String value = wrapper.getValue() == null ? "" : wrapper.getValue();
certGen.addExtension(wrapper.getOid(), wrapper.isCritical(), new DERUTF8String(value));
}
}
if (byteExtensions != null) {
for (X509ByteExtensionWrapper wrapper : byteExtensions) {
// Bouncycastle hates null values. So, set them to blank
// if they are null
byte[] value = wrapper.getValue() == null ? new byte[0] : wrapper.getValue();
certGen.addExtension(wrapper.getOid(), wrapper.isCritical(), new DEROctetString(value));
}
}
// Generate the certificate
return certGen.generate(reader.getCaKey());
}Example 17
| Project: dss-master File: CertificateService.java View source code |
/**
* Generate a CertificateToken suitable for a TSA
*
* @param algorithm
* @param keyPair
* @param issuer
* @param subject
* @param notBefore
* @param notAfter
* @return
* @throws CertIOException
* @throws OperatorCreationException
* @throws CertificateException
* @throws IOException
*/
public CertificateToken generateTspCertificate(final SignatureAlgorithm algorithm, KeyPair keyPair, X500Name issuer, X500Name subject, final Date notBefore, final Date notAfter) throws CertIOException, OperatorCreationException, CertificateException, IOException {
final SubjectPublicKeyInfo keyInfo = SubjectPublicKeyInfo.getInstance(keyPair.getPublic().getEncoded());
final X509v3CertificateBuilder certBuilder = new X509v3CertificateBuilder(issuer, new BigInteger("" + new Random().nextInt(10) + System.currentTimeMillis()), notBefore, notAfter, subject, keyInfo);
certBuilder.addExtension(Extension.extendedKeyUsage, true, new ExtendedKeyUsage(KeyPurposeId.id_kp_timeStamping));
final ContentSigner signer = new JcaContentSignerBuilder(algorithm.getJCEId()).setProvider(BouncyCastleProvider.PROVIDER_NAME).build(keyPair.getPrivate());
final X509CertificateHolder holder = certBuilder.build(signer);
final X509Certificate cert = (X509Certificate) CertificateFactory.getInstance("X509").generateCertificate(new ByteArrayInputStream(holder.getEncoded()));
return new CertificateToken(cert);
}Example 18
| Project: jqm-master File: CertificateRequest.java View source code |
private void generateX509() throws Exception {
SecureRandom random = new SecureRandom();
X500Name dnName = new X500Name(Subject);
Calendar endValidity = Calendar.getInstance();
endValidity.add(Calendar.YEAR, validityYear);
SubjectPublicKeyInfo publicKeyInfo = SubjectPublicKeyInfo.getInstance(publicKey.getEncoded());
X509v3CertificateBuilder gen = new X509v3CertificateBuilder(authorityCertificate == null ? dnName : authorityCertificate.getSubject(), BigIntegers.createRandomInRange(BigInteger.ZERO, BigInteger.valueOf(Long.MAX_VALUE), random), new Date(), endValidity.getTime(), dnName, publicKeyInfo);
// Public key ID
DigestCalculator digCalc = new BcDigestCalculatorProvider().get(new AlgorithmIdentifier(OIWObjectIdentifiers.idSHA1));
X509ExtensionUtils x509ExtensionUtils = new X509ExtensionUtils(digCalc);
gen.addExtension(Extension.subjectKeyIdentifier, false, x509ExtensionUtils.createSubjectKeyIdentifier(publicKeyInfo));
// EKU
gen.addExtension(Extension.extendedKeyUsage, false, new ExtendedKeyUsage(EKU));
// Basic constraints (is CA?)
if (authorityCertificate == null) {
gen.addExtension(Extension.basicConstraints, true, new BasicConstraints(true));
}
// Key usage
gen.addExtension(Extension.keyUsage, true, new KeyUsage(keyUsage));
// Authority
if (authorityCertificate != null) {
gen.addExtension(Extension.authorityKeyIdentifier, false, new AuthorityKeyIdentifier(authorityCertificate.getSubjectPublicKeyInfo()));
}
// Signer
ContentSigner signer = new JcaContentSignerBuilder("SHA512WithRSAEncryption").setProvider(Constants.JCA_PROVIDER).build(authorityKey == null ? privateKey : authorityKey);
// Go
holder = gen.build(signer);
}Example 19
| Project: nifi-master File: CertificateUtils.java View source code |
/**
* Generates a self-signed {@link X509Certificate} suitable for use as a Certificate Authority.
*
* @param keyPair the {@link KeyPair} to generate the {@link X509Certificate} for
* @param dn the distinguished name to user for the {@link X509Certificate}
* @param signingAlgorithm the signing algorithm to use for the {@link X509Certificate}
* @param certificateDurationDays the duration in days for which the {@link X509Certificate} should be valid
* @return a self-signed {@link X509Certificate} suitable for use as a Certificate Authority
* @throws CertificateException if there is an generating the new certificate
*/
public static X509Certificate generateSelfSignedX509Certificate(KeyPair keyPair, String dn, String signingAlgorithm, int certificateDurationDays) throws CertificateException {
try {
ContentSigner sigGen = new JcaContentSignerBuilder(signingAlgorithm).setProvider(BouncyCastleProvider.PROVIDER_NAME).build(keyPair.getPrivate());
SubjectPublicKeyInfo subPubKeyInfo = SubjectPublicKeyInfo.getInstance(keyPair.getPublic().getEncoded());
Date startDate = new Date();
Date endDate = new Date(startDate.getTime() + TimeUnit.DAYS.toMillis(certificateDurationDays));
X509v3CertificateBuilder certBuilder = new X509v3CertificateBuilder(reverseX500Name(new X500Name(dn)), getUniqueSerialNumber(), startDate, endDate, reverseX500Name(new X500Name(dn)), subPubKeyInfo);
// Set certificate extensions
// (1) digitalSignature extension
certBuilder.addExtension(Extension.keyUsage, true, new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyEncipherment | KeyUsage.dataEncipherment | KeyUsage.keyAgreement | KeyUsage.nonRepudiation | KeyUsage.cRLSign | KeyUsage.keyCertSign));
certBuilder.addExtension(Extension.basicConstraints, false, new BasicConstraints(true));
certBuilder.addExtension(Extension.subjectKeyIdentifier, false, new JcaX509ExtensionUtils().createSubjectKeyIdentifier(keyPair.getPublic()));
certBuilder.addExtension(Extension.authorityKeyIdentifier, false, new JcaX509ExtensionUtils().createAuthorityKeyIdentifier(keyPair.getPublic()));
// (2) extendedKeyUsage extension
certBuilder.addExtension(Extension.extendedKeyUsage, false, new ExtendedKeyUsage(new KeyPurposeId[] { KeyPurposeId.id_kp_clientAuth, KeyPurposeId.id_kp_serverAuth }));
// Sign the certificate
X509CertificateHolder certificateHolder = certBuilder.build(sigGen);
return new JcaX509CertificateConverter().setProvider(BouncyCastleProvider.PROVIDER_NAME).getCertificate(certificateHolder);
} catch (CertIOExceptionNoSuchAlgorithmException | OperatorCreationException | e) {
throw new CertificateException(e);
}
}Example 20
| Project: poreid-master File: OCSPClient.java View source code |
public CertStatus getCertificateStatus() throws OCSPValidationException {
try {
if (null == url) {
throw new OCSPValidationException("Certificado não tem validação por OCSP");
}
byte[] encodedOcspRequest = generateOCSPRequest(issuer, certificate.getSerialNumber()).getEncoded();
HttpURLConnection httpConnection;
httpConnection = (HttpURLConnection) url.openConnection();
httpConnection.setRequestProperty("Content-Type", "application/ocsp-request");
httpConnection.setRequestProperty("Accept", "application/ocsp-response");
httpConnection.setDoOutput(true);
try (DataOutputStream dataOut = new DataOutputStream(new BufferedOutputStream(httpConnection.getOutputStream()))) {
dataOut.write(encodedOcspRequest);
dataOut.flush();
}
InputStream in = (InputStream) httpConnection.getContent();
if (httpConnection.getResponseCode() != HttpURLConnection.HTTP_OK) {
throw new OCSPValidationException("Código HTTP recebido != 200 [" + httpConnection.getResponseCode() + "]");
}
OCSPResp ocspResponse = new OCSPResp(in);
BasicOCSPResp basicResponse = (BasicOCSPResp) ocspResponse.getResponseObject();
byte[] receivedNonce = basicResponse.getExtension(OCSPObjectIdentifiers.id_pkix_ocsp_nonce).getExtnId().getEncoded();
if (!Arrays.equals(receivedNonce, sentNonce)) {
throw new OCSPValidationException("Nonce na resposta ocsp não coincide com nonce do pedido ocsp");
}
X509CertificateHolder certHolder = basicResponse.getCerts()[0];
if (!basicResponse.isSignatureValid(new JcaContentVerifierProviderBuilder().setProvider("BC").build(issuer))) {
if (!certHolder.isValidOn(Date.from(Instant.now()))) {
throw new OCSPValidationException("Certificado não é válido na data atual");
}
// Certificado tem de ter uma Key Purpose ID for authorized responders
if (!ExtendedKeyUsage.fromExtensions(certHolder.getExtensions()).hasKeyPurposeId(KeyPurposeId.id_kp_OCSPSigning)) {
throw new OCSPValidationException("Certificado não contém extensão necessária (id_kp_OCSPSigning)");
}
// Certificado tem de ser emitido pela mesma CA do certificado que estamos a verificar
if (!certHolder.isSignatureValid(new JcaContentVerifierProviderBuilder().setProvider("BC").build(issuer))) {
throw new OCSPValidationException("Certificado não é assinado pelo mesmo issuer");
}
// Validar assinatura na resposta ocsp
if (!basicResponse.isSignatureValid(new JcaContentVerifierProviderBuilder().setProvider("BC").build(certHolder))) {
throw new OCSPValidationException("Não foi possivel validar resposta ocsp");
}
} else {
if (!certHolder.isValidOn(Date.from(Instant.now()))) {
throw new OCSPValidationException("Certificado não é válido na data atual");
}
}
// Politica de Certificados do SCEE
if (null == certHolder.getExtension(OCSPObjectIdentifiers.id_pkix_ocsp_nocheck).getExtnId()) {
throw new OCSPValidationException("Extensão id_pkix_ocsp_nocheck não encontrada no certificado (Politica de Certificados do SCEE)");
}
SingleResp[] responses = basicResponse.getResponses();
if (responses[0].getCertID().getSerialNumber().equals(certificate.getSerialNumber())) {
CertificateStatus status = responses[0].getCertStatus();
if (status == CertificateStatus.GOOD) {
return CertStatus.GOOD;
} else {
if (status instanceof RevokedStatus) {
revokedStatus = (RevokedStatus) status;
return CertStatus.REVOKED;
} else {
return CertStatus.UNKNOWN;
}
}
} else {
throw new OCSPValidationException("Número de série do certificado na resposta ocsp não coincide com número de série do certificado");
}
} catch (CertificateEncodingExceptionOperatorCreationException | OCSPException | IOException | ex) {
throw new OCSPValidationException("Não foi possivel efetuar a validação através de OCSP (" + certificate.getSubjectX500Principal().getName() + ")", ex);
} catch (CertExceptionCertificateException | ex) {
throw new OCSPValidationException("Não foi possivel efetuar a validação através de OCSP (" + certificate.getSubjectX500Principal().getName() + ")", ex);
}
}Example 21
| Project: zaproxy-master File: SslCertificateUtils.java View source code |
/**
* Creates a new Root CA certificate and returns private and public key as
* {@link KeyStore}. The {@link KeyStore#getDefaultType()} is used.
*
* @return
* @throws NoSuchAlgorithmException If no providers are found
* for 'RSA' key pair generator
* or 'SHA1PRNG' Secure random number generator
* @throws IllegalStateException in case of errors during assembling {@link KeyStore}
*/
public static final KeyStore createRootCA() throws NoSuchAlgorithmException {
final Date startDate = Calendar.getInstance().getTime();
final Date expireDate = new Date(startDate.getTime() + (DEFAULT_VALID_DAYS * 24L * 60L * 60L * 1000L));
final KeyPairGenerator g = KeyPairGenerator.getInstance("RSA");
g.initialize(2048, SecureRandom.getInstance("SHA1PRNG"));
final KeyPair keypair = g.genKeyPair();
final PrivateKey privKey = keypair.getPrivate();
final PublicKey pubKey = keypair.getPublic();
Security.addProvider(new BouncyCastleProvider());
Random rnd = new Random();
// using the hash code of the user's name and home path, keeps anonymity
// but also gives user a chance to distinguish between each other
X500NameBuilder namebld = new X500NameBuilder(BCStyle.INSTANCE);
namebld.addRDN(BCStyle.CN, "OWASP Zed Attack Proxy Root CA");
namebld.addRDN(BCStyle.L, Integer.toHexString(System.getProperty("user.name").hashCode()) + Integer.toHexString(System.getProperty("user.home").hashCode()));
namebld.addRDN(BCStyle.O, "OWASP Root CA");
namebld.addRDN(BCStyle.OU, "OWASP ZAP Root CA");
namebld.addRDN(BCStyle.C, "xx");
X509v3CertificateBuilder certGen = new JcaX509v3CertificateBuilder(namebld.build(), BigInteger.valueOf(rnd.nextInt()), startDate, expireDate, namebld.build(), pubKey);
KeyStore ks = null;
try {
certGen.addExtension(Extension.subjectKeyIdentifier, false, new SubjectKeyIdentifier(pubKey.getEncoded()));
certGen.addExtension(Extension.basicConstraints, true, new BasicConstraints(true));
certGen.addExtension(Extension.keyUsage, false, new KeyUsage(KeyUsage.keyCertSign | KeyUsage.digitalSignature | KeyUsage.keyEncipherment | KeyUsage.dataEncipherment | KeyUsage.cRLSign));
KeyPurposeId[] eku = { KeyPurposeId.id_kp_serverAuth, KeyPurposeId.id_kp_clientAuth, KeyPurposeId.anyExtendedKeyUsage };
certGen.addExtension(Extension.extendedKeyUsage, false, new ExtendedKeyUsage(eku));
final ContentSigner sigGen = new JcaContentSignerBuilder("SHA256WithRSAEncryption").setProvider("BC").build(privKey);
final X509Certificate cert = new JcaX509CertificateConverter().setProvider("BC").getCertificate(certGen.build(sigGen));
ks = KeyStore.getInstance(KeyStore.getDefaultType());
ks.load(null, null);
ks.setKeyEntry(SslCertificateService.ZAPROXY_JKS_ALIAS, privKey, SslCertificateService.PASSPHRASE, new Certificate[] { cert });
} catch (final Exception e) {
throw new IllegalStateException("Errors during assembling root CA.", e);
}
return ks;
}Example 22
| Project: xipki-master File: X509Util.java View source code |
public static ExtendedKeyUsage createExtendedUsage(final Collection<ASN1ObjectIdentifier> usages) { if (CollectionUtil.isEmpty(usages)) { return null; } List<ASN1ObjectIdentifier> list = new ArrayList<>(usages); List<ASN1ObjectIdentifier> sortedUsages = sortOidList(list); KeyPurposeId[] kps = new KeyPurposeId[sortedUsages.size()]; int idx = 0; for (ASN1ObjectIdentifier oid : sortedUsages) { kps[idx++] = KeyPurposeId.getInstance(oid); } return new ExtendedKeyUsage(kps); }
Example 23
| Project: gizmo-master File: CertificateCreator.java View source code |
/**
* Utility method for generating a "standard" server certificate. Recognized by most
* browsers as valid for SSL/TLS. These certificates are generated de novo, not from
* a template, so they will not retain the structure of the original certificate and may
* not be suitable for applications that require Extended Validation/High Assurance SSL
* or other distinct extensions or EKU.
*
* @param newPubKey
* @param caCert
* @param caPrivateKey
* @param hostname
* @return
* @throws CertificateParsingException
* @throws SignatureException
* @throws InvalidKeyException
* @throws CertificateExpiredException
* @throws CertificateNotYetValidException
* @throws CertificateException
* @throws NoSuchAlgorithmException
* @throws NoSuchProviderException
*/
public static X509Certificate generateStdSSLServerCertificate(final PublicKey newPubKey, final X509Certificate caCert, final PrivateKey caPrivateKey, final String subject) throws CertificateParsingException, SignatureException, InvalidKeyException, CertificateExpiredException, CertificateNotYetValidException, CertificateException, NoSuchAlgorithmException, NoSuchProviderException {
X509V3CertificateGenerator v3CertGen = new X509V3CertificateGenerator();
v3CertGen.setSubjectDN(new X500Principal(subject));
v3CertGen.setSignatureAlgorithm(CertificateCreator.SIGN_ALGO);
v3CertGen.setPublicKey(newPubKey);
v3CertGen.setNotAfter(new Date(System.currentTimeMillis() + 1000L * 60 * 60 * 24 * 30 * 12));
v3CertGen.setNotBefore(new Date(System.currentTimeMillis() - 1000L * 60 * 60 * 24 * 30 * 12));
v3CertGen.setIssuerDN(caCert.getSubjectX500Principal());
// Firefox actually tracks serial numbers within a CA and refuses to validate if it sees duplicates
// This is not a secure serial number generator, (duh!) but it's good enough for our purposes.
v3CertGen.setSerialNumber(new BigInteger(Long.toString(System.currentTimeMillis())));
v3CertGen.addExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(false));
v3CertGen.addExtension(X509Extensions.SubjectKeyIdentifier, false, new SubjectKeyIdentifierStructure(newPubKey));
v3CertGen.addExtension(X509Extensions.AuthorityKeyIdentifier, false, new AuthorityKeyIdentifierStructure(caCert.getPublicKey()));
// Firefox 2 disallows these extensions in an SSL server cert. IE7 doesn't care.
// v3CertGen.addExtension(
// X509Extensions.KeyUsage,
// false,
// new KeyUsage(KeyUsage.dataEncipherment | KeyUsage.digitalSignature ) );
DEREncodableVector typicalSSLServerExtendedKeyUsages = new DEREncodableVector();
typicalSSLServerExtendedKeyUsages.add(new DERObjectIdentifier(ExtendedKeyUsageConstants.serverAuth));
typicalSSLServerExtendedKeyUsages.add(new DERObjectIdentifier(ExtendedKeyUsageConstants.clientAuth));
typicalSSLServerExtendedKeyUsages.add(new DERObjectIdentifier(ExtendedKeyUsageConstants.netscapeServerGatedCrypto));
typicalSSLServerExtendedKeyUsages.add(new DERObjectIdentifier(ExtendedKeyUsageConstants.msServerGatedCrypto));
v3CertGen.addExtension(X509Extensions.ExtendedKeyUsage, false, new DERSequence(typicalSSLServerExtendedKeyUsages));
// Disabled by default. Left in comments in case this is desired.
//
// v3CertGen.addExtension(
// X509Extensions.AuthorityInfoAccess,
// false,
// new AuthorityInformationAccess(new DERObjectIdentifier(OID_ID_AD_CAISSUERS),
// new GeneralName(GeneralName.uniformResourceIdentifier, "http://" + subject + "/aia")));
// v3CertGen.addExtension(
// X509Extensions.CRLDistributionPoints,
// false,
// new CRLDistPoint(new DistributionPoint[] {}));
X509Certificate cert = v3CertGen.generateX509Certificate(caPrivateKey, "BC");
return cert;
}Example 24
| Project: google-tv-remote-jb-master File: SslUtil.java View source code |
/**
* Generates a new, self-signed X509 V3 certificate for a KeyPair.
*
* @param pair
* the {@link KeyPair} to be used
* @param name
* X.500 distinguished name
* @param notBefore
* not valid before this date
* @param notAfter
* not valid after this date
* @param serialNumber
* serial number
* @return the new certificate
* @throws GeneralSecurityException
* on error generating the certificate
*/
@SuppressWarnings("deprecation")
public static X509Certificate generateX509V3Certificate(KeyPair pair, String name, Date notBefore, Date notAfter, BigInteger serialNumber) throws GeneralSecurityException {
java.security.Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
org.bouncycastle.x509.X509V3CertificateGenerator certGen = new org.bouncycastle.x509.X509V3CertificateGenerator();
X500Name dnName = new org.bouncycastle.asn1.x500.X500Name(name);
X500Principal principal = new X500Principal(name);
certGen.setSerialNumber(serialNumber);
// certGen.setIssuerDN(dnName);
// certGen.setSubjectDN(dnName); // note: same as issuer
certGen.setIssuerDN(principal);
certGen.setSubjectDN(principal);
certGen.setNotBefore(notBefore);
certGen.setNotAfter(notAfter);
certGen.setPublicKey(pair.getPublic());
certGen.setSignatureAlgorithm("SHA256WithRSAEncryption");
// For self-signed certificates, OpenSSL 0.9.6 has specific requirements
// about certificate and extension content. Quoting the `man verify`:
//
// In OpenSSL 0.9.6 and later all certificates whose subject name
// matches
// the issuer name of the current certificate are subject to further
// tests. The relevant authority key identifier components of the
// current
// certificate (if present) must match the subject key identifier (if
// present) and issuer and serial number of the candidate issuer, in
// addition the keyUsage extension of the candidate issuer (if present)
// must permit certificate signing.
//
// In the code that follows,
// - the KeyUsage extension permits cert signing (KeyUsage.keyCertSign);
// - the Authority Key Identifier extension is added, matching the
// subject key identifier, and using the issuer, and serial number.
certGen.addExtension(X509Extension.basicConstraints, true, new BasicConstraints(false));
certGen.addExtension(X509Extension.keyUsage, true, new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyEncipherment | KeyUsage.keyCertSign));
certGen.addExtension(X509Extension.extendedKeyUsage, true, new ExtendedKeyUsage(KeyPurposeId.id_kp_serverAuth));
AuthorityKeyIdentifier authIdentifier = createAuthorityKeyIdentifier(pair.getPublic(), dnName, serialNumber);
certGen.addExtension(X509Extension.authorityKeyIdentifier, true, authIdentifier);
// certGen.addExtension(X509Extension.subjectKeyIdentifier, true,
// new SubjectKeyIdentifier(pair.getPublic()));
certGen.addExtension(X509Extension.subjectAlternativeName, false, new GeneralNames(new GeneralName(GeneralName.rfc822Name, "googletv@test.test")));
// This method is deprecated, but Android Eclair does not provide the
// generate() methods.
X509Certificate cert = certGen.generate(pair.getPrivate(), "BC");
return cert;
}Example 25
| Project: nuxeo-signature-master File: CertServiceImpl.java View source code |
protected X509Certificate createCertificateFromCSR(PKCS10CertificationRequest csr) throws CertException {
X509Certificate cert;
try {
X509V3CertificateGenerator certGen = new X509V3CertificateGenerator();
certGen.setSerialNumber(BigInteger.valueOf(System.currentTimeMillis()));
certGen.setIssuerDN(getRootCertificate().getIssuerX500Principal());
certGen.setSubjectDN(csr.getCertificationRequestInfo().getSubject());
certGen.setNotBefore(getCertStartDate());
certGen.setNotAfter(getCertEndDate());
certGen.setPublicKey(csr.getPublicKey("BC"));
certGen.setSignatureAlgorithm(CERT_SIGNATURE_ALGORITHM);
certGen.addExtension(X509Extensions.SubjectKeyIdentifier, false, new SubjectKeyIdentifierStructure(csr.getPublicKey("BC")));
certGen.addExtension(X509Extensions.AuthorityKeyIdentifier, false, new AuthorityKeyIdentifierStructure(getRootCertificate()));
certGen.addExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(false));
certGen.addExtension(X509Extensions.KeyUsage, true, new KeyUsage(KeyUsage.digitalSignature));
certGen.addExtension(X509Extensions.ExtendedKeyUsage, true, new ExtendedKeyUsage(KeyPurposeId.id_kp_serverAuth));
ASN1Set attributes = csr.getCertificationRequestInfo().getAttributes();
for (int i = 0; i != attributes.size(); i++) {
Attribute attr = Attribute.getInstance(attributes.getObjectAt(i));
if (attr.getAttrType().equals(PKCSObjectIdentifiers.pkcs_9_at_extensionRequest)) {
X509Extensions extensions = X509Extensions.getInstance(attr.getAttrValues().getObjectAt(0));
@SuppressWarnings("rawtypes") Enumeration e = extensions.oids();
while (e.hasMoreElements()) {
DERObjectIdentifier oid = (DERObjectIdentifier) e.nextElement();
X509Extension ext = extensions.getExtension(oid);
certGen.addExtension(oid, ext.isCritical(), ext.getValue().getOctets());
}
}
}
KeyPair rootKeyPair = getKeyPair(rootService.getRootKeyStore(), rootService.getRootKeyAlias(), rootService.getRootCertificateAlias(), rootService.getRootKeyPassword());
cert = certGen.generate(rootKeyPair.getPrivate(), "BC");
} catch (CertificateParsingException e) {
throw new CertException(e);
} catch (CertificateEncodingException e) {
throw new CertException(e);
} catch (InvalidKeyException e) {
throw new CertException(e);
} catch (IllegalStateException e) {
throw new CertException(e);
} catch (NoSuchProviderException e) {
throw new CertException(e);
} catch (NoSuchAlgorithmException e) {
throw new CertException(e);
} catch (java.security.SignatureException e) {
throw new CertException(e);
}
LOG.debug("Certificate generated for subject: " + cert.getSubjectDN());
return cert;
}Example 26
| Project: pwm-master File: HttpsServerCertificateManager.java View source code |
public static X509Certificate generateV3Certificate(final KeyPair pair, final String cnValue, final long futureSeconds) throws Exception {
final X500NameBuilder subjectName = new X500NameBuilder(BCStyle.INSTANCE);
subjectName.addRDN(BCStyle.CN, cnValue);
final SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddhhmmss");
final String serNumStr = formatter.format(new Date(System.currentTimeMillis()));
final BigInteger serialNumber = new BigInteger(serNumStr);
// 2 days in the past
final Date notBefore = new Date(System.currentTimeMillis() - TimeUnit.DAYS.toMillis(2));
final Date notAfter = new Date(System.currentTimeMillis() + (futureSeconds * 1000));
final X509v3CertificateBuilder certGen = new JcaX509v3CertificateBuilder(subjectName.build(), serialNumber, notBefore, notAfter, subjectName.build(), pair.getPublic());
// not a CA
final BasicConstraints basic = new BasicConstraints(false);
// OID, critical, ASN.1 encoded value
certGen.addExtension(Extension.basicConstraints, true, basic.getEncoded());
// sign and key encipher
final KeyUsage keyUsage = new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyEncipherment);
// OID, critical, ASN.1 encoded value
certGen.addExtension(Extension.keyUsage, true, keyUsage.getEncoded());
// server authentication
final ExtendedKeyUsage extKeyUsage = new ExtendedKeyUsage(KeyPurposeId.id_kp_serverAuth);
// OID, critical, ASN.1 encoded value
certGen.addExtension(Extension.extendedKeyUsage, true, extKeyUsage.getEncoded());
final ContentSigner sigGen = new JcaContentSignerBuilder("SHA256WithRSAEncryption").setProvider("BC").build(pair.getPrivate());
return new JcaX509CertificateConverter().setProvider("BC").getCertificate(certGen.build(sigGen));
}Example 27
| Project: alien-ofelia-conet-ccnx-master File: MinimalCertificateGenerator.java View source code |
/**
* Open up the ability to add additional extensions that aren't
* EKU or SubjectAltName (which we manage).
*/
public void addExtension(String oid, boolean critical, byte[] value) {
if (null == oid)
throw new IllegalArgumentException("OID cannot be null!");
DERObjectIdentifier derOID = new DERObjectIdentifier(oid);
if ((derOID.equals(X509Extensions.ExtendedKeyUsage)) || (derOID.equals(X509Extensions.SubjectAlternativeName)) || (derOID.equals(X509Extensions.AuthorityKeyIdentifier))) {
throw new IllegalArgumentException("Cannot use addExtension to set ExtendedKeyUsage or SubjectAlternativeName or AuthorityKeyIdentifier!");
}
_generator.addExtension(derOID, critical, value);
}Example 28
| Project: android-rcs-ims-stack-master File: KeyStoreManager.java View source code |
// Changed by Deutsche Telekom
private static synchronized void createClientCertificate(String ipAddress) {
try {
// IP address hasn't changed
if (ipAddress != null && ipAddress.equals(lastIpAddress)) {
if (logger.isActivated()) {
logger.debug("IP address hasn't changed. No update needed.");
}
return;
}
// remember IP address for next update
lastIpAddress = ipAddress;
// Load the keystore from file
KeyStore ks = KeyStoreManager.loadKeyStoreFromFile();
if (ks == null) {
// loading keystore failed
return;
}
// handle private and public key
PrivateKey privKey = null;
PublicKey pubKey = null;
if (ks.isKeyEntry(CLIENT_CERT_ALIAS)) {
// recycle key & certificate
if (logger.isActivated()) {
logger.debug("old keypair is recycled");
}
PrivateKeyEntry entry = (PrivateKeyEntry) ks.getEntry(CLIENT_CERT_ALIAS, new KeyStore.PasswordProtection(KEYSTORE_PASSWORD.toCharArray()));
privKey = entry.getPrivateKey();
pubKey = entry.getCertificate().getPublicKey();
ks.deleteEntry(CLIENT_CERT_ALIAS);
} else {
// generate key pair to be used by the certificate
if (logger.isActivated()) {
logger.debug("new keypair is generated");
}
KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
SecureRandom secureRandom = new SecureRandom();
// Do *not* seed secureRandom! Automatically seeded
// from system entropy.
keyGen.initialize(1024, secureRandom);
KeyPair keypair = keyGen.generateKeyPair();
privKey = keypair.getPrivate();
pubKey = keypair.getPublic();
}
// generate a new X.509 certificate
X509Certificate[] certChain = new X509Certificate[1];
// X500Name subjectName = new X500Name("CN="
// + OemCustomization.customizeString("com.orangelabs.rcs.client"));
X500Name subjectName = new X500Name("CN=com.orangelabs.rcs.client");
Date startDate = new Date(System.currentTimeMillis() - 24 * 60 * 60 * 1000);
// validity of 1 year
Date endDate = new Date(System.currentTimeMillis() + 365L * 26 * 60 * 60 * 1000);
X509v3CertificateBuilder certGen = new JcaX509v3CertificateBuilder(subjectName, BigInteger.ONE, startDate, endDate, subjectName, pubKey);
JcaX509ExtensionUtils x509ExtUtils = new JcaX509ExtensionUtils();
certGen.addExtension(X509Extension.subjectKeyIdentifier, false, (ASN1Encodable) x509ExtUtils.createSubjectKeyIdentifier(pubKey));
certGen.addExtension(X509Extension.authorityKeyIdentifier, false, (ASN1Encodable) x509ExtUtils.createAuthorityKeyIdentifier(pubKey));
certGen.addExtension(X509Extension.keyUsage, false, new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyCertSign));
certGen.addExtension(X509Extension.extendedKeyUsage, false, new ExtendedKeyUsage(KeyPurposeId.id_kp_clientAuth));
// set subjectAltName to IP address and SIP URI
certGen.addExtension(X509Extension.subjectAlternativeName, false, new GeneralNames(new GeneralName[] { new GeneralName(GeneralName.iPAddress, ipAddress), new GeneralName(GeneralName.uniformResourceIdentifier, ImsModule.IMS_USER_PROFILE.getPublicUri()) }));
// set basicConstraints to CA
certGen.addExtension(X509Extension.basicConstraints, false, new BasicConstraints(true));
// self-sign certificate
ContentSigner sigGen = new SimpleContentSignerBuilder().build(privKey);
JcaX509CertificateConverter certConv = new JcaX509CertificateConverter();
certChain[0] = certConv.getCertificate(certGen.build(sigGen));
// store fingerprint for further use
KeyStoreManager.setClientCertificateFingerprint(certChain[0]);
// place new key (incl. certificate) into keystore
ks.setEntry(CLIENT_CERT_ALIAS, new KeyStore.PrivateKeyEntry(privKey, certChain), new KeyStore.PasswordProtection(KEYSTORE_PASSWORD.toCharArray()));
// Save the keystore to file
KeyStoreManager.saveKeyStoreToFile(ks);
if (logger.isActivated()) {
logger.debug("Client certificate " + CLIENT_CERT_ALIAS + " for IP address " + ipAddress + " with fingerprint " + KeyStoreManager.getClientCertificateFingerprint() + " added");
}
} catch (Exception ex) {
if (logger.isActivated()) {
logger.error("Creating client certificate failed: ", ex);
}
}
}Example 29
| Project: BitNomen-master File: MinimalCertificateGenerator.java View source code |
/**
* Open up the ability to add additional extensions that aren't
* EKU or SubjectAltName (which we manage).
*/
public void addExtension(String oid, boolean critical, byte[] value) {
if (null == oid)
throw new IllegalArgumentException("OID cannot be null!");
DERObjectIdentifier derOID = new DERObjectIdentifier(oid);
if ((derOID.equals(X509Extensions.ExtendedKeyUsage)) || (derOID.equals(X509Extensions.SubjectAlternativeName)) || (derOID.equals(X509Extensions.AuthorityKeyIdentifier))) {
throw new IllegalArgumentException("Cannot use addExtension to set ExtendedKeyUsage or SubjectAlternativeName or AuthorityKeyIdentifier!");
}
_generator.addExtension(derOID, critical, value);
}Example 30
| Project: ccnx-master File: MinimalCertificateGenerator.java View source code |
/**
* Open up the ability to add additional extensions that aren't
* EKU or SubjectAltName (which we manage).
*/
public void addExtension(String oid, boolean critical, byte[] value) {
if (null == oid)
throw new IllegalArgumentException("OID cannot be null!");
DERObjectIdentifier derOID = new DERObjectIdentifier(oid);
if ((derOID.equals(X509Extensions.ExtendedKeyUsage)) || (derOID.equals(X509Extensions.SubjectAlternativeName)) || (derOID.equals(X509Extensions.AuthorityKeyIdentifier))) {
throw new IllegalArgumentException("Cannot use addExtension to set ExtendedKeyUsage or SubjectAlternativeName or AuthorityKeyIdentifier!");
}
_generator.addExtension(derOID, critical, value);
}Example 31
| Project: dc---master File: CertificateTest.java View source code |
public void checkCertificate(int id, byte[] cert) throws Exception {
ByteArrayInputStream bIn = new ByteArrayInputStream(cert);
ASN1InputStream aIn = new ASN1InputStream(bIn);
ASN1Sequence seq = (ASN1Sequence) aIn.readObject();
// String dump = ASN1Dump.dumpAsString(seq);
X509CertificateStructure obj = new X509CertificateStructure(seq);
TBSCertificateStructure tbsCert = obj.getTBSCertificate();
if (!tbsCert.getSubject().toString().equals(subjects[id - 1])) {
fail("failed subject test for certificate id " + id + " got " + tbsCert.getSubject().toString());
}
if (tbsCert.getVersion() == 3) {
X509Extensions ext = tbsCert.getExtensions();
if (ext != null) {
Enumeration en = ext.oids();
while (en.hasMoreElements()) {
DERObjectIdentifier oid = (DERObjectIdentifier) en.nextElement();
X509Extension extVal = ext.getExtension(oid);
ASN1OctetString oct = extVal.getValue();
ASN1InputStream extIn = new ASN1InputStream(new ByteArrayInputStream(oct.getOctets()));
if (oid.equals(X509Extensions.SubjectKeyIdentifier)) {
SubjectKeyIdentifier si = SubjectKeyIdentifier.getInstance(extIn.readObject());
} else if (oid.equals(X509Extensions.KeyUsage)) {
DERBitString ku = KeyUsage.getInstance(extIn.readObject());
} else if (oid.equals(X509Extensions.ExtendedKeyUsage)) {
ExtendedKeyUsage ku = ExtendedKeyUsage.getInstance(extIn.readObject());
ASN1Sequence sq = (ASN1Sequence) ku.getDERObject();
for (int i = 0; i != sq.size(); i++) {
DERObjectIdentifier p = KeyPurposeId.getInstance(sq.getObjectAt(i));
}
} else if (oid.equals(X509Extensions.SubjectAlternativeName)) {
GeneralNames gn = GeneralNames.getInstance(extIn.readObject());
ASN1Sequence sq = (ASN1Sequence) gn.getDERObject();
for (int i = 0; i != sq.size(); i++) {
GeneralName n = GeneralName.getInstance(sq.getObjectAt(i));
}
} else if (oid.equals(X509Extensions.IssuerAlternativeName)) {
GeneralNames gn = GeneralNames.getInstance(extIn.readObject());
ASN1Sequence sq = (ASN1Sequence) gn.getDERObject();
for (int i = 0; i != sq.size(); i++) {
GeneralName n = GeneralName.getInstance(sq.getObjectAt(i));
}
} else if (oid.equals(X509Extensions.CRLDistributionPoints)) {
CRLDistPoint p = CRLDistPoint.getInstance(extIn.readObject());
DistributionPoint[] points = p.getDistributionPoints();
for (int i = 0; i != points.length; i++) {
// do nothing
}
} else if (oid.equals(X509Extensions.CertificatePolicies)) {
ASN1Sequence cp = (ASN1Sequence) extIn.readObject();
for (int i = 0; i != cp.size(); i++) {
PolicyInformation.getInstance(cp.getObjectAt(i));
}
} else if (oid.equals(X509Extensions.AuthorityKeyIdentifier)) {
AuthorityKeyIdentifier auth = AuthorityKeyIdentifier.getInstance(extIn.readObject());
} else if (oid.equals(X509Extensions.BasicConstraints)) {
BasicConstraints bc = BasicConstraints.getInstance(extIn.readObject());
} else {
//System.out.println(oid.getId());
}
}
}
}
}Example 32
| Project: tita-master File: TiTASecurity.java View source code |
/**
* Generates a fresh Certificate for a Users KeyPair.
*
* @param pair the KeyPair to create a Certificate for.
* @param userName the Issuer of the Certificate
* @return a 10 Year valid Certificate for the User.
* @throws TiTASecurityException If an error occurs during the generation Process.
*/
private static X509Certificate generateV3Certificate(KeyPair pair, String userName) throws TiTASecurityException {
Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
X509V3CertificateGenerator certGen = new X509V3CertificateGenerator();
certGen.setSerialNumber(BigInteger.valueOf(System.currentTimeMillis()));
certGen.setIssuerDN(new X500Principal("CN=" + userName + " Certificate"));
certGen.setNotBefore(new Date(System.currentTimeMillis()));
certGen.setNotAfter(new Date(System.currentTimeMillis() + VALID_TIME_RANGE));
certGen.setSubjectDN(new X500Principal("CN=" + userName + " Certificate"));
certGen.setPublicKey(pair.getPublic());
certGen.setSignatureAlgorithm("SHA256WithRSAEncryption");
certGen.addExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(false));
certGen.addExtension(X509Extensions.KeyUsage, true, new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyEncipherment));
certGen.addExtension(X509Extensions.ExtendedKeyUsage, true, new ExtendedKeyUsage(KeyPurposeId.id_kp_serverAuth));
X509Certificate targetCertificate = null;
try {
targetCertificate = certGen.generate(pair.getPrivate(), "BC");
} catch (NoSuchProviderException e) {
log.error("Could create a certificate for: " + userName + ".");
throw new TiTASecurityException("Error while Generating a Certificate for: " + userName + ". Specified provider was not found.\n" + e.getMessage());
} catch (NoSuchAlgorithmException e) {
log.error("Could create a certificate for: " + userName + ".");
throw new TiTASecurityException("Error while Generating a Certificate for: " + userName + ". Specified algorithm was not found.\n" + e.getMessage());
} catch (SignatureException e) {
log.error("Could create a certificate for: " + userName + ".");
throw new TiTASecurityException("Error while Generating a Certificate for: " + userName + ". Signature is not valid.\n" + e.getMessage());
} catch (CertificateEncodingException e) {
log.error("Could create a certificate for: " + userName + ".");
throw new TiTASecurityException("Error while Generating a Certificate for: " + userName + ". Wrong encoding for Signature.\n" + e.getMessage());
} catch (InvalidKeyException e) {
log.error("Could create a certificate for: " + userName + ".");
throw new TiTASecurityException("Error while Generating a Certificate for: " + userName + ". The Key is not valid.\n" + e.getMessage());
}
return targetCertificate;
}Example 33
| Project: UNH_NDN-master File: MinimalCertificateGenerator.java View source code |
/**
* Open up the ability to add additional extensions that aren't
* EKU or SubjectAltName (which we manage).
*/
public void addExtension(String oid, boolean critical, byte[] value) {
if (null == oid)
throw new IllegalArgumentException("OID cannot be null!");
DERObjectIdentifier derOID = new DERObjectIdentifier(oid);
if ((derOID.equals(X509Extensions.ExtendedKeyUsage)) || (derOID.equals(X509Extensions.SubjectAlternativeName)) || (derOID.equals(X509Extensions.AuthorityKeyIdentifier))) {
throw new IllegalArgumentException("Cannot use addExtension to set ExtendedKeyUsage or SubjectAlternativeName or AuthorityKeyIdentifier!");
}
_generator.addExtension(derOID, critical, value);
}Example 34
| Project: android-libcore64-master File: TestKeyStore.java View source code |
private static X509Certificate createCertificate(PublicKey publicKey, PrivateKey privateKey, X500Principal subject, X500Principal issuer, int keyUsage, boolean ca, List<KeyPurposeId> extendedKeyUsages, List<Boolean> criticalExtendedKeyUsages, List<GeneralName> subjectAltNames, List<GeneralSubtree> permittedNameConstraints, List<GeneralSubtree> excludedNameConstraints) throws Exception {
// Note that there is no way to programmatically make a
// Certificate using java.* or javax.* APIs. The
// CertificateFactory interface assumes you want to read
// in a stream of bytes, typically the X.509 factory would
// allow ASN.1 DER encoded bytes and optionally some PEM
// formats. Here we use Bouncy Castle's
// X509V3CertificateGenerator and related classes.
long millisPerDay = 24 * 60 * 60 * 1000;
long now = System.currentTimeMillis();
Date start = new Date(now - millisPerDay);
Date end = new Date(now + millisPerDay);
BigInteger serial = BigInteger.valueOf(1);
String keyAlgorithm = privateKey.getAlgorithm();
String signatureAlgorithm;
if (keyAlgorithm.equals("RSA")) {
signatureAlgorithm = "sha1WithRSA";
} else if (keyAlgorithm.equals("DSA")) {
signatureAlgorithm = "sha1WithDSA";
} else if (keyAlgorithm.equals("EC")) {
signatureAlgorithm = "sha1WithECDSA";
} else if (keyAlgorithm.equals("EC_RSA")) {
signatureAlgorithm = "sha1WithRSA";
} else {
throw new IllegalArgumentException("Unknown key algorithm " + keyAlgorithm);
}
X509V3CertificateGenerator x509cg = new X509V3CertificateGenerator();
x509cg.setSubjectDN(subject);
x509cg.setIssuerDN(issuer);
x509cg.setNotBefore(start);
x509cg.setNotAfter(end);
x509cg.setPublicKey(publicKey);
x509cg.setSignatureAlgorithm(signatureAlgorithm);
x509cg.setSerialNumber(serial);
if (keyUsage != 0) {
x509cg.addExtension(X509Extensions.KeyUsage, true, new KeyUsage(keyUsage));
}
if (ca) {
x509cg.addExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(true));
}
for (int i = 0; i < extendedKeyUsages.size(); i++) {
KeyPurposeId keyPurposeId = extendedKeyUsages.get(i);
boolean critical = criticalExtendedKeyUsages.get(i);
x509cg.addExtension(X509Extensions.ExtendedKeyUsage, critical, new ExtendedKeyUsage(keyPurposeId));
}
for (GeneralName subjectAltName : subjectAltNames) {
x509cg.addExtension(X509Extensions.SubjectAlternativeName, false, new GeneralNames(subjectAltName).getEncoded());
}
if (!permittedNameConstraints.isEmpty() || !excludedNameConstraints.isEmpty()) {
x509cg.addExtension(X509Extensions.NameConstraints, true, new NameConstraints(permittedNameConstraints.toArray(new GeneralSubtree[permittedNameConstraints.size()]), excludedNameConstraints.toArray(new GeneralSubtree[excludedNameConstraints.size()])));
}
if (privateKey instanceof ECPrivateKey) {
/*
* bouncycastle needs its own ECPrivateKey implementation
*/
KeyFactory kf = KeyFactory.getInstance(keyAlgorithm, "BC");
PKCS8EncodedKeySpec ks = new PKCS8EncodedKeySpec(privateKey.getEncoded());
privateKey = kf.generatePrivate(ks);
}
X509Certificate x509c = x509cg.generateX509Certificate(privateKey);
if (StandardNames.IS_RI) {
/*
* The RI can't handle the BC EC signature algorithm
* string of "ECDSA", since it expects "...WITHEC...",
* so convert from BC to RI X509Certificate
* implementation via bytes.
*/
CertificateFactory cf = CertificateFactory.getInstance("X.509");
ByteArrayInputStream bais = new ByteArrayInputStream(x509c.getEncoded());
Certificate c = cf.generateCertificate(bais);
x509c = (X509Certificate) c;
}
return x509c;
}Example 35
| Project: ARTPart-master File: TestKeyStore.java View source code |
private static X509Certificate createCertificate(PublicKey publicKey, PrivateKey privateKey, X500Principal subject, X500Principal issuer, int keyUsage, boolean ca, List<KeyPurposeId> extendedKeyUsages, List<Boolean> criticalExtendedKeyUsages, List<GeneralName> subjectAltNames, List<GeneralSubtree> permittedNameConstraints, List<GeneralSubtree> excludedNameConstraints) throws Exception {
// Note that there is no way to programmatically make a
// Certificate using java.* or javax.* APIs. The
// CertificateFactory interface assumes you want to read
// in a stream of bytes, typically the X.509 factory would
// allow ASN.1 DER encoded bytes and optionally some PEM
// formats. Here we use Bouncy Castle's
// X509V3CertificateGenerator and related classes.
long millisPerDay = 24 * 60 * 60 * 1000;
long now = System.currentTimeMillis();
Date start = new Date(now - millisPerDay);
Date end = new Date(now + millisPerDay);
BigInteger serial = BigInteger.valueOf(1);
String keyAlgorithm = privateKey.getAlgorithm();
String signatureAlgorithm;
if (keyAlgorithm.equals("RSA")) {
signatureAlgorithm = "sha1WithRSA";
} else if (keyAlgorithm.equals("DSA")) {
signatureAlgorithm = "sha1WithDSA";
} else if (keyAlgorithm.equals("EC")) {
signatureAlgorithm = "sha1WithECDSA";
} else if (keyAlgorithm.equals("EC_RSA")) {
signatureAlgorithm = "sha1WithRSA";
} else {
throw new IllegalArgumentException("Unknown key algorithm " + keyAlgorithm);
}
X509V3CertificateGenerator x509cg = new X509V3CertificateGenerator();
x509cg.setSubjectDN(subject);
x509cg.setIssuerDN(issuer);
x509cg.setNotBefore(start);
x509cg.setNotAfter(end);
x509cg.setPublicKey(publicKey);
x509cg.setSignatureAlgorithm(signatureAlgorithm);
x509cg.setSerialNumber(serial);
if (keyUsage != 0) {
x509cg.addExtension(X509Extensions.KeyUsage, true, new KeyUsage(keyUsage));
}
if (ca) {
x509cg.addExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(true));
}
for (int i = 0; i < extendedKeyUsages.size(); i++) {
KeyPurposeId keyPurposeId = extendedKeyUsages.get(i);
boolean critical = criticalExtendedKeyUsages.get(i);
x509cg.addExtension(X509Extensions.ExtendedKeyUsage, critical, new ExtendedKeyUsage(keyPurposeId));
}
for (GeneralName subjectAltName : subjectAltNames) {
x509cg.addExtension(X509Extensions.SubjectAlternativeName, false, new GeneralNames(subjectAltName).getEncoded());
}
if (!permittedNameConstraints.isEmpty() || !excludedNameConstraints.isEmpty()) {
x509cg.addExtension(X509Extensions.NameConstraints, true, new NameConstraints(permittedNameConstraints.toArray(new GeneralSubtree[permittedNameConstraints.size()]), excludedNameConstraints.toArray(new GeneralSubtree[excludedNameConstraints.size()])));
}
X509Certificate x509c = x509cg.generateX509Certificate(privateKey);
if (StandardNames.IS_RI) {
/*
* The RI can't handle the BC EC signature algorithm
* string of "ECDSA", since it expects "...WITHEC...",
* so convert from BC to RI X509Certificate
* implementation via bytes.
*/
CertificateFactory cf = CertificateFactory.getInstance("X.509");
ByteArrayInputStream bais = new ByteArrayInputStream(x509c.getEncoded());
Certificate c = cf.generateCertificate(bais);
x509c = (X509Certificate) c;
}
return x509c;
}Example 36
| Project: robovm-master File: TestKeyStore.java View source code |
private static X509Certificate createCertificate(PublicKey publicKey, PrivateKey privateKey, X500Principal subject, X500Principal issuer, int keyUsage, boolean ca, List<KeyPurposeId> extendedKeyUsages, List<Boolean> criticalExtendedKeyUsages, List<GeneralName> subjectAltNames, List<GeneralSubtree> permittedNameConstraints, List<GeneralSubtree> excludedNameConstraints) throws Exception {
// Note that there is no way to programmatically make a
// Certificate using java.* or javax.* APIs. The
// CertificateFactory interface assumes you want to read
// in a stream of bytes, typically the X.509 factory would
// allow ASN.1 DER encoded bytes and optionally some PEM
// formats. Here we use Bouncy Castle's
// X509V3CertificateGenerator and related classes.
long millisPerDay = 24 * 60 * 60 * 1000;
long now = System.currentTimeMillis();
Date start = new Date(now - millisPerDay);
Date end = new Date(now + millisPerDay);
BigInteger serial = BigInteger.valueOf(1);
String keyAlgorithm = privateKey.getAlgorithm();
String signatureAlgorithm;
if (keyAlgorithm.equals("RSA")) {
signatureAlgorithm = "sha1WithRSA";
} else if (keyAlgorithm.equals("DSA")) {
signatureAlgorithm = "sha1WithDSA";
} else if (keyAlgorithm.equals("EC")) {
signatureAlgorithm = "sha1WithECDSA";
} else if (keyAlgorithm.equals("EC_RSA")) {
signatureAlgorithm = "sha1WithRSA";
} else {
throw new IllegalArgumentException("Unknown key algorithm " + keyAlgorithm);
}
X509V3CertificateGenerator x509cg = new X509V3CertificateGenerator();
x509cg.setSubjectDN(subject);
x509cg.setIssuerDN(issuer);
x509cg.setNotBefore(start);
x509cg.setNotAfter(end);
x509cg.setPublicKey(publicKey);
x509cg.setSignatureAlgorithm(signatureAlgorithm);
x509cg.setSerialNumber(serial);
if (keyUsage != 0) {
x509cg.addExtension(X509Extensions.KeyUsage, true, new KeyUsage(keyUsage));
}
if (ca) {
x509cg.addExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(true));
}
for (int i = 0; i < extendedKeyUsages.size(); i++) {
KeyPurposeId keyPurposeId = extendedKeyUsages.get(i);
boolean critical = criticalExtendedKeyUsages.get(i);
x509cg.addExtension(X509Extensions.ExtendedKeyUsage, critical, new ExtendedKeyUsage(keyPurposeId));
}
for (GeneralName subjectAltName : subjectAltNames) {
x509cg.addExtension(X509Extensions.SubjectAlternativeName, false, new GeneralNames(subjectAltName).getEncoded());
}
if (!permittedNameConstraints.isEmpty() || !excludedNameConstraints.isEmpty()) {
x509cg.addExtension(X509Extensions.NameConstraints, true, new NameConstraints(permittedNameConstraints.toArray(new GeneralSubtree[permittedNameConstraints.size()]), excludedNameConstraints.toArray(new GeneralSubtree[excludedNameConstraints.size()])));
}
if (privateKey instanceof ECPrivateKey) {
/*
* bouncycastle needs its own ECPrivateKey implementation
*/
KeyFactory kf = KeyFactory.getInstance(keyAlgorithm, "BC");
PKCS8EncodedKeySpec ks = new PKCS8EncodedKeySpec(privateKey.getEncoded());
privateKey = kf.generatePrivate(ks);
}
X509Certificate x509c = x509cg.generateX509Certificate(privateKey);
if (StandardNames.IS_RI) {
/*
* The RI can't handle the BC EC signature algorithm
* string of "ECDSA", since it expects "...WITHEC...",
* so convert from BC to RI X509Certificate
* implementation via bytes.
*/
CertificateFactory cf = CertificateFactory.getInstance("X.509");
ByteArrayInputStream bais = new ByteArrayInputStream(x509c.getEncoded());
Certificate c = cf.generateCertificate(bais);
x509c = (X509Certificate) c;
}
return x509c;
}Example 37
| Project: pades_signing_2.1.5-master File: PDFSignTest.java View source code |
public static void validateCertificate(X509Certificate paramX509Certificate) throws TSPValidationException {
if (paramX509Certificate.getVersion() != 3)
throw new IllegalArgumentException("Certificate must have an ExtendedKeyUsage extension.");
byte[] arrayOfByte = paramX509Certificate.getExtensionValue(X509Extensions.ExtendedKeyUsage.getId());
if (arrayOfByte == null)
throw new TSPValidationException("Certificate must have an ExtendedKeyUsage extension.");
if (!(paramX509Certificate.getCriticalExtensionOIDs().contains(X509Extensions.ExtendedKeyUsage.getId())))
throw new TSPValidationException("Certificate must have an ExtendedKeyUsage extension marked as critical.");
ASN1InputStream localASN1InputStream = new ASN1InputStream(new ByteArrayInputStream(arrayOfByte));
try {
localASN1InputStream = new ASN1InputStream(new ByteArrayInputStream(((ASN1OctetString) localASN1InputStream.readObject()).getOctets()));
ExtendedKeyUsage localExtendedKeyUsage = ExtendedKeyUsage.getInstance(localASN1InputStream.readObject());
if ((!(localExtendedKeyUsage.hasKeyPurposeId(KeyPurposeId.id_kp_timeStamping))) || (localExtendedKeyUsage.size() != 1))
throw new TSPValidationException("ExtendedKeyUsage not solely time stamping.");
} catch (IOException localIOException) {
throw new TSPValidationException("cannot process ExtendedKeyUsage extension");
}
}Example 38
| Project: xwiki-commons-master File: BcX509Extensions.java View source code |
@Override
public ExtendedKeyUsages getExtendedKeyUsage() {
return BcExtensionUtils.getExtendedKeyUsages(ExtendedKeyUsage.fromExtensions(this.extensions));
}