Search in sources :

Example 1 with HashGenerationInfoType

use of iso.std.iso_iec._24727.tech.schema.HashGenerationInfoType in project open-ecard by ecsec.

the class SignStep method performSignature.

/**
 * This method performs the signature creation according to BSI TR-03112 part 7.
 *
 * @param cryptoMarker The {@link CryptoMarkerType} containing the SignatureCreationInfo for creating the signature.
 * @param keyReference A byte array containing the reference of the key to use.
 * @param algorithmIdentifier A byte array containing the identifier of the signing algorithm.
 * @param message The message to sign.
 * @param slotHandle The slotHandle identifying the card.
 * @param hashRef The variable contains the reference for the hash algorithm which have to be used.
 * @param hashInfo A HashGenerationInfo object which indicates how the hash computation is to perform.
 * @return A {@link SignResponse} object containing the signature of the <b>message</b>.
 * @throws TLVException Thrown if the TLV creation for the key identifier or algorithm identifier failed.
 * @throws IncorrectParameterException Thrown if the SignatureGenerationInfo does not contain PSO_CDS or INT_AUTH
 * after an MSE_KEY command.
 * @throws APDUException Thrown if one of the command to create the signature failed.
 * @throws org.openecard.common.WSHelper.WSException Thrown if the checkResults method of WSHelper failed.
 */
