Search in sources :

Example 1 with SignResponse

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

the class TinySAL method sign.

/**
 * The Sign function signs a transmitted message.
 * See BSI-TR-03112-4, version 1.1.2, section 3.5.5.
 *
 * @param request Sign
 * @return SignResponse
 */
@Override
public SignResponse sign(Sign request) {
    SignResponse response = WSHelper.makeResponse(SignResponse.class, WSHelper.makeResultOK());
    CardStateEntry cardStateEntry = null;
    try {
        ConnectionHandleType connectionHandle = SALUtils.getConnectionHandle(request);
        cardStateEntry = SALUtils.getCardStateEntry(states, connectionHandle, false);
        byte[] applicationID = cardStateEntry.getCurrentCardApplication().getApplicationIdentifier();
        String didName = SALUtils.getDIDName(request);
        byte[] message = request.getMessage();
        Assert.assertIncorrectParameter(message, "The parameter Message is empty.");
        DIDScopeType didScope = request.getDIDScope();
        if (didScope == null) {
            didScope = DIDScopeType.LOCAL;
        }
        if (didScope.equals(DIDScopeType.LOCAL)) {
            byte[] necessarySelectedApp = cardStateEntry.getInfo().getApplicationIdByDidName(didName, didScope);
            if (!Arrays.equals(necessarySelectedApp, applicationID)) {
                String msg = "Wrong application selected for the execution of Sign with the DID " + didName + ".";
                throw new SecurityConditionNotSatisfiedException(msg);
            }
        }
        DIDStructureType didStructure = cardStateEntry.getDIDStructure(didName, didScope);
        Assert.assertNamedEntityNotFound(didStructure, "The given DIDName cannot be found.");
        String protocolURI = didStructure.getDIDMarker().getProtocol();
        SALProtocol protocol = getProtocol(connectionHandle, request.getDIDScope(), protocolURI);
        if (protocol.hasNextStep(FunctionType.Sign)) {
            response = protocol.sign(request);
            removeFinishedProtocol(connectionHandle, protocolURI, protocol);
        } else {
            throw new InappropriateProtocolForActionException("Sign", protocol.toString());
        }
    } catch (ECardException e) {
        response.setResult(e.getResult());
    } catch (Exception e) {
        LOG.error(e.getMessage(), e);
        throwThreadKillException(e);
        response.setResult(WSHelper.makeResult(e));
    }
    // TODO: remove when PIN state tracking is implemented
    setPinNotAuth(cardStateEntry);
    return response;
}
Also used : ConnectionHandleType(iso.std.iso_iec._24727.tech.schema.ConnectionHandleType) InappropriateProtocolForActionException(org.openecard.common.sal.exception.InappropriateProtocolForActionException) ECardException(org.openecard.common.ECardException) CardStateEntry(org.openecard.common.sal.state.CardStateEntry) SignResponse(iso.std.iso_iec._24727.tech.schema.SignResponse) SecurityConditionNotSatisfiedException(org.openecard.common.sal.exception.SecurityConditionNotSatisfiedException) SALProtocol(org.openecard.addon.sal.SALProtocol) DIDScopeType(iso.std.iso_iec._24727.tech.schema.DIDScopeType) DIDStructureType(iso.std.iso_iec._24727.tech.schema.DIDStructureType) PrerequisitesNotSatisfiedException(org.openecard.common.sal.exception.PrerequisitesNotSatisfiedException) NameExistsException(org.openecard.common.sal.exception.NameExistsException) AddonNotFoundException(org.openecard.addon.AddonNotFoundException) ThreadTerminateException(org.openecard.common.ThreadTerminateException) ECardException(org.openecard.common.ECardException) NamedEntityNotFoundException(org.openecard.common.sal.exception.NamedEntityNotFoundException) UnknownProtocolException(org.openecard.common.sal.exception.UnknownProtocolException) IncorrectParameterException(org.openecard.common.sal.exception.IncorrectParameterException) InappropriateProtocolForActionException(org.openecard.common.sal.exception.InappropriateProtocolForActionException) TLVException(org.openecard.common.tlv.TLVException) SecurityConditionNotSatisfiedException(org.openecard.common.sal.exception.SecurityConditionNotSatisfiedException) UnknownConnectionHandleException(org.openecard.common.sal.exception.UnknownConnectionHandleException)

Example 2 with SignResponse

use of iso.std.iso_iec._24727.tech.schema.SignResponse 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 3 with SignResponse

use of iso.std.iso_iec._24727.tech.schema.SignResponse 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 4 with SignResponse

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

the class SignStep method performLegacySignature.

/**
 * The method performs the SignatureCreation if no standard commands are possible.
 * This method creates a signature with APDUs which are not covered by the methods defined in TR-03112 part 7.
 *
 * @param cryptoMarker A {@link CryptoMarkerType} object containing the information about the creation of a signature
 *   in a legacy way.
 * @param slotHandle A slotHandle identifying the current card.
 * @param templateCTX A Map containing the context data for the evaluation of the template variables. This object
 *   contains per default the message to sign and the {@link TLVFunction}.
 * @return A {@link SignResponse} object containing the signature of the <b>message</b>.
 * @throws APDUTemplateException Thrown if the evaluation of the {@link CardCommandTemplate} failed.
 * @throws APDUException Thrown if one of the commands to execute failed.
 * @throws WSHelper.WSException Thrown if the checkResult method of WSHelper failed.
 */
