use of org.openecard.bouncycastle.asn1.x509.Certificate in project xipki by xipki.
the class ScepResponder method servicePkiOperation0.
private PkiMessage servicePkiOperation0(DecodedPkiMessage req, AuditEvent event) throws MessageDecodingException, CaException {
TransactionId tid = req.getTransactionId();
PkiMessage rep = new PkiMessage(tid, MessageType.CertRep, Nonce.randomNonce());
rep.setPkiStatus(PkiStatus.SUCCESS);
rep.setRecipientNonce(req.getSenderNonce());
if (req.getFailureMessage() != null) {
return buildPkiMessage(rep, PkiStatus.FAILURE, FailInfo.badRequest);
}
Boolean bo = req.isSignatureValid();
if (bo != null && !bo.booleanValue()) {
return buildPkiMessage(rep, PkiStatus.FAILURE, FailInfo.badMessageCheck);
}
bo = req.isDecryptionSuccessful();
if (bo != null && !bo.booleanValue()) {
return buildPkiMessage(rep, PkiStatus.FAILURE, FailInfo.badRequest);
}
Date signingTime = req.getSigningTime();
if (maxSigningTimeBiasInMs > 0) {
boolean isTimeBad = false;
if (signingTime == null) {
isTimeBad = true;
} else {
long now = System.currentTimeMillis();
long diff = now - signingTime.getTime();
if (diff < 0) {
diff = -1 * diff;
}
isTimeBad = diff > maxSigningTimeBiasInMs;
}
if (isTimeBad) {
return buildPkiMessage(rep, PkiStatus.FAILURE, FailInfo.badTime);
}
}
// check the digest algorithm
String oid = req.getDigestAlgorithm().getId();
ScepHashAlgo hashAlgo = ScepHashAlgo.forNameOrOid(oid);
if (hashAlgo == null) {
LOG.warn("tid={}: unknown digest algorithm {}", tid, oid);
return buildPkiMessage(rep, PkiStatus.FAILURE, FailInfo.badAlg);
}
// end if
boolean supported = false;
if (hashAlgo == ScepHashAlgo.SHA1) {
if (caCaps.containsCapability(CaCapability.SHA1)) {
supported = true;
}
} else if (hashAlgo == ScepHashAlgo.SHA256) {
if (caCaps.containsCapability(CaCapability.SHA256)) {
supported = true;
}
} else if (hashAlgo == ScepHashAlgo.SHA512) {
if (caCaps.containsCapability(CaCapability.SHA512)) {
supported = true;
}
} else if (hashAlgo == ScepHashAlgo.MD5) {
if (control.isUseInsecureAlg()) {
supported = true;
}
}
if (!supported) {
LOG.warn("tid={}: unsupported digest algorithm {}", tid, oid);
return buildPkiMessage(rep, PkiStatus.FAILURE, FailInfo.badAlg);
}
// end if
// check the content encryption algorithm
ASN1ObjectIdentifier encOid = req.getContentEncryptionAlgorithm();
if (CMSAlgorithm.DES_EDE3_CBC.equals(encOid)) {
if (!caCaps.containsCapability(CaCapability.DES3)) {
LOG.warn("tid={}: encryption with DES3 algorithm is not permitted", tid, encOid);
return buildPkiMessage(rep, PkiStatus.FAILURE, FailInfo.badAlg);
}
} else if (AES_ENC_ALGS.contains(encOid)) {
if (!caCaps.containsCapability(CaCapability.AES)) {
LOG.warn("tid={}: encryption with AES algorithm {} is not permitted", tid, encOid);
return buildPkiMessage(rep, PkiStatus.FAILURE, FailInfo.badAlg);
}
} else if (CMSAlgorithm.DES_CBC.equals(encOid)) {
if (!control.isUseInsecureAlg()) {
LOG.warn("tid={}: encryption with DES algorithm {} is not permitted", tid, encOid);
return buildPkiMessage(rep, PkiStatus.FAILURE, FailInfo.badAlg);
}
} else {
LOG.warn("tid={}: encryption with algorithm {} is not permitted", tid, encOid);
return buildPkiMessage(rep, PkiStatus.FAILURE, FailInfo.badAlg);
}
if (rep.getPkiStatus() == PkiStatus.FAILURE) {
return rep;
}
MessageType messageType = req.getMessageType();
switch(messageType) {
case PKCSReq:
boolean selfSigned = req.getSignatureCert().getIssuerX500Principal().equals(req.getSignatureCert().getIssuerX500Principal());
CertificationRequest csr = CertificationRequest.getInstance(req.getMessageData());
if (selfSigned) {
X500Name name = X500Name.getInstance(req.getSignatureCert().getSubjectX500Principal().getEncoded());
if (!name.equals(csr.getCertificationRequestInfo().getSubject())) {
LOG.warn("tid={}: self-signed cert.subject != CSR.subject", tid);
return buildPkiMessage(rep, PkiStatus.FAILURE, FailInfo.badRequest);
}
}
String challengePwd = getChallengePassword(csr.getCertificationRequestInfo());
if (challengePwd == null || !control.getSecret().equals(challengePwd)) {
LOG.warn("challengePassword is not trusted");
return buildPkiMessage(rep, PkiStatus.FAILURE, FailInfo.badRequest);
}
Certificate cert;
try {
cert = caEmulator.generateCert(csr);
} catch (Exception ex) {
throw new CaException("system failure: " + ex.getMessage(), ex);
}
if (cert != null && control.isPendingCert()) {
rep.setPkiStatus(PkiStatus.PENDING);
} else if (cert != null) {
ContentInfo messageData = createSignedData(cert);
rep.setMessageData(messageData);
} else {
buildPkiMessage(rep, PkiStatus.FAILURE, FailInfo.badCertId);
}
break;
case CertPoll:
IssuerAndSubject is = IssuerAndSubject.getInstance(req.getMessageData());
cert = caEmulator.pollCert(is.getIssuer(), is.getSubject());
if (cert != null) {
rep.setMessageData(createSignedData(cert));
} else {
buildPkiMessage(rep, PkiStatus.FAILURE, FailInfo.badCertId);
}
break;
case GetCert:
IssuerAndSerialNumber isn = IssuerAndSerialNumber.getInstance(req.getMessageData());
cert = caEmulator.getCert(isn.getName(), isn.getSerialNumber().getValue());
if (cert != null) {
rep.setMessageData(createSignedData(cert));
} else {
buildPkiMessage(rep, PkiStatus.FAILURE, FailInfo.badCertId);
}
break;
case RenewalReq:
if (!caCaps.containsCapability(CaCapability.Renewal)) {
buildPkiMessage(rep, PkiStatus.FAILURE, FailInfo.badRequest);
} else {
csr = CertificationRequest.getInstance(req.getMessageData());
try {
cert = caEmulator.generateCert(csr);
} catch (Exception ex) {
throw new CaException("system failure: " + ex.getMessage(), ex);
}
if (cert != null) {
rep.setMessageData(createSignedData(cert));
} else {
rep.setPkiStatus(PkiStatus.FAILURE);
rep.setFailInfo(FailInfo.badCertId);
}
}
break;
case UpdateReq:
if (!caCaps.containsCapability(CaCapability.Update)) {
buildPkiMessage(rep, PkiStatus.FAILURE, FailInfo.badRequest);
} else {
csr = CertificationRequest.getInstance(req.getMessageData());
try {
cert = caEmulator.generateCert(csr);
} catch (Exception ex) {
throw new CaException("system failure: " + ex.getMessage(), ex);
}
if (cert != null) {
rep.setMessageData(createSignedData(cert));
} else {
buildPkiMessage(rep, PkiStatus.FAILURE, FailInfo.badCertId);
}
}
break;
case GetCRL:
isn = IssuerAndSerialNumber.getInstance(req.getMessageData());
CertificateList crl;
try {
crl = caEmulator.getCrl(isn.getName(), isn.getSerialNumber().getValue());
} catch (Exception ex) {
throw new CaException("system failure: " + ex.getMessage(), ex);
}
if (crl != null) {
rep.setMessageData(createSignedData(crl));
} else {
buildPkiMessage(rep, PkiStatus.FAILURE, FailInfo.badCertId);
}
break;
default:
buildPkiMessage(rep, PkiStatus.FAILURE, FailInfo.badRequest);
}
return rep;
}
use of org.openecard.bouncycastle.asn1.x509.Certificate in project xipki by xipki.
the class ScepUtil method generateSelfsignedCert.
public static X509Certificate generateSelfsignedCert(X500Name subjectDn, SubjectPublicKeyInfo pubKeyInfo, PrivateKey identityKey) throws CertificateException {
requireNonNull("subjectDn", subjectDn);
requireNonNull("pubKeyInfo", pubKeyInfo);
requireNonNull("identityKey", identityKey);
Date notBefore = new Date(System.currentTimeMillis() - 5 * MIN_IN_MS);
Date notAfter = new Date(notBefore.getTime() + 30 * DAY_IN_MS);
X509v3CertificateBuilder certGenerator = new X509v3CertificateBuilder(subjectDn, BigInteger.ONE, notBefore, notAfter, subjectDn, pubKeyInfo);
X509KeyUsage ku = new X509KeyUsage(X509KeyUsage.digitalSignature | X509KeyUsage.dataEncipherment | X509KeyUsage.keyAgreement | X509KeyUsage.keyEncipherment);
try {
certGenerator.addExtension(Extension.keyUsage, true, ku);
} catch (CertIOException ex) {
throw new CertificateException("could not generate self-signed certificate: " + ex.getMessage(), ex);
}
String sigAlgorithm = ScepUtil.getSignatureAlgorithm(identityKey, ScepHashAlgo.SHA1);
ContentSigner contentSigner;
try {
contentSigner = new JcaContentSignerBuilder(sigAlgorithm).build(identityKey);
} catch (OperatorCreationException ex) {
throw new CertificateException("error while creating signer", ex);
}
Certificate asn1Cert = certGenerator.build(contentSigner).toASN1Structure();
return toX509Cert(asn1Cert);
}
use of org.openecard.bouncycastle.asn1.x509.Certificate in project xipki by xipki.
the class ExtractCertFromCrlCmd method execute0.
@Override
protected Object execute0() throws Exception {
X509CRL crl = X509Util.parseCrl(crlFile);
String oidExtnCerts = ObjectIdentifiers.id_xipki_ext_crlCertset.getId();
byte[] extnValue = crl.getExtensionValue(oidExtnCerts);
if (extnValue == null) {
throw new IllegalCmdParamException("no certificate is contained in " + crlFile);
}
extnValue = removingTagAndLenFromExtensionValue(extnValue);
ASN1Set asn1Set = DERSet.getInstance(extnValue);
final int n = asn1Set.size();
if (n == 0) {
throw new CmdFailure("no certificate is contained in " + crlFile);
}
ByteArrayOutputStream out = new ByteArrayOutputStream();
ZipOutputStream zip = new ZipOutputStream(out);
for (int i = 0; i < n; i++) {
ASN1Encodable asn1 = asn1Set.getObjectAt(i);
Certificate cert;
try {
ASN1Sequence seq = ASN1Sequence.getInstance(asn1);
cert = Certificate.getInstance(seq.getObjectAt(0));
} catch (IllegalArgumentException ex) {
// backwards compatibility
cert = Certificate.getInstance(asn1);
}
byte[] certBytes = cert.getEncoded();
String sha1FpCert = HashAlgo.SHA1.hexHash(certBytes);
ZipEntry certZipEntry = new ZipEntry(sha1FpCert + ".der");
zip.putNextEntry(certZipEntry);
try {
zip.write(certBytes);
} finally {
zip.closeEntry();
}
}
zip.flush();
zip.close();
saveVerbose("extracted " + n + " certificates to", new File(outFile), out.toByteArray());
return null;
}
use of org.openecard.bouncycastle.asn1.x509.Certificate in project jasn1 by openmuc.
the class AuthenticateResponseOk method decode.
public int decode(InputStream is, boolean withTag) throws IOException {
int codeLength = 0;
int subCodeLength = 0;
BerTag berTag = new BerTag();
if (withTag) {
codeLength += tag.decodeAndCheck(is);
}
BerLength length = new BerLength();
codeLength += length.decode(is);
int totalLength = length.val;
if (totalLength == -1) {
subCodeLength += berTag.decode(is);
if (berTag.tagNumber == 0 && berTag.tagClass == 0 && berTag.primitive == 0) {
int nextByte = is.read();
if (nextByte != 0) {
if (nextByte == -1) {
throw new EOFException("Unexpected end of input stream.");
}
throw new IOException("Decoded sequence has wrong end of contents octets");
}
codeLength += subCodeLength + 1;
return codeLength;
}
if (berTag.equals(EuiccSigned1.tag)) {
euiccSigned1 = new EuiccSigned1();
subCodeLength += euiccSigned1.decode(is, false);
subCodeLength += berTag.decode(is);
}
if (berTag.tagNumber == 0 && berTag.tagClass == 0 && berTag.primitive == 0) {
int nextByte = is.read();
if (nextByte != 0) {
if (nextByte == -1) {
throw new EOFException("Unexpected end of input stream.");
}
throw new IOException("Decoded sequence has wrong end of contents octets");
}
codeLength += subCodeLength + 1;
return codeLength;
}
if (berTag.equals(BerTag.APPLICATION_CLASS, BerTag.PRIMITIVE, 55)) {
euiccSignature1 = new BerOctetString();
subCodeLength += euiccSignature1.decode(is, false);
subCodeLength += berTag.decode(is);
}
if (berTag.tagNumber == 0 && berTag.tagClass == 0 && berTag.primitive == 0) {
int nextByte = is.read();
if (nextByte != 0) {
if (nextByte == -1) {
throw new EOFException("Unexpected end of input stream.");
}
throw new IOException("Decoded sequence has wrong end of contents octets");
}
codeLength += subCodeLength + 1;
return codeLength;
}
if (berTag.equals(Certificate.tag)) {
euiccCertificate = new Certificate();
subCodeLength += euiccCertificate.decode(is, false);
subCodeLength += berTag.decode(is);
}
if (berTag.tagNumber == 0 && berTag.tagClass == 0 && berTag.primitive == 0) {
int nextByte = is.read();
if (nextByte != 0) {
if (nextByte == -1) {
throw new EOFException("Unexpected end of input stream.");
}
throw new IOException("Decoded sequence has wrong end of contents octets");
}
codeLength += subCodeLength + 1;
return codeLength;
}
if (berTag.equals(Certificate.tag)) {
eumCertificate = new Certificate();
subCodeLength += eumCertificate.decode(is, false);
subCodeLength += berTag.decode(is);
}
int nextByte = is.read();
if (berTag.tagNumber != 0 || berTag.tagClass != 0 || berTag.primitive != 0 || nextByte != 0) {
if (nextByte == -1) {
throw new EOFException("Unexpected end of input stream.");
}
throw new IOException("Decoded sequence has wrong end of contents octets");
}
codeLength += subCodeLength + 1;
return codeLength;
}
codeLength += totalLength;
subCodeLength += berTag.decode(is);
if (berTag.equals(EuiccSigned1.tag)) {
euiccSigned1 = new EuiccSigned1();
subCodeLength += euiccSigned1.decode(is, false);
subCodeLength += berTag.decode(is);
} else {
throw new IOException("Tag does not match the mandatory sequence element tag.");
}
if (berTag.equals(BerTag.APPLICATION_CLASS, BerTag.PRIMITIVE, 55)) {
euiccSignature1 = new BerOctetString();
subCodeLength += euiccSignature1.decode(is, false);
subCodeLength += berTag.decode(is);
} else {
throw new IOException("Tag does not match the mandatory sequence element tag.");
}
if (berTag.equals(Certificate.tag)) {
euiccCertificate = new Certificate();
subCodeLength += euiccCertificate.decode(is, false);
subCodeLength += berTag.decode(is);
} else {
throw new IOException("Tag does not match the mandatory sequence element tag.");
}
if (berTag.equals(Certificate.tag)) {
eumCertificate = new Certificate();
subCodeLength += eumCertificate.decode(is, false);
if (subCodeLength == totalLength) {
return codeLength;
}
}
throw new IOException("Unexpected end of sequence, length tag: " + totalLength + ", actual sequence length: " + subCodeLength);
}
use of org.openecard.bouncycastle.asn1.x509.Certificate in project airavata by apache.
the class X509SecurityContext method generateShortLivedCredential.
public KeyAndCertCredential generateShortLivedCredential(String userDN, String caCertPath, String caKeyPath, String caPwd) throws Exception {
// 15 minutes
final long CredentialGoodFromOffset = 1000L * 60L * 15L;
// ago
final long startTime = System.currentTimeMillis() - CredentialGoodFromOffset;
final long endTime = startTime + 30 * 3600 * 1000;
String keyLengthProp = "1024";
int keyLength = Integer.parseInt(keyLengthProp);
String signatureAlgorithm = "SHA1withRSA";
KeyAndCertCredential caCred = getCACredential(caCertPath, caKeyPath, caPwd);
KeyPairGenerator kpg = KeyPairGenerator.getInstance(caCred.getKey().getAlgorithm());
kpg.initialize(keyLength);
KeyPair pair = kpg.generateKeyPair();
X500Principal subjectDN = new X500Principal(userDN);
Random rand = new Random();
SubjectPublicKeyInfo publicKeyInfo;
try {
publicKeyInfo = SubjectPublicKeyInfo.getInstance(new ASN1InputStream(pair.getPublic().getEncoded()).readObject());
} catch (IOException e) {
throw new InvalidKeyException("Can not parse the public key" + "being included in the short lived certificate", e);
}
X500Name issuerX500Name = CertificateHelpers.toX500Name(caCred.getCertificate().getSubjectX500Principal());
X500Name subjectX500Name = CertificateHelpers.toX500Name(subjectDN);
X509v3CertificateBuilder certBuilder = new X509v3CertificateBuilder(issuerX500Name, new BigInteger(20, rand), new Date(startTime), new Date(endTime), subjectX500Name, publicKeyInfo);
AlgorithmIdentifier sigAlgId = X509v3CertificateBuilder.extractAlgorithmId(caCred.getCertificate());
X509Certificate certificate = certBuilder.build(caCred.getKey(), sigAlgId, signatureAlgorithm, null, null);
certificate.checkValidity(new Date());
certificate.verify(caCred.getCertificate().getPublicKey());
KeyAndCertCredential result = new KeyAndCertCredential(pair.getPrivate(), new X509Certificate[] { certificate, caCred.getCertificate() });
return result;
}
Aggregations