private SignResponse performSignature(CryptoMarkerType cryptoMarker, byte[] keyReference, byte[] algorithmIdentifier, byte[] message, byte[] slotHandle, byte[] hashRef, HashGenerationInfoType hashInfo) throws TLVException, IncorrectParameterException, APDUException, WSHelper.WSException {
    SignResponse response = WSHelper.makeResponse(SignResponse.class, WSHelper.makeResultOK());
    TLV tagAlgorithmIdentifier = new TLV();
    tagAlgorithmIdentifier.setTagNumWithClass(CARD_ALG_REF);
    tagAlgorithmIdentifier.setValue(algorithmIdentifier);
    TLV tagKeyReference = new TLV();
    tagKeyReference.setTagNumWithClass(KEY_REFERENCE_PRIVATE_KEY);
    tagKeyReference.setValue(keyReference);
    CardCommandAPDU cmdAPDU = null;
    CardResponseAPDU responseAPDU = null;
    String[] signatureGenerationInfo = cryptoMarker.getSignatureGenerationInfo();
    for (String command : signatureGenerationInfo) {
        HashSet<String> signGenInfo = new HashSet<>(java.util.Arrays.asList(signatureGenerationInfo));
        if (command.equals("MSE_KEY")) {
            byte[] mseData = tagKeyReference.toBER();
            if (signGenInfo.contains("PSO_CDS")) {
                cmdAPDU = new ManageSecurityEnvironment(SET_COMPUTATION, ManageSecurityEnvironment.DST, mseData);
            } else if (signGenInfo.contains("INT_AUTH") && !signGenInfo.contains("PSO_CDS")) {
                cmdAPDU = new ManageSecurityEnvironment(SET_COMPUTATION, ManageSecurityEnvironment.AT, mseData);
            } else {
                String msg = "The command 'MSE_KEY' followed by 'INT_AUTH' and 'PSO_CDS' is currently not supported.";
                LOG.error(msg);
                throw new IncorrectParameterException(msg);
            }
        } else if (command.equals("PSO_CDS")) {
            cmdAPDU = new PSOComputeDigitalSignature(message, BLOCKSIZE);
        } else if (command.equals("INT_AUTH")) {
            cmdAPDU = new InternalAuthenticate(message, BLOCKSIZE);
        } else if (command.equals("MSE_RESTORE")) {
            cmdAPDU = new ManageSecurityEnvironment.Restore(ManageSecurityEnvironment.DST);
        } else if (command.equals("MSE_HASH")) {
            cmdAPDU = new ManageSecurityEnvironment.Set(SET_COMPUTATION, ManageSecurityEnvironment.HT);
            TLV mseDataTLV = new TLV();
            mseDataTLV.setTagNumWithClass((byte) 0x80);
            mseDataTLV.setValue(hashRef);
            cmdAPDU.setData(mseDataTLV.toBER());
        } else if (command.equals("PSO_HASH")) {
            if (hashInfo == HashGenerationInfoType.LAST_ROUND_ON_CARD || hashInfo == HashGenerationInfoType.NOT_ON_CARD) {
                cmdAPDU = new PSOHash(PSOHash.P2_SET_HASH_OR_PART, message);
            } else {
                cmdAPDU = new PSOHash(PSOHash.P2_HASH_MESSAGE, message);
            }
        } else if (command.equals("MSE_DS")) {
            byte[] mseData = tagAlgorithmIdentifier.toBER();
            cmdAPDU = new ManageSecurityEnvironment(SET_COMPUTATION, ManageSecurityEnvironment.DST, mseData);
        } else if (command.equals("MSE_KEY_DS")) {
            byte[] mseData = ByteUtils.concatenate(tagKeyReference.toBER(), tagAlgorithmIdentifier.toBER());
            cmdAPDU = new ManageSecurityEnvironment(SET_COMPUTATION, ManageSecurityEnvironment.DST, mseData);
        } else if (command.equals("MSE_INT_AUTH")) {
            byte[] mseData = tagKeyReference.toBER();
            cmdAPDU = new ManageSecurityEnvironment(SET_COMPUTATION, ManageSecurityEnvironment.AT, mseData);
        } else if (command.equals("MSE_KEY_INT_AUTH")) {
            byte[] mseData = ByteUtils.concatenate(tagKeyReference.toBER(), tagAlgorithmIdentifier.toBER());
            cmdAPDU = new ManageSecurityEnvironment(SET_COMPUTATION, ManageSecurityEnvironment.AT, mseData);
        } else {
            String msg = "The signature generation command '" + command + "' is unknown.";
            throw new IncorrectParameterException(msg);
        }
        responseAPDU = cmdAPDU.transmit(dispatcher, slotHandle, Collections.<byte[]>emptyList());
    }
    byte[] signedMessage = responseAPDU.getData();
    // check if further response data is available
    while (responseAPDU.getTrailer()[0] == (byte) 0x61) {
        GetResponse getResponseData = new GetResponse();
        responseAPDU = getResponseData.transmit(dispatcher, slotHandle, Collections.<byte[]>emptyList());
        signedMessage = Arrays.concatenate(signedMessage, responseAPDU.getData());
    }
    if (!Arrays.areEqual(responseAPDU.getTrailer(), new byte[] { (byte) 0x90, (byte) 0x00 })) {
        String minor = SALErrorUtils.getMinor(responseAPDU.getTrailer());
        response.setResult(WSHelper.makeResultError(minor, responseAPDU.getStatusMessage()));
        return response;
    }
    response.setSignature(signedMessage);
    return response;
}
Also used : CardCommandAPDU(org.openecard.common.apdu.common.CardCommandAPDU) PSOHash(org.openecard.sal.protocol.genericcryptography.apdu.PSOHash) GetResponse(org.openecard.common.apdu.GetResponse) PSOComputeDigitalSignature(org.openecard.sal.protocol.genericcryptography.apdu.PSOComputeDigitalSignature) SignResponse(iso.std.iso_iec._24727.tech.schema.SignResponse) IncorrectParameterException(org.openecard.common.sal.exception.IncorrectParameterException) InternalAuthenticate(org.openecard.common.apdu.InternalAuthenticate) CardResponseAPDU(org.openecard.common.apdu.common.CardResponseAPDU) ManageSecurityEnvironment(org.openecard.common.apdu.ManageSecurityEnvironment) TLV(org.openecard.common.tlv.TLV) HashSet(java.util.HashSet)

Example 2 with HashGenerationInfoType

use of iso.std.iso_iec._24727.tech.schema.HashGenerationInfoType in project open-ecard by ecsec.

the class SignStep method perform.

