use of org.openecard.bouncycastle.asn1.ASN1Encodable in project xipki by xipki.
the class ProxyP11Module method refresh.
public void refresh() throws P11TokenException {
byte[] resp = send(P11ProxyConstants.ACTION_GET_SERVER_CAPS, null);
Asn1ServerCaps caps;
try {
caps = Asn1ServerCaps.getInstance(resp);
} catch (BadAsn1ObjectException ex) {
throw new P11TokenException("response is a valid Asn1ServerCaps", ex);
}
if (!caps.getVersions().contains(version)) {
throw new P11TokenException("Server does not support any version supported by the client");
}
this.readOnly = caps.isReadOnly();
resp = send(P11ProxyConstants.ACTION_GET_SLOT_IDS, null);
ASN1Sequence seq;
try {
seq = ASN1Sequence.getInstance(resp);
} catch (IllegalArgumentException ex) {
throw new P11TokenException("response is not ASN1Sequence", ex);
}
final int n = seq.size();
Set<P11Slot> slots = new HashSet<>();
for (int i = 0; i < n; i++) {
Asn1P11SlotIdentifier asn1SlotId;
try {
ASN1Encodable obj = seq.getObjectAt(i);
asn1SlotId = Asn1P11SlotIdentifier.getInstance(obj);
} catch (Exception ex) {
throw new P11TokenException(ex.getMessage(), ex);
}
P11SlotIdentifier slotId = asn1SlotId.getSlotId();
if (!conf.isSlotIncluded(slotId)) {
continue;
}
if (!conf.isSlotIncluded(slotId)) {
LOG.info("skipped slot {}", slotId);
continue;
}
P11Slot slot = new ProxyP11Slot(this, slotId, conf.isReadOnly(), conf.getP11MechanismFilter());
slots.add(slot);
}
setSlots(slots);
}
use of org.openecard.bouncycastle.asn1.ASN1Encodable in project xipki by xipki.
the class OcspStatusCmd method processResponse.
@Override
protected Object processResponse(OCSPResp response, X509Certificate respIssuer, IssuerHash issuerHash, List<BigInteger> serialNumbers, Map<BigInteger, byte[]> encodedCerts) throws Exception {
ParamUtil.requireNonNull("response", response);
ParamUtil.requireNonNull("issuerHash", issuerHash);
ParamUtil.requireNonNull("serialNumbers", serialNumbers);
BasicOCSPResp basicResp = OcspUtils.extractBasicOcspResp(response);
boolean extendedRevoke = basicResp.getExtension(ObjectIdentifiers.id_pkix_ocsp_extendedRevoke) != null;
SingleResp[] singleResponses = basicResp.getResponses();
if (singleResponses == null || singleResponses.length == 0) {
throw new CmdFailure("received no status from server");
}
final int n = singleResponses.length;
if (n != serialNumbers.size()) {
throw new CmdFailure("received status with " + n + " single responses from server, but " + serialNumbers.size() + " were requested");
}
Date[] thisUpdates = new Date[n];
for (int i = 0; i < n; i++) {
thisUpdates[i] = singleResponses[i].getThisUpdate();
}
// check the signature if available
if (null == basicResp.getSignature()) {
println("response is not signed");
} else {
X509CertificateHolder[] responderCerts = basicResp.getCerts();
if (responderCerts == null || responderCerts.length < 1) {
throw new CmdFailure("no responder certificate is contained in the response");
}
ResponderID respId = basicResp.getResponderId().toASN1Primitive();
X500Name respIdByName = respId.getName();
byte[] respIdByKey = respId.getKeyHash();
X509CertificateHolder respSigner = null;
for (X509CertificateHolder cert : responderCerts) {
if (respIdByName != null) {
if (cert.getSubject().equals(respIdByName)) {
respSigner = cert;
}
} else {
byte[] spkiSha1 = HashAlgo.SHA1.hash(cert.getSubjectPublicKeyInfo().getPublicKeyData().getBytes());
if (Arrays.equals(respIdByKey, spkiSha1)) {
respSigner = cert;
}
}
if (respSigner != null) {
break;
}
}
if (respSigner == null) {
throw new CmdFailure("no responder certificate match the ResponderId");
}
boolean validOn = true;
for (Date thisUpdate : thisUpdates) {
validOn = respSigner.isValidOn(thisUpdate);
if (!validOn) {
throw new CmdFailure("responder certificate is not valid on " + thisUpdate);
}
}
if (validOn) {
PublicKey responderPubKey = KeyUtil.generatePublicKey(respSigner.getSubjectPublicKeyInfo());
ContentVerifierProvider cvp = securityFactory.getContentVerifierProvider(responderPubKey);
boolean sigValid = basicResp.isSignatureValid(cvp);
if (!sigValid) {
throw new CmdFailure("response is equipped with invalid signature");
}
// verify the OCSPResponse signer
if (respIssuer != null) {
boolean certValid = true;
X509Certificate jceRespSigner = X509Util.toX509Cert(respSigner.toASN1Structure());
if (X509Util.issues(respIssuer, jceRespSigner)) {
try {
jceRespSigner.verify(respIssuer.getPublicKey());
} catch (SignatureException ex) {
certValid = false;
}
}
if (!certValid) {
throw new CmdFailure("response is equipped with valid signature but the" + " OCSP signer is not trusted");
}
} else {
println("response is equipped with valid signature");
}
// end if(respIssuer)
}
if (verbose.booleanValue()) {
println("responder is " + X509Util.getRfc4519Name(responderCerts[0].getSubject()));
}
}
for (int i = 0; i < n; i++) {
if (n > 1) {
println("---------------------------- " + i + "----------------------------");
}
SingleResp singleResp = singleResponses[i];
CertificateStatus singleCertStatus = singleResp.getCertStatus();
String status;
if (singleCertStatus == null) {
status = "good";
} else if (singleCertStatus instanceof RevokedStatus) {
RevokedStatus revStatus = (RevokedStatus) singleCertStatus;
Date revTime = revStatus.getRevocationTime();
Date invTime = null;
Extension ext = singleResp.getExtension(Extension.invalidityDate);
if (ext != null) {
invTime = ASN1GeneralizedTime.getInstance(ext.getParsedValue()).getDate();
}
if (revStatus.hasRevocationReason()) {
int reason = revStatus.getRevocationReason();
if (extendedRevoke && reason == CrlReason.CERTIFICATE_HOLD.getCode() && revTime.getTime() == 0) {
status = "unknown (RFC6960)";
} else {
status = StringUtil.concatObjects("revoked, reason = ", CrlReason.forReasonCode(reason).getDescription(), ", revocationTime = ", revTime, (invTime == null ? "" : ", invalidityTime = " + invTime));
}
} else {
status = "revoked, no reason, revocationTime = " + revTime;
}
} else if (singleCertStatus instanceof UnknownStatus) {
status = "unknown (RFC2560)";
} else {
status = "ERROR";
}
StringBuilder msg = new StringBuilder();
CertificateID certId = singleResp.getCertID();
HashAlgo hashAlgo = HashAlgo.getNonNullInstance(certId.getHashAlgOID());
boolean issuerMatch = issuerHash.match(hashAlgo, certId.getIssuerNameHash(), certId.getIssuerKeyHash());
BigInteger serialNumber = certId.getSerialNumber();
msg.append("issuer matched: ").append(issuerMatch);
msg.append("\nserialNumber: ").append(LogUtil.formatCsn(serialNumber));
msg.append("\nCertificate status: ").append(status);
if (verbose.booleanValue()) {
msg.append("\nthisUpdate: ").append(singleResp.getThisUpdate());
msg.append("\nnextUpdate: ").append(singleResp.getNextUpdate());
Extension extension = singleResp.getExtension(ISISMTTObjectIdentifiers.id_isismtt_at_certHash);
if (extension != null) {
msg.append("\nCertHash is provided:\n");
ASN1Encodable extensionValue = extension.getParsedValue();
CertHash certHash = CertHash.getInstance(extensionValue);
ASN1ObjectIdentifier hashAlgOid = certHash.getHashAlgorithm().getAlgorithm();
byte[] hashValue = certHash.getCertificateHash();
msg.append("\tHash algo : ").append(hashAlgOid.getId()).append("\n");
msg.append("\tHash value: ").append(Hex.encode(hashValue)).append("\n");
if (encodedCerts != null) {
byte[] encodedCert = encodedCerts.get(serialNumber);
MessageDigest md = MessageDigest.getInstance(hashAlgOid.getId());
byte[] expectedHashValue = md.digest(encodedCert);
if (Arrays.equals(expectedHashValue, hashValue)) {
msg.append("\tThis matches the requested certificate");
} else {
msg.append("\tThis differs from the requested certificate");
}
}
}
// end if (extension != null)
extension = singleResp.getExtension(OCSPObjectIdentifiers.id_pkix_ocsp_archive_cutoff);
if (extension != null) {
ASN1Encodable extensionValue = extension.getParsedValue();
ASN1GeneralizedTime time = ASN1GeneralizedTime.getInstance(extensionValue);
msg.append("\nArchive-CutOff: ");
msg.append(time.getTimeString());
}
AlgorithmIdentifier sigAlg = basicResp.getSignatureAlgorithmID();
if (sigAlg == null) {
msg.append(("\nresponse is not signed"));
} else {
String sigAlgName = AlgorithmUtil.getSignatureAlgoName(sigAlg);
if (sigAlgName == null) {
sigAlgName = "unknown";
}
msg.append("\nresponse is signed with ").append(sigAlgName);
}
// extensions
msg.append("\nExtensions: ");
List<?> extensionOids = basicResp.getExtensionOIDs();
if (extensionOids == null || extensionOids.size() == 0) {
msg.append("-");
} else {
int size = extensionOids.size();
for (int j = 0; j < size; j++) {
ASN1ObjectIdentifier extensionOid = (ASN1ObjectIdentifier) extensionOids.get(j);
String name = EXTENSION_OIDNAME_MAP.get(extensionOid);
if (name == null) {
msg.append(extensionOid.getId());
} else {
msg.append(name);
}
if (j != size - 1) {
msg.append(", ");
}
}
}
}
// end if (verbose.booleanValue())
println(msg.toString());
}
// end for
println("");
return null;
}
use of org.openecard.bouncycastle.asn1.ASN1Encodable in project signer by demoiselle.
the class RevocationRefs method getValue.
@Override
public Attribute getValue() throws SignerException {
try {
int chainSize = certificates.length - 1;
ArrayList<CrlValidatedID> crls = new ArrayList<CrlValidatedID>();
for (int ix = 0; ix < chainSize; ix++) {
X509Certificate cert = (X509Certificate) certificates[ix];
Collection<ICPBR_CRL> icpCrls = crlRepository.getX509CRL(cert);
for (ICPBR_CRL icpCrl : icpCrls) {
crls.add(makeCrlValidatedID(icpCrl.getCRL()));
}
}
int crlsIdSize = crls.size();
CrlValidatedID[] crlsForId = new CrlValidatedID[crlsIdSize];
int i = 0;
for (CrlValidatedID crlVID : crls) {
crlsForId[i] = crlVID;
i++;
}
// CrlListID crlids = new CrlListID(crlsForId);
DERSequence crlValidatedIDSeq = new DERSequence(crlsForId);
// --CRLListID--/
ASN1Encodable[] crlValidatedIDSeqArr = new ASN1Encodable[1];
crlValidatedIDSeqArr[0] = crlValidatedIDSeq;
DERSequence crlListID = new DERSequence(crlValidatedIDSeqArr);
// CRLListID--/
DERTaggedObject crlListIDTagged = new DERTaggedObject(0, crlListID);
// CrlOcspRef--/
ASN1Encodable[] crlListIDTaggedArr = new ASN1Encodable[1];
crlListIDTaggedArr[0] = crlListIDTagged;
DERSequence crlOscpRef = new DERSequence(crlListIDTaggedArr);
// --CompleteRevocationRefs--/
ASN1Encodable[] crlOscpRefArr = new ASN1Encodable[1];
crlOscpRefArr[0] = crlOscpRef;
DERSequence completeRevocationRefs = new DERSequence(crlOscpRefArr);
// CrlOcspRef crlOcspRef = new CrlOcspRef(crlids, null, null);
return new Attribute(new ASN1ObjectIdentifier(identifier), new DERSet(completeRevocationRefs));
// CrlOcspRef[] crlOcspRefArray = new
// CrlOcspRef[completeRevocationRefs.size()];
} catch (NoSuchAlgorithmException | CRLException e) {
throw new SignerException(e.getMessage());
}
}
use of org.openecard.bouncycastle.asn1.ASN1Encodable in project signer by demoiselle.
the class CertificateRefs method getValue.
@Override
public Attribute getValue() throws SignerException {
try {
int chainSize = certificates.length - 1;
OtherCertID[] arrayOtherCertID = new OtherCertID[chainSize];
for (int i = 1; i <= chainSize; i++) {
X509Certificate issuerCert = null;
X509Certificate cert = (X509Certificate) certificates[i];
if (i < chainSize) {
issuerCert = (X509Certificate) certificates[i + 1];
} else {
// raiz
issuerCert = (X509Certificate) certificates[i];
}
Digest digest = DigestFactory.getInstance().factoryDefault();
digest.setAlgorithm(DigestAlgorithmEnum.SHA_256);
byte[] certHash = digest.digest(cert.getEncoded());
X500Name dirName = new X500Name(issuerCert.getSubjectX500Principal().getName());
GeneralName name = new GeneralName(dirName);
GeneralNames issuer = new GeneralNames(name);
ASN1Integer serialNumber = new ASN1Integer(cert.getSerialNumber());
IssuerSerial issuerSerial = new IssuerSerial(issuer, serialNumber);
AlgorithmIdentifier algId = new AlgorithmIdentifier(NISTObjectIdentifiers.id_sha256);
OtherCertID otherCertID = new OtherCertID(algId, certHash, issuerSerial);
arrayOtherCertID[i - 1] = otherCertID;
}
return new Attribute(new ASN1ObjectIdentifier(identifier), new DERSet(new ASN1Encodable[] { new DERSequence(arrayOtherCertID) }));
} catch (CertificateEncodingException e) {
throw new SignerException(e.getMessage());
}
}
use of org.openecard.bouncycastle.asn1.ASN1Encodable in project signer by demoiselle.
the class SignerRules method parse.
@Override
public void parse(ASN1Primitive primitive) {
ASN1Sequence derSequence = ASN1Object.getDERSequence(primitive);
int total = derSequence.size();
if (total > 0) {
for (int i = 0; i < total; i++) {
ASN1Primitive object = derSequence.getObjectAt(i).toASN1Primitive();
if (object instanceof DERTaggedObject) {
DERTaggedObject derTaggedObject = (DERTaggedObject) object;
TAG tag = TAG.getTag(derTaggedObject.getTagNo());
switch(tag) {
case mandatedCertificateRef:
this.mandatedCertificateRef = CertRefReq.parse(object);
break;
case mandatedCertificateInfo:
this.mandatedCertificateInfo = CertInfoReq.parse(object);
break;
case signPolExtensions:
this.signPolExtensions = new SignPolExtensions();
this.signPolExtensions.parse(object);
break;
default:
break;
}
}
}
}
int i = 0;
ASN1Encodable object = derSequence.getObjectAt(i);
if (!(object instanceof DERSequence)) {
if (object instanceof ASN1Boolean) {
this.externalSignedData = ((ASN1Boolean) object).isTrue();
}
i++;
}
this.mandatedSignedAttr = new CMSAttrs();
this.mandatedSignedAttr.parse(derSequence.getObjectAt(i).toASN1Primitive());
i++;
this.mandatedUnsignedAttr = new CMSAttrs();
this.mandatedUnsignedAttr.parse(derSequence.getObjectAt(i).toASN1Primitive());
}
Aggregations