use of javax.security.auth.x500.X500Principal in project cas by apereo.
the class ThresholdExpiredCRLRevocationPolicyTests method getTestParameters.
/**
* Gets the unit test parameters.
*
* @return Test parameter data.
* @throws Exception if there is an exception getting the test parameters.
*/
@Parameters
public static Collection<Object[]> getTestParameters() throws Exception {
final Collection<Object[]> params = new ArrayList<>();
final ZonedDateTime now = ZonedDateTime.now(ZoneOffset.UTC);
final ZonedDateTime twoHoursAgo = now.minusHours(2);
final ZonedDateTime oneHourAgo = now.minusHours(1);
final ZonedDateTime halfHourAgo = now.minusMinutes(30);
final X500Principal issuer = new X500Principal("CN=CAS");
// Test case #1
// Expect expired for zero leniency on CRL expiring 1ms ago
final ThresholdExpiredCRLRevocationPolicy zeroThreshold = new ThresholdExpiredCRLRevocationPolicy(0);
params.add(new Object[] { zeroThreshold, new MockX509CRL(issuer, DateTimeUtils.dateOf(oneHourAgo), DateTimeUtils.dateOf(now.minusSeconds(1))), new ExpiredCRLException("CN=CAS", ZonedDateTime.now(ZoneOffset.UTC)) });
// Test case #2
// Expect expired for 1h leniency on CRL expired 1 hour 1ms ago
final ThresholdExpiredCRLRevocationPolicy oneHourThreshold = new ThresholdExpiredCRLRevocationPolicy(3600);
params.add(new Object[] { oneHourThreshold, new MockX509CRL(issuer, DateTimeUtils.dateOf(twoHoursAgo), DateTimeUtils.dateOf(oneHourAgo.minusSeconds(1))), new ExpiredCRLException("CN=CAS", ZonedDateTime.now(ZoneOffset.UTC)) });
// Test case #3
// Expect valid for 1h leniency on CRL expired 30m ago
params.add(new Object[] { oneHourThreshold, new MockX509CRL(issuer, DateTimeUtils.dateOf(twoHoursAgo), DateTimeUtils.dateOf(halfHourAgo)), null });
return params;
}
use of javax.security.auth.x500.X500Principal in project cas by apereo.
the class ResourceCRLRevocationChecker method getCRLs.
@Override
protected Collection<X509CRL> getCRLs(final X509Certificate cert) {
final X500Principal principal = cert.getIssuerX500Principal();
if (this.crlIssuerMap.containsKey(principal)) {
return Collections.singleton(this.crlIssuerMap.get(principal));
}
LOGGER.warn("Could not locate CRL for issuer principal [{}]", principal);
return Collections.emptyList();
}
use of javax.security.auth.x500.X500Principal in project gocd by gocd.
the class X509AuthoritiesPopulator method getUserDetails.
public UserDetails getUserDetails(X509Certificate clientCert) throws AuthenticationException {
X500Principal principal = clientCert.getSubjectX500Principal();
Matcher cnMatcher = CN_PATTERN.matcher(principal.getName());
Matcher ouMatcher = OU_PATTERN.matcher(principal.getName());
if (cnMatcher.find() && ouMatcher.find()) {
GrantedAuthorityImpl agentAuthority = new GrantedAuthorityImpl(role);
return new User(cnMatcher.group(1), "", true, true, true, true, new GrantedAuthority[] { agentAuthority });
}
throw new BadCredentialsException("Couldn't find CN and/or OU for the certificate");
}
use of javax.security.auth.x500.X500Principal in project j2objc by google.
the class X509CRLImpl method parse.
/*
* Parses an X.509 CRL, should be used only by constructors.
*/
private void parse(DerValue val) throws CRLException, IOException {
// check if can over write the certificate
if (readOnly)
throw new CRLException("cannot over-write existing CRL");
if (val.getData() == null || val.tag != DerValue.tag_Sequence)
throw new CRLException("Invalid DER-encoded CRL data");
signedCRL = val.toByteArray();
DerValue[] seq = new DerValue[3];
seq[0] = val.data.getDerValue();
seq[1] = val.data.getDerValue();
seq[2] = val.data.getDerValue();
if (val.data.available() != 0)
throw new CRLException("signed overrun, bytes = " + val.data.available());
if (seq[0].tag != DerValue.tag_Sequence)
throw new CRLException("signed CRL fields invalid");
sigAlgId = AlgorithmId.parse(seq[1]);
signature = seq[2].getBitString();
if (seq[1].data.available() != 0)
throw new CRLException("AlgorithmId field overrun");
if (seq[2].data.available() != 0)
throw new CRLException("Signature field overrun");
// the tbsCertsList
tbsCertList = seq[0].toByteArray();
// parse the information
DerInputStream derStrm = seq[0].data;
DerValue tmp;
byte nextByte;
// version (optional if v1)
// by default, version = v1 == 0
version = 0;
nextByte = (byte) derStrm.peekByte();
if (nextByte == DerValue.tag_Integer) {
version = derStrm.getInteger();
if (// i.e. v2
version != 1)
throw new CRLException("Invalid version");
}
tmp = derStrm.getDerValue();
// signature
AlgorithmId tmpId = AlgorithmId.parse(tmp);
// the "inner" and "outer" signature algorithms must match
if (!tmpId.equals(sigAlgId))
throw new CRLException("Signature algorithm mismatch");
infoSigAlgId = tmpId;
// issuer
issuer = new X500Name(derStrm);
if (issuer.isEmpty()) {
throw new CRLException("Empty issuer DN not allowed in X509CRLs");
}
// thisUpdate
// check if UTCTime encoded or GeneralizedTime
nextByte = (byte) derStrm.peekByte();
if (nextByte == DerValue.tag_UtcTime) {
thisUpdate = derStrm.getUTCTime();
} else if (nextByte == DerValue.tag_GeneralizedTime) {
thisUpdate = derStrm.getGeneralizedTime();
} else {
throw new CRLException("Invalid encoding for thisUpdate" + " (tag=" + nextByte + ")");
}
if (derStrm.available() == 0)
// done parsing no more optional fields present
return;
// nextUpdate (optional)
nextByte = (byte) derStrm.peekByte();
if (nextByte == DerValue.tag_UtcTime) {
nextUpdate = derStrm.getUTCTime();
} else if (nextByte == DerValue.tag_GeneralizedTime) {
nextUpdate = derStrm.getGeneralizedTime();
}
if (derStrm.available() == 0)
// done parsing no more optional fields present
return;
// revokedCertificates (optional)
nextByte = (byte) derStrm.peekByte();
if ((nextByte == DerValue.tag_SequenceOf) && (!((nextByte & 0x0c0) == 0x080))) {
DerValue[] badCerts = derStrm.getSequence(4);
X500Principal crlIssuer = getIssuerX500Principal();
X500Principal badCertIssuer = crlIssuer;
for (int i = 0; i < badCerts.length; i++) {
X509CRLEntryImpl entry = new X509CRLEntryImpl(badCerts[i]);
badCertIssuer = getCertIssuer(entry, badCertIssuer);
entry.setCertificateIssuer(crlIssuer, badCertIssuer);
X509IssuerSerial issuerSerial = new X509IssuerSerial(badCertIssuer, entry.getSerialNumber());
revokedMap.put(issuerSerial, entry);
revokedList.add(entry);
}
}
if (derStrm.available() == 0)
// done parsing no extensions
return;
// crlExtensions (optional)
tmp = derStrm.getDerValue();
if (tmp.isConstructed() && tmp.isContextSpecific((byte) 0)) {
extensions = new CRLExtensions(tmp.data);
}
readOnly = true;
}
use of javax.security.auth.x500.X500Principal in project j2objc by google.
the class JarUtils method verifySignature.
/**
* This method handle all the work with PKCS7, ASN1 encoding, signature verifying,
* and certification path building.
* See also PKCS #7: Cryptographic Message Syntax Standard:
* http://www.ietf.org/rfc/rfc2315.txt
* @param signature - the input stream of signature file to be verified
* @param signatureBlock - the input stream of corresponding signature block file
* @return array of certificates used to verify the signature file
* @throws IOException - if some errors occurs during reading from the stream
* @throws GeneralSecurityException - if signature verification process fails
*/
public static Certificate[] verifySignature(InputStream signature, InputStream signatureBlock) throws IOException, GeneralSecurityException {
BerInputStream bis = new BerInputStream(signatureBlock);
ContentInfo info = (ContentInfo) ContentInfo.ASN1.decode(bis);
SignedData signedData = info.getSignedData();
if (signedData == null) {
throw new IOException("No SignedData found");
}
Collection<org.apache.harmony.security.x509.Certificate> encCerts = signedData.getCertificates();
if (encCerts.isEmpty()) {
return null;
}
X509Certificate[] certs = new X509Certificate[encCerts.size()];
CertificateFactory cf = CertificateFactory.getInstance("X.509");
int i = 0;
for (org.apache.harmony.security.x509.Certificate encCert : encCerts) {
final byte[] encoded = encCert.getEncoded();
final InputStream is = new ByteArrayInputStream(encoded);
certs[i++] = new VerbatimX509Certificate((X509Certificate) cf.generateCertificate(is), encoded);
}
List<SignerInfo> sigInfos = signedData.getSignerInfos();
SignerInfo sigInfo;
if (!sigInfos.isEmpty()) {
sigInfo = sigInfos.get(0);
} else {
return null;
}
// Issuer
X500Principal issuer = sigInfo.getIssuer();
// Certificate serial number
BigInteger snum = sigInfo.getSerialNumber();
// Locate the certificate
int issuerSertIndex = 0;
for (i = 0; i < certs.length; i++) {
if (issuer.equals(certs[i].getIssuerDN()) && snum.equals(certs[i].getSerialNumber())) {
issuerSertIndex = i;
break;
}
}
if (i == certs.length) {
// No issuer certificate found
return null;
}
if (certs[issuerSertIndex].hasUnsupportedCriticalExtension()) {
throw new SecurityException("Can not recognize a critical extension");
}
// Get Signature instance
final String daOid = sigInfo.getDigestAlgorithm();
final String daName = sigInfo.getDigestAlgorithmName();
final String deaOid = sigInfo.getDigestEncryptionAlgorithm();
final String deaName = sigInfo.getDigestEncryptionAlgorithmName();
String alg = null;
Signature sig = null;
if (daOid != null && deaOid != null) {
alg = daOid + "with" + deaOid;
try {
sig = Signature.getInstance(alg);
} catch (NoSuchAlgorithmException e) {
}
// Try to convert to names instead of OID.
if (sig == null && daName != null && deaName != null) {
alg = daName + "with" + deaName;
try {
sig = Signature.getInstance(alg);
} catch (NoSuchAlgorithmException e) {
}
}
}
if (sig == null && deaOid != null) {
alg = deaOid;
try {
sig = Signature.getInstance(alg);
} catch (NoSuchAlgorithmException e) {
}
if (sig == null) {
alg = deaName;
try {
sig = Signature.getInstance(alg);
} catch (NoSuchAlgorithmException e) {
}
}
}
// We couldn't find a valid Signature type.
if (sig == null) {
return null;
}
sig.initVerify(certs[issuerSertIndex]);
// If the authenticatedAttributes field of SignerInfo contains more than zero attributes,
// compute the message digest on the ASN.1 DER encoding of the Attributes value.
// Otherwise, compute the message digest on the data.
List<AttributeTypeAndValue> atr = sigInfo.getAuthenticatedAttributes();
byte[] sfBytes = new byte[signature.available()];
signature.read(sfBytes);
if (atr == null) {
sig.update(sfBytes);
} else {
sig.update(sigInfo.getEncodedAuthenticatedAttributes());
// If the authenticatedAttributes field contains the message-digest attribute,
// verify that it equals the computed digest of the signature file
byte[] existingDigest = null;
for (AttributeTypeAndValue a : atr) {
if (Arrays.equals(a.getType().getOid(), MESSAGE_DIGEST_OID)) {
if (existingDigest != null) {
throw new SecurityException("Too many MessageDigest attributes");
}
Collection<?> entries = a.getValue().getValues(ASN1OctetString.getInstance());
if (entries.size() != 1) {
throw new SecurityException("Too many values for MessageDigest attribute");
}
existingDigest = (byte[]) entries.iterator().next();
}
}
// must have a message-digest attribute.
if (existingDigest == null) {
throw new SecurityException("Missing MessageDigest in Authenticated Attributes");
}
MessageDigest md = null;
if (daOid != null) {
md = MessageDigest.getInstance(daOid);
}
if (md == null && daName != null) {
md = MessageDigest.getInstance(daName);
}
if (md == null) {
return null;
}
byte[] computedDigest = md.digest(sfBytes);
if (!Arrays.equals(existingDigest, computedDigest)) {
throw new SecurityException("Incorrect MD");
}
}
if (!sig.verify(sigInfo.getEncryptedDigest())) {
throw new SecurityException("Incorrect signature");
}
return createChain(certs[issuerSertIndex], certs);
}
Aggregations