@Override
public SignResponse perform(Sign sign, Map<String, Object> internalData) {
    SignResponse response = WSHelper.makeResponse(SignResponse.class, WSHelper.makeResultOK());
    try {
        ConnectionHandleType connectionHandle = SALUtils.getConnectionHandle(sign);
        String didName = SALUtils.getDIDName(sign);
        CardStateEntry cardStateEntry = SALUtils.getCardStateEntry(internalData, connectionHandle);
        DIDStructureType didStructure = SALUtils.getDIDStructure(sign, didName, cardStateEntry, connectionHandle);
        CryptoMarkerType cryptoMarker = new CryptoMarkerType(didStructure.getDIDMarker());
        byte[] slotHandle = connectionHandle.getSlotHandle();
        byte[] applicationID = connectionHandle.getCardApplication();
        Assert.securityConditionDID(cardStateEntry, applicationID, didName, CryptographicServiceActionName.SIGN);
        byte[] message = sign.getMessage();
        byte[] keyReference = cryptoMarker.getCryptoKeyInfo().getKeyRef().getKeyRef();
        byte[] algorithmIdentifier = cryptoMarker.getAlgorithmInfo().getCardAlgRef();
        byte[] hashRef = cryptoMarker.getAlgorithmInfo().getHashAlgRef();
        HashGenerationInfoType hashInfo = cryptoMarker.getHashGenerationInfo();
        if (didStructure.getDIDScope() == DIDScopeType.LOCAL) {
            keyReference[0] = (byte) (0x80 | keyReference[0]);
        }
        if (cryptoMarker.getSignatureGenerationInfo() != null) {
            response = performSignature(cryptoMarker, keyReference, algorithmIdentifier, message, slotHandle, hashRef, hashInfo);
        } else {
            // assuming that legacySignatureInformation exists
            BaseTemplateContext templateContext = new BaseTemplateContext();
            templateContext.put(HASH_TO_SIGN, message);
            templateContext.put(KEY_REFERENCE, keyReference);
            templateContext.put(ALGORITHM_IDENTIFIER, algorithmIdentifier);
            templateContext.put(HASHALGORITHM_REFERENCE, hashRef);
            response = performLegacySignature(cryptoMarker, connectionHandle, templateContext);
        }
    } catch (ECardException e) {
        response.setResult(e.getResult());
    } catch (Exception e) {
        LOG.warn(e.getMessage(), e);
        response.setResult(WSHelper.makeResult(e));
    }
    return response;
}
Also used : ConnectionHandleType(iso.std.iso_iec._24727.tech.schema.ConnectionHandleType) ECardException(org.openecard.common.ECardException) CardStateEntry(org.openecard.common.sal.state.CardStateEntry) SignResponse(iso.std.iso_iec._24727.tech.schema.SignResponse) DIDStructureType(iso.std.iso_iec._24727.tech.schema.DIDStructureType) CryptoMarkerType(org.openecard.crypto.common.sal.did.CryptoMarkerType) BaseTemplateContext(org.openecard.common.apdu.common.BaseTemplateContext) HashGenerationInfoType(iso.std.iso_iec._24727.tech.schema.HashGenerationInfoType) IncorrectParameterException(org.openecard.common.sal.exception.IncorrectParameterException) APDUException(org.openecard.common.apdu.exception.APDUException) InvocationTargetException(java.lang.reflect.InvocationTargetException) ECardException(org.openecard.common.ECardException) TLVException(org.openecard.common.tlv.TLVException) IOException(java.io.IOException) APDUTemplateException(org.openecard.common.apdu.common.APDUTemplateException)

Example 3 with HashGenerationInfoType

use of iso.std.iso_iec._24727.tech.schema.HashGenerationInfoType in project open-ecard by ecsec.

the class CryptoMarkerBuilder method build.

