use of javax.security.auth.x500.X500Principal in project OpenAttestation by OpenAttestation.
the class CertificateUtils method generateSelfSignedX509Certificate.
/**
* Generate a self signed X509 certificate with Bouncy Castle.
* @throws SignatureException
* @throws IllegalStateException
* @throws InvalidKeyException
* @throws CertificateEncodingException
*/
public static X509Certificate generateSelfSignedX509Certificate() throws NoSuchAlgorithmException, NoSuchProviderException, CertificateEncodingException, InvalidKeyException, IllegalStateException, SignatureException {
Security.addProvider(new BouncyCastleProvider());
int validityDays = 3652;
// GENERATE THE PUBLIC/PRIVATE RSA KEY PAIR
KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA", "BC");
keyPairGenerator.initialize(1024, new SecureRandom());
KeyPair keyPair = keyPairGenerator.generateKeyPair();
// GENERATE THE X509 CERTIFICATE
X509V1CertificateGenerator certGen = new X509V1CertificateGenerator();
X500Principal dnName = new X500Principal("CN=OATServer");
certGen.setSerialNumber(BigInteger.valueOf(System.currentTimeMillis()));
certGen.setSubjectDN(dnName);
// use the same
certGen.setIssuerDN(dnName);
certGen.setNotBefore(new java.sql.Time(System.currentTimeMillis()));
Calendar expiry = Calendar.getInstance();
expiry.add(Calendar.DAY_OF_YEAR, validityDays);
certGen.setNotAfter(expiry.getTime());
certGen.setPublicKey(keyPair.getPublic());
certGen.setSignatureAlgorithm("SHA256WithRSAEncryption");
X509Certificate cert = certGen.generate(keyPair.getPrivate(), "BC");
return cert;
}
use of javax.security.auth.x500.X500Principal in project Openfire by igniterealtime.
the class OCSPChecker method check.
@Override
public void check(Certificate cert, Collection<String> unresolvedCritExts) throws CertPathValidatorException {
Log.debug("OCSPChecker: check called");
InputStream in = null;
OutputStream out = null;
try {
// Examine OCSP properties
X509Certificate responderCert = null;
//defaults to issuers cert
boolean haveResponderCert = true;
X500Principal responderSubjectName = null;
boolean haveIssuerCert = false;
// If we set the subject name, we need to find the certificate
if (ocspServerSubject != null) {
haveResponderCert = false;
responderSubjectName = new X500Principal(ocspServerSubject);
}
X509Certificate issuerCert = null;
X509Certificate currCert = (X509Certificate) cert;
// Set the issuer certificate if we were passed a chain
if (certIndex != 0) {
issuerCert = certs[certIndex];
haveIssuerCert = true;
if (haveResponderCert) {
responderCert = certs[certIndex];
}
}
if (!haveIssuerCert || !haveResponderCert) {
if (!haveResponderCert) {
Log.debug("OCSPChecker: Looking for responder's certificate");
}
if (!haveIssuerCert) {
Log.debug("OCSPChecker: Looking for issuer's certificate");
}
// Extract the anchor certs
Iterator anchors = pkixParams.getTrustAnchors().iterator();
if (!anchors.hasNext()) {
throw new CertPathValidatorException("Must specify at least one trust anchor");
}
X500Principal certIssuerName = currCert.getIssuerX500Principal();
while (anchors.hasNext() && (!haveIssuerCert || !haveResponderCert)) {
TrustAnchor anchor = (TrustAnchor) anchors.next();
X509Certificate anchorCert = anchor.getTrustedCert();
X500Principal anchorSubjectName = anchorCert.getSubjectX500Principal();
// Check if this anchor cert is the issuer cert
if (!haveIssuerCert && certIssuerName.equals(anchorSubjectName)) {
issuerCert = anchorCert;
haveIssuerCert = true;
//If we have not set the responderCert at this point, set it to the issuer
if (haveResponderCert && responderCert == null) {
responderCert = anchorCert;
Log.debug("OCSPChecker: Responder's certificate = issuer certificate");
}
}
// Check if this anchor cert is the responder cert
if (!haveResponderCert) {
if (responderSubjectName != null && responderSubjectName.equals(anchorSubjectName)) {
responderCert = anchorCert;
haveResponderCert = true;
}
}
}
if (issuerCert == null) {
//No trust anchor was found matching the issuer
throw new CertPathValidatorException("No trusted certificate for " + currCert.getIssuerDN());
}
// Check cert stores if responder cert has not yet been found
if (!haveResponderCert) {
Log.debug("OCSPChecker: Searching cert stores for responder's certificate");
if (responderSubjectName != null) {
X509CertSelector filter = new X509CertSelector();
filter.setSubject(responderSubjectName.getName());
List<CertStore> certStores = pkixParams.getCertStores();
for (CertStore certStore : certStores) {
Iterator i = certStore.getCertificates(filter).iterator();
if (i.hasNext()) {
responderCert = (X509Certificate) i.next();
haveResponderCert = true;
break;
}
}
}
}
}
// Could not find the responder cert
if (!haveResponderCert) {
throw new CertPathValidatorException("Cannot find the responder's certificate.");
}
// Construct an OCSP Request
OCSPReqBuilder gen = new OCSPReqBuilder();
CertificateID certID = new CertificateID(new JcaDigestCalculatorProviderBuilder().setProvider("BC").build().get(CertificateID.HASH_SHA1), new X509CertificateHolder(issuerCert.getEncoded()), currCert.getSerialNumber());
gen.addRequest(certID);
OCSPReq ocspRequest = gen.build();
URL url;
if (ocspServerUrl != null) {
try {
url = new URL(ocspServerUrl);
} catch (MalformedURLException e) {
throw new CertPathValidatorException(e);
}
} else {
throw new CertPathValidatorException("Must set OCSP Server URL");
}
HttpURLConnection con = (HttpURLConnection) url.openConnection();
Log.debug("OCSPChecker: connecting to OCSP service at: " + url);
con.setDoOutput(true);
con.setDoInput(true);
con.setRequestMethod("POST");
con.setRequestProperty("Content-type", "application/ocsp-request");
con.setRequestProperty("Accept", "application/ocsp-response");
byte[] bytes = ocspRequest.getEncoded();
con.setRequestProperty("Content-length", String.valueOf(bytes.length));
out = con.getOutputStream();
out.write(bytes);
out.flush();
// Check the response
if (con.getResponseCode() != HttpURLConnection.HTTP_OK) {
Log.debug("OCSPChecker: Received HTTP error: " + con.getResponseCode() + " - " + con.getResponseMessage());
}
in = con.getInputStream();
OCSPResp ocspResponse = new OCSPResp(in);
BigInteger serialNumber = currCert.getSerialNumber();
BasicOCSPResp brep = (BasicOCSPResp) ocspResponse.getResponseObject();
try {
if (!brep.isSignatureValid(new JcaContentVerifierProviderBuilder().setProvider("BC").build(responderCert.getPublicKey()))) {
throw new CertPathValidatorException("OCSP response is not verified");
}
} catch (Exception e) {
throw new CertPathValidatorException("OCSP response could not be verified (" + e.getMessage() + ")", null, cp, certIndex);
}
SingleResp[] singleResp = brep.getResponses();
boolean foundResponse = false;
for (SingleResp resp : singleResp) {
CertificateID respCertID = resp.getCertID();
if (respCertID.equals(certID)) {
Object status = resp.getCertStatus();
if (status == CertificateStatus.GOOD) {
Log.debug("OCSPChecker: Status of certificate (with serial number " + serialNumber.toString() + ") is: good");
foundResponse = true;
break;
} else if (status instanceof org.bouncycastle.cert.ocsp.RevokedStatus) {
Log.debug("OCSPChecker: Status of certificate (with serial number " + serialNumber.toString() + ") is: revoked");
throw new CertPathValidatorException("Certificate has been revoked", null, cp, certIndex);
} else if (status instanceof org.bouncycastle.cert.ocsp.UnknownStatus) {
Log.debug("OCSPChecker: Status of certificate (with serial number " + serialNumber.toString() + ") is: unknown");
throw new CertPathValidatorException("Certificate's revocation status is unknown", null, cp, certIndex);
} else {
Log.debug("Status of certificate (with serial number " + serialNumber.toString() + ") is: not recognized");
throw new CertPathValidatorException("Unknown OCSP response for certificate", null, cp, certIndex);
}
}
}
// Check that response applies to the cert that was supplied
if (!foundResponse) {
throw new CertPathValidatorException("No certificates in the OCSP response match the " + "certificate supplied in the OCSP request.");
}
} catch (CertPathValidatorException cpve) {
throw cpve;
} catch (Exception e) {
throw new CertPathValidatorException(e);
} finally {
if (in != null) {
try {
in.close();
} catch (IOException ioe) {
throw new CertPathValidatorException(ioe);
}
}
if (out != null) {
try {
out.close();
} catch (IOException ioe) {
throw new CertPathValidatorException(ioe);
}
}
}
}
use of javax.security.auth.x500.X500Principal in project Android-Developers-Samples by johnjohndoe.
the class BasicAndroidKeyStoreFragment method createKeys.
/**
* Creates a public and private key and stores it using the Android Key Store, so that only
* this application will be able to access the keys.
*/
public void createKeys(Context context) throws NoSuchProviderException, NoSuchAlgorithmException, InvalidAlgorithmParameterException {
// BEGIN_INCLUDE(create_valid_dates)
// Create a start and end time, for the validity range of the key pair that's about to be
// generated.
Calendar start = new GregorianCalendar();
Calendar end = new GregorianCalendar();
end.add(1, Calendar.YEAR);
//END_INCLUDE(create_valid_dates)
// BEGIN_INCLUDE(create_spec)
// The KeyPairGeneratorSpec object is how parameters for your key pair are passed
// to the KeyPairGenerator. For a fun home game, count how many classes in this sample
// start with the phrase "KeyPair".
KeyPairGeneratorSpec spec = new KeyPairGeneratorSpec.Builder(context).setAlias(mAlias).setSubject(new X500Principal("CN=" + mAlias)).setSerialNumber(BigInteger.valueOf(1337)).setStartDate(start.getTime()).setEndDate(end.getTime()).build();
// END_INCLUDE(create_spec)
// BEGIN_INCLUDE(create_keypair)
// Initialize a KeyPair generator using the the intended algorithm (in this example, RSA
// and the KeyStore. This example uses the AndroidKeyStore.
KeyPairGenerator kpGenerator = KeyPairGenerator.getInstance(SecurityConstants.TYPE_RSA, SecurityConstants.KEYSTORE_PROVIDER_ANDROID_KEYSTORE);
kpGenerator.initialize(spec);
KeyPair kp = kpGenerator.generateKeyPair();
Log.d(TAG, "Public Key is: " + kp.getPublic().toString());
// END_INCLUDE(create_keypair)
}
use of javax.security.auth.x500.X500Principal in project platformlayer by platformlayer.
the class ManagedKeystore method ensureIsCompleteCertificateChain.
static void ensureIsCompleteCertificateChain(List<X509Certificate> certificateChain) throws OpsException {
while (true) {
X509Certificate tail = certificateChain.get(certificateChain.size() - 1);
if (Certificates.isSelfSigned(tail)) {
break;
}
X500Principal issuer = tail.getIssuerX500Principal();
X509Certificate issuerCert = findIssuerCertificate(issuer);
if (issuerCert == null) {
throw new OpsException("Cannot find certificate: " + issuer);
}
certificateChain.add(issuerCert);
if (certificateChain.size() > 64) {
throw new OpsException("Likely certificate chain loop detected");
}
}
}
use of javax.security.auth.x500.X500Principal in project robovm by robovm.
the class PKIXCertPathValidatorSpi method engineValidate.
// END android-added
public CertPathValidatorResult engineValidate(CertPath certPath, CertPathParameters params) throws CertPathValidatorException, InvalidAlgorithmParameterException {
if (!(params instanceof PKIXParameters)) {
throw new InvalidAlgorithmParameterException("Parameters must be a " + PKIXParameters.class.getName() + " instance.");
}
ExtendedPKIXParameters paramsPKIX;
if (params instanceof ExtendedPKIXParameters) {
paramsPKIX = (ExtendedPKIXParameters) params;
} else {
paramsPKIX = ExtendedPKIXParameters.getInstance((PKIXParameters) params);
}
if (paramsPKIX.getTrustAnchors() == null) {
throw new InvalidAlgorithmParameterException("trustAnchors is null, this is not allowed for certification path validation.");
}
//
// 6.1.1 - inputs
//
//
// (a)
//
List certs = certPath.getCertificates();
int n = certs.size();
if (certs.isEmpty()) {
throw new CertPathValidatorException("Certification path is empty.", null, certPath, 0);
}
// BEGIN android-added
{
X509Certificate cert = (X509Certificate) certs.get(0);
if (cert != null) {
BigInteger serial = cert.getSerialNumber();
if (blacklist.isSerialNumberBlackListed(serial)) {
// emulate CRL exception message in RFC3280CertPathUtilities.checkCRLs
String message = "Certificate revocation of serial 0x" + serial.toString(16);
System.out.println(message);
AnnotatedException e = new AnnotatedException(message);
throw new CertPathValidatorException(e.getMessage(), e, certPath, 0);
}
}
}
// END android-added
//
// (b)
//
// Date validDate = CertPathValidatorUtilities.getValidDate(paramsPKIX);
//
// (c)
//
Set userInitialPolicySet = paramsPKIX.getInitialPolicies();
//
// (d)
//
TrustAnchor trust;
try {
trust = CertPathValidatorUtilities.findTrustAnchor((X509Certificate) certs.get(certs.size() - 1), paramsPKIX.getTrustAnchors(), paramsPKIX.getSigProvider());
} catch (AnnotatedException e) {
throw new CertPathValidatorException(e.getMessage(), e, certPath, certs.size() - 1);
}
if (trust == null) {
throw new CertPathValidatorException("Trust anchor for certification path not found.", null, certPath, -1);
}
//
// (e), (f), (g) are part of the paramsPKIX object.
//
Iterator certIter;
int index = 0;
int i;
// Certificate for each interation of the validation loop
// Signature information for each iteration of the validation loop
//
// 6.1.2 - setup
//
//
// (a)
//
List[] policyNodes = new ArrayList[n + 1];
for (int j = 0; j < policyNodes.length; j++) {
policyNodes[j] = new ArrayList();
}
Set policySet = new HashSet();
policySet.add(RFC3280CertPathUtilities.ANY_POLICY);
PKIXPolicyNode validPolicyTree = new PKIXPolicyNode(new ArrayList(), 0, policySet, null, new HashSet(), RFC3280CertPathUtilities.ANY_POLICY, false);
policyNodes[0].add(validPolicyTree);
//
// (b) and (c)
//
PKIXNameConstraintValidator nameConstraintValidator = new PKIXNameConstraintValidator();
// (d)
//
int explicitPolicy;
Set acceptablePolicies = new HashSet();
if (paramsPKIX.isExplicitPolicyRequired()) {
explicitPolicy = 0;
} else {
explicitPolicy = n + 1;
}
//
// (e)
//
int inhibitAnyPolicy;
if (paramsPKIX.isAnyPolicyInhibited()) {
inhibitAnyPolicy = 0;
} else {
inhibitAnyPolicy = n + 1;
}
//
// (f)
//
int policyMapping;
if (paramsPKIX.isPolicyMappingInhibited()) {
policyMapping = 0;
} else {
policyMapping = n + 1;
}
//
// (g), (h), (i), (j)
//
PublicKey workingPublicKey;
X500Principal workingIssuerName;
X509Certificate sign = trust.getTrustedCert();
try {
if (sign != null) {
workingIssuerName = CertPathValidatorUtilities.getSubjectPrincipal(sign);
workingPublicKey = sign.getPublicKey();
} else {
workingIssuerName = new X500Principal(trust.getCAName());
workingPublicKey = trust.getCAPublicKey();
}
} catch (IllegalArgumentException ex) {
throw new ExtCertPathValidatorException("Subject of trust anchor could not be (re)encoded.", ex, certPath, -1);
}
AlgorithmIdentifier workingAlgId = null;
try {
workingAlgId = CertPathValidatorUtilities.getAlgorithmIdentifier(workingPublicKey);
} catch (CertPathValidatorException e) {
throw new ExtCertPathValidatorException("Algorithm identifier of public key of trust anchor could not be read.", e, certPath, -1);
}
DERObjectIdentifier workingPublicKeyAlgorithm = workingAlgId.getObjectId();
ASN1Encodable workingPublicKeyParameters = workingAlgId.getParameters();
//
// (k)
//
int maxPathLength = n;
if (paramsPKIX.getTargetConstraints() != null && !paramsPKIX.getTargetConstraints().match((X509Certificate) certs.get(0))) {
throw new ExtCertPathValidatorException("Target certificate in certification path does not match targetConstraints.", null, certPath, 0);
}
//
// initialize CertPathChecker's
//
List pathCheckers = paramsPKIX.getCertPathCheckers();
certIter = pathCheckers.iterator();
while (certIter.hasNext()) {
((PKIXCertPathChecker) certIter.next()).init(false);
}
X509Certificate cert = null;
for (index = certs.size() - 1; index >= 0; index--) {
// BEGIN android-added
if (blacklist.isPublicKeyBlackListed(workingPublicKey)) {
// emulate CRL exception message in RFC3280CertPathUtilities.checkCRLs
String message = "Certificate revocation of public key " + workingPublicKey;
System.out.println(message);
AnnotatedException e = new AnnotatedException(message);
throw new CertPathValidatorException(e.getMessage(), e, certPath, index);
}
// END android-added
// try
// {
//
// i as defined in the algorithm description
//
i = n - index;
//
// set certificate to be checked in this round
// sign and workingPublicKey and workingIssuerName are set
// at the end of the for loop and initialized the
// first time from the TrustAnchor
//
cert = (X509Certificate) certs.get(index);
boolean verificationAlreadyPerformed = (index == certs.size() - 1);
//
// 6.1.3
//
RFC3280CertPathUtilities.processCertA(certPath, paramsPKIX, index, workingPublicKey, verificationAlreadyPerformed, workingIssuerName, sign);
RFC3280CertPathUtilities.processCertBC(certPath, index, nameConstraintValidator);
validPolicyTree = RFC3280CertPathUtilities.processCertD(certPath, index, acceptablePolicies, validPolicyTree, policyNodes, inhibitAnyPolicy);
validPolicyTree = RFC3280CertPathUtilities.processCertE(certPath, index, validPolicyTree);
RFC3280CertPathUtilities.processCertF(certPath, index, validPolicyTree, explicitPolicy);
if (i != n) {
if (cert != null && cert.getVersion() == 1) {
throw new CertPathValidatorException("Version 1 certificates can't be used as CA ones.", null, certPath, index);
}
RFC3280CertPathUtilities.prepareNextCertA(certPath, index);
validPolicyTree = RFC3280CertPathUtilities.prepareCertB(certPath, index, policyNodes, validPolicyTree, policyMapping);
RFC3280CertPathUtilities.prepareNextCertG(certPath, index, nameConstraintValidator);
// (h)
explicitPolicy = RFC3280CertPathUtilities.prepareNextCertH1(certPath, index, explicitPolicy);
policyMapping = RFC3280CertPathUtilities.prepareNextCertH2(certPath, index, policyMapping);
inhibitAnyPolicy = RFC3280CertPathUtilities.prepareNextCertH3(certPath, index, inhibitAnyPolicy);
//
// (i)
//
explicitPolicy = RFC3280CertPathUtilities.prepareNextCertI1(certPath, index, explicitPolicy);
policyMapping = RFC3280CertPathUtilities.prepareNextCertI2(certPath, index, policyMapping);
// (j)
inhibitAnyPolicy = RFC3280CertPathUtilities.prepareNextCertJ(certPath, index, inhibitAnyPolicy);
// (k)
RFC3280CertPathUtilities.prepareNextCertK(certPath, index);
// (l)
maxPathLength = RFC3280CertPathUtilities.prepareNextCertL(certPath, index, maxPathLength);
// (m)
maxPathLength = RFC3280CertPathUtilities.prepareNextCertM(certPath, index, maxPathLength);
// (n)
RFC3280CertPathUtilities.prepareNextCertN(certPath, index);
Set criticalExtensions = cert.getCriticalExtensionOIDs();
if (criticalExtensions != null) {
criticalExtensions = new HashSet(criticalExtensions);
// these extensions are handled by the algorithm
criticalExtensions.remove(RFC3280CertPathUtilities.KEY_USAGE);
criticalExtensions.remove(RFC3280CertPathUtilities.CERTIFICATE_POLICIES);
criticalExtensions.remove(RFC3280CertPathUtilities.POLICY_MAPPINGS);
criticalExtensions.remove(RFC3280CertPathUtilities.INHIBIT_ANY_POLICY);
criticalExtensions.remove(RFC3280CertPathUtilities.ISSUING_DISTRIBUTION_POINT);
criticalExtensions.remove(RFC3280CertPathUtilities.DELTA_CRL_INDICATOR);
criticalExtensions.remove(RFC3280CertPathUtilities.POLICY_CONSTRAINTS);
criticalExtensions.remove(RFC3280CertPathUtilities.BASIC_CONSTRAINTS);
criticalExtensions.remove(RFC3280CertPathUtilities.SUBJECT_ALTERNATIVE_NAME);
criticalExtensions.remove(RFC3280CertPathUtilities.NAME_CONSTRAINTS);
} else {
criticalExtensions = new HashSet();
}
// (o)
RFC3280CertPathUtilities.prepareNextCertO(certPath, index, criticalExtensions, pathCheckers);
// set signing certificate for next round
sign = cert;
// (c)
workingIssuerName = CertPathValidatorUtilities.getSubjectPrincipal(sign);
// (d)
try {
workingPublicKey = CertPathValidatorUtilities.getNextWorkingKey(certPath.getCertificates(), index);
} catch (CertPathValidatorException e) {
throw new CertPathValidatorException("Next working key could not be retrieved.", e, certPath, index);
}
workingAlgId = CertPathValidatorUtilities.getAlgorithmIdentifier(workingPublicKey);
// (f)
workingPublicKeyAlgorithm = workingAlgId.getObjectId();
// (e)
workingPublicKeyParameters = workingAlgId.getParameters();
}
}
//
// 6.1.5 Wrap-up procedure
//
explicitPolicy = RFC3280CertPathUtilities.wrapupCertA(explicitPolicy, cert);
explicitPolicy = RFC3280CertPathUtilities.wrapupCertB(certPath, index + 1, explicitPolicy);
//
// (c) (d) and (e) are already done
//
//
// (f)
//
Set criticalExtensions = cert.getCriticalExtensionOIDs();
if (criticalExtensions != null) {
criticalExtensions = new HashSet(criticalExtensions);
// these extensions are handled by the algorithm
criticalExtensions.remove(RFC3280CertPathUtilities.KEY_USAGE);
criticalExtensions.remove(RFC3280CertPathUtilities.CERTIFICATE_POLICIES);
criticalExtensions.remove(RFC3280CertPathUtilities.POLICY_MAPPINGS);
criticalExtensions.remove(RFC3280CertPathUtilities.INHIBIT_ANY_POLICY);
criticalExtensions.remove(RFC3280CertPathUtilities.ISSUING_DISTRIBUTION_POINT);
criticalExtensions.remove(RFC3280CertPathUtilities.DELTA_CRL_INDICATOR);
criticalExtensions.remove(RFC3280CertPathUtilities.POLICY_CONSTRAINTS);
criticalExtensions.remove(RFC3280CertPathUtilities.BASIC_CONSTRAINTS);
criticalExtensions.remove(RFC3280CertPathUtilities.SUBJECT_ALTERNATIVE_NAME);
criticalExtensions.remove(RFC3280CertPathUtilities.NAME_CONSTRAINTS);
criticalExtensions.remove(RFC3280CertPathUtilities.CRL_DISTRIBUTION_POINTS);
} else {
criticalExtensions = new HashSet();
}
RFC3280CertPathUtilities.wrapupCertF(certPath, index + 1, pathCheckers, criticalExtensions);
PKIXPolicyNode intersection = RFC3280CertPathUtilities.wrapupCertG(certPath, paramsPKIX, userInitialPolicySet, index + 1, policyNodes, validPolicyTree, acceptablePolicies);
if ((explicitPolicy > 0) || (intersection != null)) {
return new PKIXCertPathValidatorResult(trust, intersection, cert.getPublicKey());
}
throw new CertPathValidatorException("Path processing failed on policy.", null, certPath, index);
}
Aggregations