private SignResponse performLegacySignature(CryptoMarkerType cryptoMarker, ConnectionHandleType connectionHandle, BaseTemplateContext templateCTX) throws APDUTemplateException, APDUException, WSHelper.WSException {
    SignResponse response = WSHelper.makeResponse(SignResponse.class, WSHelper.makeResultOK());
    List<Object> legacyCommands = cryptoMarker.getLegacySignatureGenerationInfo();
    CardCommandAPDU cmdAPDU;
    CardResponseAPDU responseAPDU = null;
    byte[] slotHandle = connectionHandle.getSlotHandle();
    byte[] signedMessage;
    for (Object next : legacyCommands) {
        if (next instanceof CardCallTemplateType) {
            CardCallTemplateType cctt = (CardCallTemplateType) next;
            CardCommandTemplate template = new CardCommandTemplate(cctt);
            cmdAPDU = template.evaluate(templateCTX);
            responseAPDU = cmdAPDU.transmit(dispatcher, slotHandle, Collections.<byte[]>emptyList());
        } else if (next instanceof APICommand) {
            sendAPICommand(connectionHandle, (APICommand) next);
        }
    }
    signedMessage = responseAPDU.getData();
    // check if further response data is available
    while (responseAPDU.getTrailer()[0] == (byte) 0x61) {
        CardCommandAPDU getResponseData = new CardCommandAPDU((byte) 0x00, (byte) 0xC0, (byte) 0x00, (byte) 0x00, responseAPDU.getTrailer()[1]);
        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;
    }
    // fix output format
    String outForm = cryptoMarker.getLegacyOutputFormat();
    if (outForm != null) {
        switch(outForm) {
            case "rawRS":
                signedMessage = encodeRawRS(signedMessage);
                break;
            default:
                LOG.warn("Unsupport outputFormat={} specified in LegacySignatureGenerationInfo.", outForm);
        }
    }
    response.setSignature(signedMessage);
    return response;
}
Also used : CardCommandAPDU(org.openecard.common.apdu.common.CardCommandAPDU) CardCallTemplateType(iso.std.iso_iec._24727.tech.schema.CardCallTemplateType) SignResponse(iso.std.iso_iec._24727.tech.schema.SignResponse) CardResponseAPDU(org.openecard.common.apdu.common.CardResponseAPDU) CardCommandTemplate(org.openecard.common.apdu.common.CardCommandTemplate) APICommand(iso.std.iso_iec._24727.tech.schema.LegacySignatureGenerationType.APICommand)

Example 5 with SignResponse

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

the class TinySALTest method testSign.

/**
 * Test of sign method, of class TinySAL.
 */
@Test(enabled = TESTS_ENABLED)
public void testSign() {
    System.out.println("sign");
    Sign parameters = new Sign();
    SignResponse result = instance.sign(parameters);
    assertEquals(ECardConstants.Major.ERROR, result.getResult().getResultMajor());
}
Also used : SignResponse(iso.std.iso_iec._24727.tech.schema.SignResponse) Sign(iso.std.iso_iec._24727.tech.schema.Sign) Test(org.testng.annotations.Test)

Aggregations

SignResponse (iso.std.iso_iec._24727.tech.schema.SignResponse)9 Sign (iso.std.iso_iec._24727.tech.schema.Sign)4 IncorrectParameterException (org.openecard.common.sal.exception.IncorrectParameterException)4 ConnectionHandleType (iso.std.iso_iec._24727.tech.schema.ConnectionHandleType)3 DIDStructureType (iso.std.iso_iec._24727.tech.schema.DIDStructureType)3 ECardException (org.openecard.common.ECardException)3 CardStateEntry (org.openecard.common.sal.state.CardStateEntry)3 Test (org.testng.annotations.Test)3 CardApplicationConnect (iso.std.iso_iec._24727.tech.schema.CardApplicationConnect)2 CardApplicationConnectResponse (iso.std.iso_iec._24727.tech.schema.CardApplicationConnectResponse)2 CardApplicationPath (iso.std.iso_iec._24727.tech.schema.CardApplicationPath)2 CardApplicationPathResponse (iso.std.iso_iec._24727.tech.schema.CardApplicationPathResponse)2 CardAppPathResultSet (iso.std.iso_iec._24727.tech.schema.CardApplicationPathResponse.CardAppPathResultSet)2 CardApplicationPathType (iso.std.iso_iec._24727.tech.schema.CardApplicationPathType)2 CryptoMarkerType (iso.std.iso_iec._24727.tech.schema.CryptoMarkerType)2 DIDAuthenticate (iso.std.iso_iec._24727.tech.schema.DIDAuthenticate)2 DIDAuthenticateResponse (iso.std.iso_iec._24727.tech.schema.DIDAuthenticateResponse)2 DIDGet (iso.std.iso_iec._24727.tech.schema.DIDGet)2 DIDGetResponse (iso.std.iso_iec._24727.tech.schema.DIDGetResponse)2 DIDList (iso.std.iso_iec._24727.tech.schema.DIDList)2