public CryptoMarkerType build() {
    CryptoMarkerType marker = new CryptoMarkerType();
    marker.setProtocol(PROTOCOL);
    if (algInfo != null) {
        try {
            JAXBElement<AlgorithmInfoType> e;
            e = new JAXBElement<>(new QName(ISONS, "AlgorithmInfo"), AlgorithmInfoType.class, algInfo);
            Document d = m.marshal(e);
            marker.getAny().add(d.getDocumentElement());
        } catch (MarshallingTypeException ex) {
            LOG.error("Failed to marshal AlgorithmInfo element.", ex);
        }
    }
    if (keyInfo != null) {
        try {
            JAXBElement<CryptoKeyInfoType> e;
            e = new JAXBElement<>(new QName(ISONS, "KeyInfo"), CryptoKeyInfoType.class, keyInfo);
            Document d = m.marshal(e);
            marker.getAny().add(d.getDocumentElement());
        } catch (MarshallingTypeException ex) {
            LOG.error("Failed to marshal KeyInfo element.", ex);
        }
    }
    if (sigGenInfo != null) {
        try {
            JAXBElement<String> e;
            e = new JAXBElement(new QName(ISONS, "SignatureGenerationInfo"), String.class, sigGenInfo);
            Document d = m.marshal(e);
            marker.getAny().add(d.getDocumentElement());
        } catch (MarshallingTypeException ex) {
            LOG.error("Failed to marshal SignatureGenerationInfo element.", ex);
        }
    }
    if (legacySignGenInfo != null) {
        try {
            JAXBElement<LegacySignatureGenerationType> e;
            e = new JAXBElement(new QName(ISONS, "LegacySignatureGenerationInfo"), LegacySignatureGenerationType.class, legacySignGenInfo);
            Document d = m.marshal(e);
            marker.getAny().add(d.getDocumentElement());
        } catch (MarshallingTypeException ex) {
            LOG.error("Failed to marshal LegacySignatureGenerationInfo element.", ex);
        }
    }
    if (hashGenInfo != null) {
        try {
            JAXBElement<HashGenerationInfoType> e;
            e = new JAXBElement(new QName(ISONS, "HashGenerationInfo"), HashGenerationInfoType.class, hashGenInfo);
            Document d = m.marshal(e);
            marker.getAny().add(d.getDocumentElement());
        } catch (MarshallingTypeException ex) {
            LOG.error("Failed to marshal HashGenerationInfo element.", ex);
        }
    }
    for (CertificateRefType certRef : getCertRefs()) {
        try {
            JAXBElement<CertificateRefType> e;
            e = new JAXBElement(new QName(ISONS, "CertificateRef"), CertificateRefType.class, certRef);
            Document d = m.marshal(e);
            marker.getAny().add(d.getDocumentElement());
        } catch (MarshallingTypeException ex) {
            LOG.error("Failed to marshal CertificateRef element.", ex);
        }
    }
    if (legacyKeyname != null) {
        try {
            JAXBElement<String> e;
            e = new JAXBElement(new QName(ISONS, "LegacyKeyName"), String.class, legacyKeyname);
            Document d = m.marshal(e);
            marker.getAny().add(d.getDocumentElement());
        } catch (MarshallingTypeException ex) {
            LOG.error("Failed to marshal LegacyKeyName element.", ex);
        }
    }
    return marker;
}
Also used : MarshallingTypeException(org.openecard.ws.marshal.MarshallingTypeException) LegacySignatureGenerationType(iso.std.iso_iec._24727.tech.schema.LegacySignatureGenerationType) QName(javax.xml.namespace.QName) CryptoMarkerType(iso.std.iso_iec._24727.tech.schema.CryptoMarkerType) JAXBElement(javax.xml.bind.JAXBElement) Document(org.w3c.dom.Document) HashGenerationInfoType(iso.std.iso_iec._24727.tech.schema.HashGenerationInfoType) CertificateRefType(iso.std.iso_iec._24727.tech.schema.CertificateRefType) CryptoKeyInfoType(iso.std.iso_iec._24727.tech.schema.CryptoKeyInfoType) AlgorithmInfoType(iso.std.iso_iec._24727.tech.schema.AlgorithmInfoType)

Example 4 with HashGenerationInfoType

use of iso.std.iso_iec._24727.tech.schema.HashGenerationInfoType in project open-ecard by ecsec.

the class HashStep method perform.

