use of sun.security.x509.X500Name in project pac4j by pac4j.
the class SAML2ClientConfiguration method createKeystore.
private void createKeystore() {
try {
if (CommonHelper.isBlank(this.keyStoreAlias)) {
this.keyStoreAlias = getClass().getSimpleName();
LOGGER.warn("Using keystore alias {}", this.keyStoreAlias);
}
if (CommonHelper.isBlank(this.keyStoreType)) {
this.keyStoreType = KeyStore.getDefaultType();
LOGGER.warn("Using keystore type {}", this.keyStoreType);
}
final KeyStore ks = KeyStore.getInstance(this.keyStoreType);
final char[] password = this.keystorePassword.toCharArray();
ks.load(null, password);
final KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
kpg.initialize(2048);
final KeyPair kp = kpg.genKeyPair();
final String sigAlgName = "SHA1WithRSA";
final AlgorithmIdentifier sigAlgID = new AlgorithmIdentifier(PKCSObjectIdentifiers.sha1WithRSAEncryption, DERNull.INSTANCE);
final String dn = InetAddress.getLocalHost().getHostName();
final PrivateKey signingKey = kp.getPrivate();
final X509Certificate certificate = createSelfSignedCert(new X500Name("CN=" + dn), sigAlgName, sigAlgID, kp);
final char[] keyPassword = this.privateKeyPassword.toCharArray();
ks.setKeyEntry(this.keyStoreAlias, signingKey, keyPassword, new Certificate[] { certificate });
try (final FileOutputStream fos = new FileOutputStream(this.keystoreResource.getFile().getCanonicalPath())) {
ks.store(fos, password);
fos.flush();
}
LOGGER.info("Created keystore {} with key alias {} ", keystoreResource.getFile().getCanonicalPath(), ks.aliases().nextElement());
} catch (final Exception e) {
throw new SAMLException("Could not create keystore", e);
}
}
use of sun.security.x509.X500Name in project xipki by xipki.
the class CertStoreQueryExecutor method listCertificates.
List<CertListInfo> listCertificates(NameId ca, X500Name subjectPattern, Date validFrom, Date validTo, CertListOrderBy orderBy, int numEntries) throws DataAccessException, OperationException {
ParamUtil.requireNonNull("ca", ca);
ParamUtil.requireMin("numEntries", numEntries, 1);
StringBuilder sb = new StringBuilder(200);
sb.append("SN,NBEFORE,NAFTER,SUBJECT FROM CERT WHERE CA_ID=?");
// .append(caId)
Integer idxNotBefore = null;
Integer idxNotAfter = null;
Integer idxSubject = null;
int idx = 2;
if (validFrom != null) {
idxNotBefore = idx++;
sb.append(" AND NBEFORE<?");
}
if (validTo != null) {
idxNotAfter = idx++;
sb.append(" AND NAFTER>?");
}
String subjectLike = null;
if (subjectPattern != null) {
idxSubject = idx++;
sb.append(" AND SUBJECT LIKE ?");
StringBuilder buffer = new StringBuilder(100);
buffer.append("%");
RDN[] rdns = subjectPattern.getRDNs();
for (int i = 0; i < rdns.length; i++) {
X500Name rdnName = new X500Name(new RDN[] { rdns[i] });
String rdnStr = X509Util.getRfc4519Name(rdnName);
if (rdnStr.indexOf('%') != -1) {
throw new OperationException(ErrorCode.BAD_REQUEST, "the character '%' is not allowed in subjectPattern");
}
if (rdnStr.indexOf('*') != -1) {
rdnStr = rdnStr.replace('*', '%');
}
buffer.append(rdnStr);
buffer.append("%");
}
subjectLike = buffer.toString();
}
String sortByStr = null;
if (orderBy != null) {
switch(orderBy) {
case NOT_BEFORE:
sortByStr = "NBEFORE";
break;
case NOT_BEFORE_DESC:
sortByStr = "NBEFORE DESC";
break;
case NOT_AFTER:
sortByStr = "NAFTER";
break;
case NOT_AFTER_DESC:
sortByStr = "NAFTER DESC";
break;
case SUBJECT:
sortByStr = "SUBJECT";
break;
case SUBJECT_DESC:
sortByStr = "SUBJECT DESC";
break;
default:
throw new RuntimeException("unknown CertListOrderBy " + orderBy);
}
}
final String sql = datasource.buildSelectFirstSql(numEntries, sortByStr, sb.toString());
ResultSet rs = null;
PreparedStatement ps = borrowPreparedStatement(sql);
try {
ps.setInt(1, ca.getId());
if (idxNotBefore != null) {
long time = validFrom.getTime() / 1000;
ps.setLong(idxNotBefore, time - 1);
}
if (idxNotAfter != null) {
long time = validTo.getTime() / 1000;
ps.setLong(idxNotAfter, time);
}
if (idxSubject != null) {
ps.setString(idxSubject, subjectLike);
}
rs = ps.executeQuery();
List<CertListInfo> ret = new LinkedList<>();
while (rs.next()) {
String snStr = rs.getString("SN");
BigInteger sn = new BigInteger(snStr, 16);
Date notBefore = new Date(rs.getLong("NBEFORE") * 1000);
Date notAfter = new Date(rs.getLong("NAFTER") * 1000);
String subject = rs.getString("SUBJECT");
CertListInfo info = new CertListInfo(sn, subject, notBefore, notAfter);
ret.add(info);
}
return ret;
} catch (SQLException ex) {
throw datasource.translate(sql, ex);
} finally {
releaseDbResources(ps, rs);
}
}
use of sun.security.x509.X500Name in project xipki by xipki.
the class CertStoreQueryExecutor method getLatestSerialNumber.
// method isHealthy
String getLatestSerialNumber(X500Name nameWithSn) throws OperationException {
RDN[] rdns1 = nameWithSn.getRDNs();
RDN[] rdns2 = new RDN[rdns1.length];
for (int i = 0; i < rdns1.length; i++) {
RDN rdn = rdns1[i];
rdns2[i] = rdn.getFirst().getType().equals(ObjectIdentifiers.DN_SERIALNUMBER) ? new RDN(ObjectIdentifiers.DN_SERIALNUMBER, new DERPrintableString("%")) : rdn;
}
String namePattern = X509Util.getRfc4519Name(new X500Name(rdns2));
final String sql = sqls.sqlLatestSerialForSubjectLike;
ResultSet rs = null;
PreparedStatement ps;
try {
ps = borrowPreparedStatement(sql);
} catch (DataAccessException ex) {
throw new OperationException(ErrorCode.DATABASE_FAILURE, ex.getMessage());
}
String subjectStr;
try {
ps.setString(1, namePattern);
rs = ps.executeQuery();
if (!rs.next()) {
return null;
}
subjectStr = rs.getString("SUBJECT");
} catch (SQLException ex) {
throw new OperationException(ErrorCode.DATABASE_FAILURE, ex.getMessage());
} finally {
releaseDbResources(ps, rs);
}
X500Name lastName = new X500Name(subjectStr);
RDN[] rdns = lastName.getRDNs(ObjectIdentifiers.DN_SERIALNUMBER);
if (rdns == null || rdns.length == 0) {
return null;
}
return X509Util.rdnValueToString(rdns[0].getFirst().getValue());
}
use of sun.security.x509.X500Name in project xipki by xipki.
the class CmpRequestor method verifyProtection.
private ProtectionVerificationResult verifyProtection(String tid, GeneralPKIMessage pkiMessage) throws CMPException, InvalidKeyException, OperatorCreationException {
ProtectedPKIMessage protectedMsg = new ProtectedPKIMessage(pkiMessage);
if (protectedMsg.hasPasswordBasedMacProtection()) {
LOG.warn("NOT_SIGNAUTRE_BASED: {}", pkiMessage.getHeader().getProtectionAlg().getAlgorithm().getId());
return new ProtectionVerificationResult(null, ProtectionResult.NOT_SIGNATURE_BASED);
}
PKIHeader header = protectedMsg.getHeader();
if (recipientName != null) {
boolean authorizedResponder = true;
if (header.getSender().getTagNo() != GeneralName.directoryName) {
authorizedResponder = false;
} else {
X500Name msgSender = X500Name.getInstance(header.getSender().getName());
authorizedResponder = recipientName.equals(msgSender);
}
if (!authorizedResponder) {
LOG.warn("tid={}: not authorized responder '{}'", tid, header.getSender());
return new ProtectionVerificationResult(null, ProtectionResult.SENDER_NOT_AUTHORIZED);
}
}
AlgorithmIdentifier protectionAlgo = protectedMsg.getHeader().getProtectionAlg();
if (!responder.getSigAlgoValidator().isAlgorithmPermitted(protectionAlgo)) {
String algoName;
try {
algoName = AlgorithmUtil.getSignatureAlgoName(protectionAlgo);
} catch (NoSuchAlgorithmException ex) {
algoName = protectionAlgo.getAlgorithm().getId();
}
LOG.warn("tid={}: response protected by untrusted protection algorithm '{}'", tid, algoName);
return new ProtectionVerificationResult(null, ProtectionResult.INVALID);
}
X509Certificate cert = responder.getCert();
ContentVerifierProvider verifierProvider = securityFactory.getContentVerifierProvider(cert);
if (verifierProvider == null) {
LOG.warn("tid={}: not authorized responder '{}'", tid, header.getSender());
return new ProtectionVerificationResult(cert, ProtectionResult.SENDER_NOT_AUTHORIZED);
}
boolean signatureValid = protectedMsg.verify(verifierProvider);
ProtectionResult protRes = signatureValid ? ProtectionResult.VALID : ProtectionResult.INVALID;
return new ProtectionVerificationResult(cert, protRes);
}
use of sun.security.x509.X500Name in project xipki by xipki.
the class CaClientImpl method removeCerts.
@Override
public Map<String, CertIdOrError> removeCerts(UnrevokeOrRemoveCertRequest request, RequestResponseDebug debug) throws CaClientException, PkiErrorException {
ParamUtil.requireNonNull("request", request);
init0(false);
List<UnrevokeOrRemoveCertEntry> requestEntries = request.getRequestEntries();
if (CollectionUtil.isEmpty(requestEntries)) {
return Collections.emptyMap();
}
X500Name issuer = requestEntries.get(0).getIssuer();
for (int i = 1; i < requestEntries.size(); i++) {
if (!issuer.equals(requestEntries.get(i).getIssuer())) {
throw new PkiErrorException(PKIStatus.REJECTION, PKIFailureInfo.badRequest, "removing certificates issued by more than one CA is not allowed");
}
}
final String caName = getCaNameByIssuer(issuer);
X509CmpRequestor cmpRequestor = casMap.get(caName).getRequestor();
RevokeCertResultType result;
try {
result = cmpRequestor.removeCertificate(request, debug);
} catch (CmpRequestorException ex) {
throw new CaClientException(ex.getMessage(), ex);
}
return parseRevokeCertResult(result);
}
Aggregations