use of org.openecard.crypto.common.sal.did.DidInfos in project open-ecard by ecsec.
the class ListCertificates method getCertificates.
public List<CertificateInfoType> getCertificates() throws WSHelper.WSException, NoSuchDid, CertificateException, CertificateEncodingException, SecurityConditionUnsatisfiable, ParameterInvalid, SlotHandleInvalid {
try {
ArrayList<CertificateInfoType> result = new ArrayList<>();
// get crypto dids
DidInfos didInfos = tokenCache.getInfo(pin, handle);
List<DidInfo> cryptoDids = didInfos.getCryptoDidInfos();
// get certificates for each crypto did
for (DidInfo nextDid : cryptoDids) {
LOG.debug("Reading certificates from DID={}.", nextDid.getDidName());
List<X509Certificate> certChain = getCertChain(nextDid);
if (!certChain.isEmpty() && matchesFilter(certChain)) {
AlgorithmInfoType algInfo = nextDid.getGenericCryptoMarker().getAlgorithmInfo();
try {
String jcaAlg = convertAlgInfo(algInfo);
X509Certificate cert = certChain.get(0);
CertificateInfoType certInfo = new CertificateInfoType();
for (X509Certificate nextCert : certChain) {
certInfo.getCertificate().add(nextCert.getEncoded());
}
certInfo.setUniqueSSN(getUniqueIdentifier(cert));
certInfo.setAlgorithm(jcaAlg);
certInfo.setDIDName(nextDid.getDidName());
result.add(certInfo);
} catch (UnsupportedAlgorithmException ex) {
// ignore this DID
String algId = algInfo.getAlgorithmIdentifier().getAlgorithm();
LOG.warn("Ignoring DID with unsupported algorithm ({}).", algId);
}
}
}
return result;
} catch (WSHelper.WSException ex) {
String minor = StringUtils.nullToEmpty(ex.getResultMinor());
switch(minor) {
case ECardConstants.Minor.App.INCORRECT_PARM:
throw new ParameterInvalid(ex.getMessage(), ex);
case ECardConstants.Minor.IFD.INVALID_SLOT_HANDLE:
throw new SlotHandleInvalid(ex.getMessage(), ex);
case ECardConstants.Minor.SAL.SECURITY_CONDITION_NOT_SATISFIED:
throw new SecurityConditionUnsatisfiable(ex.getMessage(), ex);
case ECardConstants.Minor.IFD.CANCELLATION_BY_USER:
case ECardConstants.Minor.SAL.CANCELLATION_BY_USER:
throw new ThreadTerminateException("Certificate retrieval interrupted.", ex);
default:
throw ex;
}
} catch (InvocationTargetExceptionUnchecked ex) {
if (ex.getCause() instanceof InterruptedException || ex.getCause() instanceof ThreadTerminateException) {
String msg = "Certificate retrieval interrupted.";
LOG.debug(msg, ex);
throw new ThreadTerminateException(msg);
} else {
String msg = ex.getCause().getMessage();
throw WSHelper.createException(WSHelper.makeResultError(ECardConstants.Minor.App.INT_ERROR, msg));
}
} finally {
tokenCache.clearPins();
}
}
use of org.openecard.crypto.common.sal.did.DidInfos in project open-ecard by ecsec.
the class ListTokens method determineTokenFeatures.
private boolean determineTokenFeatures(TokenInfoType next) {
try {
// request the missing information
ConnectionHandleType h = new ConnectionHandleType();
h.setSlotHandle(next.getConnectionHandle().getSlotHandle());
DidInfos dids = new DidInfos(dispatcher, null, h);
List<DidInfo> didInfos = dids.getDidInfos();
boolean needsDidPin = false;
boolean needsCertPin = false;
TreeSet<String> algorithms = new TreeSet<>();
// find out everything about the token
for (DidInfo didInfo : didInfos) {
if (didInfo.isCryptoDid()) {
// only evaluate if we have no positive match yet
if (!needsDidPin) {
needsDidPin |= didInfo.needsPin();
}
// only evaluate if we have no positive match yet
if (!needsCertPin) {
for (DataSetInfo dataSetinfo : didInfo.getRelatedDataSets()) {
needsCertPin |= dataSetinfo.needsPin();
}
}
// get the algorithm of the did
AlgorithmInfoType algInfo = didInfo.getGenericCryptoMarker().getAlgorithmInfo();
AlgorithmIdentifierType algId = algInfo.getAlgorithmIdentifier();
String alg = algInfo.getAlgorithm();
try {
if (algId != null && algId.getAlgorithm() != null) {
String jcaName = AllowedSignatureAlgorithms.algIdtoJcaName(algId.getAlgorithm());
algorithms.add(jcaName);
}
} catch (UnsupportedAlgorithmException ex) {
// ignore and fall back to Algorithm field
if (alg != null && !alg.isEmpty() && AllowedSignatureAlgorithms.isKnownJcaAlgorithm(alg)) {
algorithms.add(alg);
}
}
}
}
next.setNeedsPinForCertAccess(needsCertPin);
next.setNeedsPinForPrivateKeyAccess(needsDidPin);
next.getAlgorithm().addAll(algorithms);
// finished evaluation everything successfully
return true;
} catch (NoSuchDid | WSHelper.WSException | SecurityConditionUnsatisfiable ex) {
LOG.error("Failed to evaluate DID.", ex);
}
// there has been an error
return false;
}
use of org.openecard.crypto.common.sal.did.DidInfos in project open-ecard by ecsec.
the class Signer method sign.
public byte[] sign(byte[] data) throws NoSuchDid, WSHelper.WSException, SecurityConditionUnsatisfiable, ParameterInvalid, SlotHandleInvalid, PinBlocked {
Semaphore s = getLock(handle.getIFDName());
boolean acquired = false;
try {
s.acquire();
acquired = true;
// get crypto dids
DidInfos didInfos = tokenCache.getInfo(pin, handle);
DidInfo didInfo = didInfos.getDidInfo(didName);
didInfo.connectApplication();
didInfo.authenticateMissing();
CryptoMarkerType cryptoMarker = didInfo.getGenericCryptoMarker();
String algUri = cryptoMarker.getAlgorithmInfo().getAlgorithmIdentifier().getAlgorithm();
try {
SignatureAlgorithms alg = SignatureAlgorithms.fromAlgId(algUri);
// calculate hash if needed
byte[] digest = data;
if (alg.getHashAlg() != null && (cryptoMarker.getHashGenerationInfo() == null || cryptoMarker.getHashGenerationInfo() == HashGenerationInfoType.NOT_ON_CARD)) {
digest = didInfo.hash(digest);
}
// wrap hash in DigestInfo if needed
if (alg == SignatureAlgorithms.CKM_RSA_PKCS) {
try {
ASN1ObjectIdentifier digestOid = getHashAlgOid(data);
DigestInfo di = new DigestInfo(new AlgorithmIdentifier(digestOid, DERNull.INSTANCE), digest);
byte[] sigMsg = di.getEncoded(ASN1Encoding.DER);
digest = sigMsg;
} catch (IOException ex) {
String msg = "Error encoding DigestInfo object.";
Result r = WSHelper.makeResultError(ECardConstants.Minor.App.INT_ERROR, msg);
throw WSHelper.createException(r);
} catch (InvalidParameterException ex) {
String msg = "Hash algorithm could not be determined for the given hash.";
Result r = WSHelper.makeResultError(ECardConstants.Minor.App.INCORRECT_PARM, msg);
throw WSHelper.createException(r);
}
}
byte[] signature = didInfo.sign(digest);
return signature;
} catch (UnsupportedAlgorithmException ex) {
String msg = String.format("DID uses unsupported algorithm %s.", algUri);
throw WSHelper.createException(WSHelper.makeResultError(ECardConstants.Minor.App.INT_ERROR, msg));
}
} catch (WSHelper.WSException ex) {
String minor = StringUtils.nullToEmpty(ex.getResultMinor());
switch(minor) {
case ECardConstants.Minor.App.INCORRECT_PARM:
throw new ParameterInvalid(ex.getMessage(), ex);
case ECardConstants.Minor.IFD.INVALID_SLOT_HANDLE:
throw new SlotHandleInvalid(ex.getMessage(), ex);
case ECardConstants.Minor.IFD.PASSWORD_BLOCKED:
case ECardConstants.Minor.IFD.PASSWORD_SUSPENDED:
case ECardConstants.Minor.IFD.PASSWORD_DEACTIVATED:
throw new PinBlocked(ex.getMessage(), ex);
case ECardConstants.Minor.SAL.SECURITY_CONDITION_NOT_SATISFIED:
throw new SecurityConditionUnsatisfiable(ex.getMessage(), ex);
case ECardConstants.Minor.IFD.CANCELLATION_BY_USER:
case ECardConstants.Minor.SAL.CANCELLATION_BY_USER:
throw new ThreadTerminateException("Signature generation cancelled.", ex);
default:
throw ex;
}
} catch (InvocationTargetExceptionUnchecked ex) {
if (ex.getCause() instanceof InterruptedException || ex.getCause() instanceof ThreadTerminateException) {
throw new ThreadTerminateException("Signature creation interrupted.");
} else {
String msg = ex.getCause().getMessage();
throw WSHelper.createException(WSHelper.makeResultError(ECardConstants.Minor.App.INT_ERROR, msg));
}
} catch (InterruptedException ex) {
throw new ThreadTerminateException("Signature creation interrupted.");
} finally {
tokenCache.clearPins();
if (acquired) {
s.release();
}
}
}
use of org.openecard.crypto.common.sal.did.DidInfos in project open-ecard by ecsec.
the class SmartCardCredentialFactory method getClientCredentials.
@Override
public List<TlsCredentialedSigner> getClientCredentials(CertificateRequest cr) {
ArrayList<TlsCredentialedSigner> credentials = new ArrayList<>();
TlsCryptoParameters tlsCrypto = new TlsCryptoParameters(context);
LOG.debug("Selecting a suitable DID for the following requested algorithms:");
ArrayList<SignatureAndHashAlgorithm> crSigAlgs = getCrSigAlgs(cr);
removeUnsupportedAlgs(crSigAlgs);
for (SignatureAndHashAlgorithm reqAlg : crSigAlgs) {
String reqAlgStr = String.format("%s-%s", SignatureAlgorithm.getText(reqAlg.getSignature()), HashAlgorithm.getText(reqAlg.getHash()));
LOG.debug(" {}", reqAlgStr);
}
try {
DidInfos didInfos = tokenCache.getInfo(null, handle);
List<DidInfo> infos = didInfos.getCryptoDidInfos();
printCerts(infos);
// remove unsuitable DIDs
LOG.info("Sorting out DIDs not able to handle the TLS request.");
infos = removeSecretCertDids(infos);
infos = removeNonAuthDids(infos);
infos = removeUnsupportedAlgs(infos);
infos = removeUnsupportedCerts(cr, infos);
// infos = nonRawFirst(infos);
LOG.info("Creating signer instances for the TLS Client Certificate signature.");
// TLS < 1.2
if (crSigAlgs.isEmpty()) {
LOG.info("Looking for a raw RSA DID.");
for (DidInfo info : infos) {
try {
LOG.debug("Checking DID= {}.", info.getDidName());
TlsCredentialedSigner cred;
List<X509Certificate> chain = info.getRelatedCertificateChain();
Certificate clientCert = convertCert(context.getCrypto(), chain);
if (isRawRSA(info)) {
LOG.debug("Adding raw RSA signer.");
TlsSigner signer = new SmartCardSignerCredential(info);
cred = new DefaultTlsCredentialedSigner(tlsCrypto, signer, clientCert, null);
credentials.add(cred);
}
} catch (SecurityConditionUnsatisfiable | NoSuchDid | CertificateException | IOException ex) {
LOG.error("Failed to read certificates from card. Skipping DID " + info.getDidName() + ".", ex);
} catch (UnsupportedAlgorithmException ex) {
LOG.error("Unsupported algorithm used in CIF. Skipping DID " + info.getDidName() + ".", ex);
} catch (WSHelper.WSException ex) {
LOG.error("Unknown error accessing DID " + info.getDidName() + ".", ex);
}
}
} else {
// TLS >= 1.2
LOG.info("Looking for most specific DIDs.");
// looping over the servers alg list preserves its ordering
for (SignatureAndHashAlgorithm reqAlg : crSigAlgs) {
for (DidInfo info : infos) {
LOG.debug("Checking DID={}.", info.getDidName());
try {
AlgorithmInfoType algInfo = info.getGenericCryptoMarker().getAlgorithmInfo();
SignatureAlgorithms alg = SignatureAlgorithms.fromAlgId(algInfo.getAlgorithmIdentifier().getAlgorithm());
TlsCredentialedSigner cred;
List<X509Certificate> chain = info.getRelatedCertificateChain();
Certificate clientCert = convertCert(context.getCrypto(), chain);
// find one DID for this problem, then continue with the next algorithm
if (matchesAlg(reqAlg, alg) && (alg.getHashAlg() != null || isSafeForNoneDid(reqAlg))) {
LOG.debug("Adding {} signer.", alg.getJcaAlg());
TlsSigner signer = new SmartCardSignerCredential(info);
cred = new DefaultTlsCredentialedSigner(tlsCrypto, signer, clientCert, reqAlg);
credentials.add(cred);
// break;
return credentials;
}
} catch (SecurityConditionUnsatisfiable | NoSuchDid | CertificateException | IOException ex) {
LOG.error("Failed to read certificates from card. Skipping DID " + info.getDidName() + ".", ex);
} catch (UnsupportedAlgorithmException ex) {
LOG.error("Unsupported algorithm used in CIF. Skipping DID " + info.getDidName() + ".", ex);
} catch (WSHelper.WSException ex) {
LOG.error("Unknown error accessing DID " + info.getDidName() + ".", ex);
}
}
}
}
} catch (NoSuchDid | WSHelper.WSException ex) {
LOG.error("Failed to access DIDs of smartcard. Proceeding without client authentication.", ex);
}
return credentials;
}
Aggregations