@Override
public HashResponse perform(Hash request, Map<String, Object> internalData) {
    HashResponse response = WSHelper.makeResponse(HashResponse.class, WSHelper.makeResultOK());
    try {
        ConnectionHandleType connectionHandle = SALUtils.getConnectionHandle(request);
        String didName = SALUtils.getDIDName(request);
        CardStateEntry cardStateEntry = SALUtils.getCardStateEntry(internalData, connectionHandle);
        DIDStructureType didStructure = SALUtils.getDIDStructure(request, didName, cardStateEntry, connectionHandle);
        CryptoMarkerType cryptoMarker = new CryptoMarkerType(didStructure.getDIDMarker());
        HashGenerationInfoType hashInfo = cryptoMarker.getHashGenerationInfo();
        if (hashInfo != null) {
            if (hashInfo == HashGenerationInfoType.NOT_ON_CARD) {
                String algId = cryptoMarker.getAlgorithmInfo().getAlgorithmIdentifier().getAlgorithm();
                SignatureAlgorithms alg = SignatureAlgorithms.fromAlgId(algId);
                HashAlgorithms hashAlg = alg.getHashAlg();
                if (hashAlg == null) {
                    String msg = String.format("Algorithm %s does not specify a Hash algorithm.", algId);
                    LOG.error(msg);
                    String minor = ECardConstants.Minor.App.INCORRECT_PARM;
                    response.setResult(WSHelper.makeResultError(minor, msg));
                } else {
                    // calculate hash
                    MessageDigest md = MessageDigest.getInstance(hashAlg.getJcaAlg());
                    md.update(request.getMessage());
                    byte[] digest = md.digest();
                    response.setHash(digest);
                }
            } else {
                // TODO: implement hashing on card
                String msg = String.format("Unsupported Hash generation type (%s) requested.", hashInfo);
                LOG.error(msg);
                String minor = ECardConstants.Minor.SAL.INAPPROPRIATE_PROTOCOL_FOR_ACTION;
                response.setResult(WSHelper.makeResultError(minor, msg));
            }
        } else {
            // no hash alg specified, this is an error
            String msg = String.format("No Hash generation type specified in CIF.");
            LOG.error(msg);
            String minor = ECardConstants.Minor.SAL.INAPPROPRIATE_PROTOCOL_FOR_ACTION;
            response.setResult(WSHelper.makeResultError(minor, msg));
        }
    } catch (ECardException e) {
        response.setResult(e.getResult());
    } catch (UnsupportedAlgorithmException | NoSuchAlgorithmException ex) {
    } catch (Exception e) {
        LOG.warn(e.getMessage(), e);
        response.setResult(WSHelper.makeResult(e));
    }
    return response;
}
Also used : ConnectionHandleType(iso.std.iso_iec._24727.tech.schema.ConnectionHandleType) HashAlgorithms(org.openecard.crypto.common.HashAlgorithms) CardStateEntry(org.openecard.common.sal.state.CardStateEntry) CryptoMarkerType(org.openecard.crypto.common.sal.did.CryptoMarkerType) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) HashGenerationInfoType(iso.std.iso_iec._24727.tech.schema.HashGenerationInfoType) UnsupportedAlgorithmException(org.openecard.crypto.common.UnsupportedAlgorithmException) ECardException(org.openecard.common.ECardException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) ECardException(org.openecard.common.ECardException) HashResponse(iso.std.iso_iec._24727.tech.schema.HashResponse) SignatureAlgorithms(org.openecard.crypto.common.SignatureAlgorithms) UnsupportedAlgorithmException(org.openecard.crypto.common.UnsupportedAlgorithmException) DIDStructureType(iso.std.iso_iec._24727.tech.schema.DIDStructureType) MessageDigest(java.security.MessageDigest)

Aggregations

HashGenerationInfoType (iso.std.iso_iec._24727.tech.schema.HashGenerationInfoType)3 ConnectionHandleType (iso.std.iso_iec._24727.tech.schema.ConnectionHandleType)2 DIDStructureType (iso.std.iso_iec._24727.tech.schema.DIDStructureType)2 SignResponse (iso.std.iso_iec._24727.tech.schema.SignResponse)2 ECardException (org.openecard.common.ECardException)2 IncorrectParameterException (org.openecard.common.sal.exception.IncorrectParameterException)2 CardStateEntry (org.openecard.common.sal.state.CardStateEntry)2 CryptoMarkerType (org.openecard.crypto.common.sal.did.CryptoMarkerType)2 AlgorithmInfoType (iso.std.iso_iec._24727.tech.schema.AlgorithmInfoType)1 CertificateRefType (iso.std.iso_iec._24727.tech.schema.CertificateRefType)1 CryptoKeyInfoType (iso.std.iso_iec._24727.tech.schema.CryptoKeyInfoType)1 CryptoMarkerType (iso.std.iso_iec._24727.tech.schema.CryptoMarkerType)1 HashResponse (iso.std.iso_iec._24727.tech.schema.HashResponse)1 LegacySignatureGenerationType (iso.std.iso_iec._24727.tech.schema.LegacySignatureGenerationType)1 IOException (java.io.IOException)1 InvocationTargetException (java.lang.reflect.InvocationTargetException)1 MessageDigest (java.security.MessageDigest)1 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)1 HashSet (java.util.HashSet)1 JAXBElement (javax.xml.bind.JAXBElement)1