use of sun.security.x509.X500Name in project ariADDna by StnetixDevTeam.
the class CertFactory method getNewCertificate.
public File getNewCertificate(String alias) throws KeyStoreException {
KeyPairGenerator keyPairGenerator = null;
try {
keyPairGenerator = KeyPairGenerator.getInstance(CRYPTO_ALGORITHM_RSA);
keyPairGenerator.initialize(CERTIFICATE_SIZE);
KeyPair keyPair = keyPairGenerator.generateKeyPair();
PrivateKey privateKey = keyPair.getPrivate();
X509CertInfo certInfo = new X509CertInfo();
CertificateValidity interval = new CertificateValidity(FROM, TO);
BigInteger sn = new BigInteger(64, new SecureRandom());
X500Name owner = new X500Name(SUBJECT_CN + alias + ", " + SUBJECT_L_C);
certInfo.set(X509CertInfo.VALIDITY, interval);
certInfo.set(X509CertInfo.SERIAL_NUMBER, new CertificateSerialNumber(sn));
certInfo.set(X509CertInfo.SUBJECT, owner);
certInfo.set(X509CertInfo.ISSUER, owner);
certInfo.set(X509CertInfo.KEY, new CertificateX509Key(keyPair.getPublic()));
certInfo.set(X509CertInfo.VERSION, new CertificateVersion(CertificateVersion.V3));
AlgorithmId algorithm = new AlgorithmId(AlgorithmId.md2WithRSAEncryption_oid);
certInfo.set(X509CertInfo.ALGORITHM_ID, new CertificateAlgorithmId(algorithm));
X509CertImpl cert = new X509CertImpl(certInfo);
cert.sign(privateKey, CRYPTO_ALGORITHM_SHA1RSA);
algorithm = (AlgorithmId) cert.get(X509CertImpl.SIG_ALG);
certInfo.set(CertificateAlgorithmId.NAME + "." + CertificateAlgorithmId.ALGORITHM, algorithm);
cert = new X509CertImpl(certInfo);
cert.sign(privateKey, CRYPTO_ALGORITHM_SHA1RSA);
File certFile = new File(alias + ".cer");
if (certFile.createNewFile()) {
FileOutputStream fos = new FileOutputStream(certFile);
fos.write(cert.getEncoded());
fos.close();
}
LOGGER.info("Certificate generated with filename {}", certFile.getAbsolutePath());
CertificateDTO storedCert = persistHelper.storeCertificete(new CertificateDTO(alias, true));
LOGGER.info("Certificate stored id DB with id {}", storedCert.getId());
return certFile;
} catch (Exception e) {
LOGGER.error("Exception: ", e);
throw new KeyStoreException("Caused by: ", e);
}
}
use of sun.security.x509.X500Name in project xipki by xipki.
the class BaseX509Certprofile method getSubject.
@Override
public SubjectInfo getSubject(X500Name requestedSubject) throws CertprofileException, BadCertTemplateException {
ParamUtil.requireNonNull("requestedSubject", requestedSubject);
verifySubjectDnOccurence(requestedSubject);
RDN[] requstedRdns = requestedSubject.getRDNs();
SubjectControl scontrol = getSubjectControl();
List<RDN> rdns = new LinkedList<>();
for (ASN1ObjectIdentifier type : scontrol.getTypes()) {
RdnControl control = scontrol.getControl(type);
if (control == null) {
continue;
}
RDN[] thisRdns = getRdns(requstedRdns, type);
if (thisRdns == null) {
continue;
}
int len = thisRdns.length;
if (len == 0) {
continue;
}
if (ObjectIdentifiers.DN_EmailAddress.equals(type)) {
throw new BadCertTemplateException("emailAddress is not allowed");
}
if (len == 1) {
ASN1Encodable rdnValue = thisRdns[0].getFirst().getValue();
RDN rdn;
if (ObjectIdentifiers.DN_DATE_OF_BIRTH.equals(type)) {
rdn = createDateOfBirthRdn(type, rdnValue);
} else if (ObjectIdentifiers.DN_POSTAL_ADDRESS.equals(type)) {
rdn = createPostalAddressRdn(type, rdnValue, control, 0);
} else {
String value = X509Util.rdnValueToString(rdnValue);
rdn = createSubjectRdn(value, type, control, 0);
}
if (rdn != null) {
rdns.add(rdn);
}
} else {
if (ObjectIdentifiers.DN_DATE_OF_BIRTH.equals(type)) {
for (int i = 0; i < len; i++) {
RDN rdn = createDateOfBirthRdn(type, thisRdns[i].getFirst().getValue());
rdns.add(rdn);
}
} else if (ObjectIdentifiers.DN_POSTAL_ADDRESS.equals(type)) {
for (int i = 0; i < len; i++) {
RDN rdn = createPostalAddressRdn(type, thisRdns[i].getFirst().getValue(), control, i);
rdns.add(rdn);
}
} else {
String[] values = new String[len];
for (int i = 0; i < len; i++) {
values[i] = X509Util.rdnValueToString(thisRdns[i].getFirst().getValue());
}
values = sortRdns(control, values);
int idx = 0;
for (String value : values) {
rdns.add(createSubjectRdn(value, type, control, idx++));
}
}
// if
}
// if
}
// for
Set<String> subjectDnGroups = scontrol.getGroups();
if (CollectionUtil.isNonEmpty(subjectDnGroups)) {
Set<String> consideredGroups = new HashSet<>();
final int n = rdns.size();
List<RDN> newRdns = new ArrayList<>(rdns.size());
for (int i = 0; i < n; i++) {
RDN rdn = rdns.get(i);
ASN1ObjectIdentifier type = rdn.getFirst().getType();
String group = scontrol.getGroup(type);
if (group == null) {
newRdns.add(rdn);
} else if (!consideredGroups.contains(group)) {
List<AttributeTypeAndValue> atvs = new LinkedList<>();
atvs.add(rdn.getFirst());
for (int j = i + 1; j < n; j++) {
RDN rdn2 = rdns.get(j);
ASN1ObjectIdentifier type2 = rdn2.getFirst().getType();
String group2 = scontrol.getGroup(type2);
if (group.equals(group2)) {
atvs.add(rdn2.getFirst());
}
}
newRdns.add(new RDN(atvs.toArray(new AttributeTypeAndValue[0])));
consideredGroups.add(group);
}
}
// for
rdns = newRdns;
}
// if
X500Name grantedSubject = new X500Name(rdns.toArray(new RDN[0]));
return new SubjectInfo(grantedSubject, null);
}
use of sun.security.x509.X500Name in project xipki by xipki.
the class X509Util method createGeneralName.
/**
* Creates {@link GeneralName} from the tagged value.
* @param taggedValue [tag]value, and the value for tags otherName and ediPartyName is
* type=value.
* @return the created {@link GeneralName}
* @throws BadInputException
* if the {@code taggedValue} is invalid.
*/
public static GeneralName createGeneralName(String taggedValue) throws BadInputException {
ParamUtil.requireNonBlank("taggedValue", taggedValue);
int tag = -1;
String value = null;
if (taggedValue.charAt(0) == '[') {
int idx = taggedValue.indexOf(']', 1);
if (idx > 1 && idx < taggedValue.length() - 1) {
String tagS = taggedValue.substring(1, idx);
try {
tag = Integer.parseInt(tagS);
value = taggedValue.substring(idx + 1);
} catch (NumberFormatException ex) {
throw new BadInputException("invalid tag '" + tagS + "'");
}
}
}
if (tag == -1) {
throw new BadInputException("invalid taggedValue " + taggedValue);
}
switch(tag) {
case GeneralName.otherName:
if (value == null) {
throw new BadInputException("invalid otherName: no value specified");
}
int idxSep = value.indexOf("=");
if (idxSep == -1 || idxSep == 0 || idxSep == value.length() - 1) {
throw new BadInputException("invalid otherName " + value);
}
String otherTypeOid = value.substring(0, idxSep);
ASN1ObjectIdentifier type = new ASN1ObjectIdentifier(otherTypeOid);
String otherValue = value.substring(idxSep + 1);
ASN1EncodableVector vector = new ASN1EncodableVector();
vector.add(type);
vector.add(new DERTaggedObject(true, 0, new DERUTF8String(otherValue)));
DERSequence seq = new DERSequence(vector);
return new GeneralName(GeneralName.otherName, seq);
case GeneralName.rfc822Name:
return new GeneralName(tag, value);
case GeneralName.dNSName:
return new GeneralName(tag, value);
case GeneralName.directoryName:
X500Name x500Name = reverse(new X500Name(value));
return new GeneralName(GeneralName.directoryName, x500Name);
case GeneralName.ediPartyName:
if (value == null) {
throw new BadInputException("invalid ediPartyName: no value specified");
}
idxSep = value.indexOf("=");
if (idxSep == -1 || idxSep == value.length() - 1) {
throw new BadInputException("invalid ediPartyName " + value);
}
String nameAssigner = (idxSep == 0) ? null : value.substring(0, idxSep);
String partyName = value.substring(idxSep + 1);
vector = new ASN1EncodableVector();
if (nameAssigner != null) {
vector.add(new DERTaggedObject(false, 0, new DirectoryString(nameAssigner)));
}
vector.add(new DERTaggedObject(false, 1, new DirectoryString(partyName)));
seq = new DERSequence(vector);
return new GeneralName(GeneralName.ediPartyName, seq);
case GeneralName.uniformResourceIdentifier:
return new GeneralName(tag, value);
case GeneralName.iPAddress:
return new GeneralName(tag, value);
case GeneralName.registeredID:
return new GeneralName(tag, value);
default:
throw new RuntimeException("unsupported tag " + tag);
}
// end switch (tag)
}
use of sun.security.x509.X500Name in project xipki by xipki.
the class ScepClientExample method main.
public static void main(String[] args) {
try {
X509Certificate caCert = ScepUtil.parseCert(ScepUtil.read(new FileInputStream(expandPath(CA_CERT_FILE))));
CaIdentifier tmpCaId = new CaIdentifier(CA_URL, null);
CaCertValidator caCertValidator = new PreprovisionedCaCertValidator(caCert);
ScepClient client = new ScepClient(tmpCaId, caCertValidator);
client.init();
// Self-Signed Identity Certificate
MyKeypair keypair = generateRsaKeypair();
CertificationRequest csr = genCsr(keypair, getSubject(), challengePassword);
// self-signed cert must use the same subject as in CSR
X500Name subjectDn = csr.getCertificationRequestInfo().getSubject();
X509v3CertificateBuilder certGenerator = new X509v3CertificateBuilder(subjectDn, BigInteger.valueOf(1), new Date(), new Date(System.currentTimeMillis() + 24 * 3600 * 1000), subjectDn, keypair.getPublic());
ContentSigner signer = new JcaContentSignerBuilder("SHA256withRSA").build(keypair.getPrivate());
X509Certificate selfSignedCert = ScepUtil.parseCert(certGenerator.build(signer).getEncoded());
// Enroll certificate - RSA
EnrolmentResponse resp = (EnrolmentResponse) client.scepEnrol(csr, keypair.getPrivate(), selfSignedCert);
if (resp.isFailure()) {
throw new Exception("server returned 'failure'");
}
if (resp.isPending()) {
throw new Exception("server returned 'pending'");
}
X509Certificate cert = resp.getCertificates().get(0);
printCert("SCEP (RSA, Self-Signed Identity Cert)", cert);
// Use the CA signed identity certificate
X509Certificate identityCert = cert;
PrivateKey identityKey = keypair.getPrivate();
keypair = generateRsaKeypair();
csr = genCsr(keypair, getSubject(), challengePassword);
// Enroll certificate - RSA
resp = (EnrolmentResponse) client.scepEnrol(csr, identityKey, identityCert);
if (resp.isFailure()) {
throw new Exception("server returned 'failure'");
}
if (resp.isPending()) {
throw new Exception("server returned 'pending'");
}
cert = resp.getCertificates().get(0);
printCert("SCEP (RSA, CA issued identity Cert)", cert);
client.destroy();
} catch (Exception ex) {
ex.printStackTrace();
System.exit(-1);
}
}
use of sun.security.x509.X500Name in project xipki by xipki.
the class CaClientExample method genCsr.
protected static CertificationRequest genCsr(MyKeypair keypair, String subject, String challengePassword) throws GeneralSecurityException, OperatorCreationException {
X500Name subjectDn = new X500Name(subject);
PKCS10CertificationRequestBuilder csrBuilder = new PKCS10CertificationRequestBuilder(subjectDn, keypair.publicKeyInfo);
if (challengePassword != null && !challengePassword.isEmpty()) {
csrBuilder.addAttribute(PKCSObjectIdentifiers.pkcs_9_at_challengePassword, new DERPrintableString(challengePassword));
}
ContentSigner signer = buildSigner(keypair.privateKey, "SHA256");
return csrBuilder.build(signer).toASN1Structure();
}
Aggregations