Search in sources :

Example 16 with TLV

use of org.openecard.common.tlv.TLV in project open-ecard by ecsec.

the class TinySAL method createFakeFCP.

private byte[] createFakeFCP(byte[] fid) {
    try {
        TLV fcp = new TLV();
        fcp.setTagNumWithClass((byte) 0x62);
        TLV fileID = new TLV();
        fileID.setTagNumWithClass((byte) 0x83);
        fileID.setValue(fid);
        fcp.setChild(fileID);
        return fcp.toBER();
    } catch (TLVException ex) {
        LOG.error(null, ex);
        return null;
    }
}
Also used : TLVException(org.openecard.common.tlv.TLVException) TLV(org.openecard.common.tlv.TLV)

Example 17 with TLV

use of org.openecard.common.tlv.TLV in project open-ecard by ecsec.

the class SecureMessaging method encrypt.

/**
 * Encrypt the APDU.
 *
 * @param apdu APDU
 * @param secureMessagingSSC Secure Messaging Send Sequence Counter
 * @return Encrypted APDU
 * @throws Exception
 */
private byte[] encrypt(byte[] apdu, byte[] secureMessagingSSC) throws Exception {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    CardCommandAPDU cAPDU = new CardCommandAPDU(apdu);
    if (cAPDU.isSecureMessaging()) {
        throw new IllegalArgumentException("Malformed APDU.");
    }
    byte[] data = cAPDU.getData();
    byte[] header = cAPDU.getHeader();
    int lc = cAPDU.getLC();
    int le = cAPDU.getLE();
    if (data.length > 0) {
        data = pad(data, 16);
        // Encrypt data
        Cipher c = getCipher(secureMessagingSSC, Cipher.ENCRYPT_MODE);
        byte[] dataEncrypted = c.doFinal(data);
        // Add padding indicator 0x01
        dataEncrypted = ByteUtils.concatenate((byte) 0x01, dataEncrypted);
        TLV dataObject = new TLV();
        dataObject.setTagNumWithClass((byte) 0x87);
        dataObject.setValue(dataEncrypted);
        baos.write(dataObject.toBER());
    }
    // Write protected LE
    if (le >= 0) {
        TLV leObject = new TLV();
        leObject.setTagNumWithClass((byte) 0x97);
        if (le == 0x100) {
            leObject.setValue(NULL);
        } else if (le > 0x100) {
            leObject.setValue(new byte[] { (byte) ((le >> 8) & 0xFF), (byte) (le & 0xFF) });
        } else {
            leObject.setValue(new byte[] { (byte) le });
        }
        baos.write(leObject.toBER());
    }
    // Indicate Secure Messaging
    // note: must be done before mac calculation
    header[0] |= 0x0C;
    /*
	 * Calculate MAC
	 */
    byte[] mac = new byte[16];
    CMac cmac = getCMAC(secureMessagingSSC);
    byte[] paddedHeader = pad(header, 16);
    cmac.update(paddedHeader, 0, paddedHeader.length);
    if (baos.size() > 0) {
        byte[] paddedData = pad(baos.toByteArray(), 16);
        cmac.update(paddedData, 0, paddedData.length);
    }
    cmac.doFinal(mac, 0);
    mac = ByteUtils.copy(mac, 0, 8);
    // 
    // Build APDU
    TLV macStructure = new TLV();
    macStructure.setTagNumWithClass((byte) 0x8E);
    macStructure.setValue(mac);
    byte[] secureData = ByteUtils.concatenate(baos.toByteArray(), macStructure.toBER());
    CardCommandAPDU secureCommand = new CardCommandAPDU(header[0], header[1], header[2], header[3], secureData);
    // set LE explicitely to 0x00 or in case of extended length 0x00 0x00
    if ((lc > 0xFF) || (le > 0x100)) {
        secureCommand.setLE(65536);
    } else {
        secureCommand.setLE(256);
    }
    return secureCommand.toByteArray();
}
Also used : CardCommandAPDU(org.openecard.common.apdu.common.CardCommandAPDU) CMac(org.openecard.bouncycastle.crypto.macs.CMac) ByteArrayOutputStream(java.io.ByteArrayOutputStream) Cipher(javax.crypto.Cipher) TLV(org.openecard.common.tlv.TLV)

Example 18 with TLV

use of org.openecard.common.tlv.TLV in project open-ecard by ecsec.

the class DecipherStep method perform.

@Override
public DecipherResponse perform(Decipher request, Map<String, Object> internalData) {
    DecipherResponse response = WSHelper.makeResponse(DecipherResponse.class, WSHelper.makeResultOK());
    try {
        ConnectionHandleType connectionHandle = SALUtils.getConnectionHandle(request);
        String didName = SALUtils.getDIDName(request);
        byte[] applicationID = connectionHandle.getCardApplication();
        CardStateEntry cardStateEntry = SALUtils.getCardStateEntry(internalData, connectionHandle);
        Assert.securityConditionDID(cardStateEntry, applicationID, didName, CryptographicServiceActionName.DECIPHER);
        DIDStructureType didStructure = SALUtils.getDIDStructure(request, didName, cardStateEntry, connectionHandle);
        CryptoMarkerType cryptoMarker = new CryptoMarkerType(didStructure.getDIDMarker());
        byte[] keyReference = cryptoMarker.getCryptoKeyInfo().getKeyRef().getKeyRef();
        byte[] algorithmIdentifier = cryptoMarker.getAlgorithmInfo().getCardAlgRef();
        byte[] slotHandle = connectionHandle.getSlotHandle();
        // See eGK specification, part 1, version 2.2.0, section 15.9.6.
        if (didStructure.getDIDScope().equals(DIDScopeType.LOCAL)) {
            keyReference[0] = (byte) (0x80 | keyReference[0]);
        }
        TLV tagKeyReference = new TLV();
        tagKeyReference.setTagNumWithClass(0x84);
        tagKeyReference.setValue(keyReference);
        TLV tagAlgorithmIdentifier = new TLV();
        tagAlgorithmIdentifier.setTagNumWithClass(0x80);
        tagAlgorithmIdentifier.setValue(algorithmIdentifier);
        byte[] mseData = ByteUtils.concatenate(tagKeyReference.toBER(), tagAlgorithmIdentifier.toBER());
        CardCommandAPDU apdu = new ManageSecurityEnvironment((byte) 0x41, ManageSecurityEnvironment.CT, mseData);
        apdu.transmit(dispatcher, slotHandle);
        byte[] ciphertext = request.getCipherText();
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        BigInteger bitKeySize = cryptoMarker.getCryptoKeyInfo().getKeySize();
        int blocksize = bitKeySize.divide(new BigInteger("8")).intValue();
        // check if the ciphertext length is divisible by the blocksize without rest
        if ((ciphertext.length % blocksize) != 0) {
            return WSHelper.makeResponse(DecipherResponse.class, WSHelper.makeResultError(ECardConstants.Minor.App.INCORRECT_PARM, "The length of the ciphertext should be a multiple of the blocksize."));
        }
        // decrypt the ciphertext block for block
        for (int offset = 0; offset < ciphertext.length; offset += blocksize) {
            byte[] ciphertextblock = ByteUtils.copy(ciphertext, offset, blocksize);
            apdu = new PSODecipher(ByteUtils.concatenate(PADDING_INDICATOR_BYTE, ciphertextblock), (byte) blocksize);
            CardResponseAPDU responseAPDU = apdu.transmit(dispatcher, slotHandle);
            baos.write(responseAPDU.getData());
        }
        response.setPlainText(baos.toByteArray());
    } catch (ECardException e) {
        response.setResult(e.getResult());
    } catch (Exception e) {
        logger.error(e.getMessage(), e);
        response.setResult(WSHelper.makeResult(e));
    }
    return response;
}
Also used : ConnectionHandleType(iso.std.iso_iec._24727.tech.schema.ConnectionHandleType) CardCommandAPDU(org.openecard.common.apdu.common.CardCommandAPDU) CardStateEntry(org.openecard.common.sal.state.CardStateEntry) CryptoMarkerType(org.openecard.crypto.common.sal.did.CryptoMarkerType) ByteArrayOutputStream(java.io.ByteArrayOutputStream) PSODecipher(org.openecard.sal.protocol.genericcryptography.apdu.PSODecipher) ECardException(org.openecard.common.ECardException) ECardException(org.openecard.common.ECardException) BigInteger(java.math.BigInteger) DecipherResponse(iso.std.iso_iec._24727.tech.schema.DecipherResponse) DIDStructureType(iso.std.iso_iec._24727.tech.schema.DIDStructureType) CardResponseAPDU(org.openecard.common.apdu.common.CardResponseAPDU) ManageSecurityEnvironment(org.openecard.common.apdu.ManageSecurityEnvironment) TLV(org.openecard.common.tlv.TLV)

Example 19 with TLV

use of org.openecard.common.tlv.TLV in project open-ecard by ecsec.

the class AuthenticationHelper method performAuth.

public EAC2OutputType performAuth(EAC2OutputType eac2Output, Map<String, Object> internalData) throws ProtocolException, TLVException {
    // get needed values from context
    CardVerifiableCertificate terminalCertificate;
    terminalCertificate = (CardVerifiableCertificate) internalData.get(EACConstants.IDATA_TERMINAL_CERTIFICATE);
    byte[] key = (byte[]) internalData.get(EACConstants.IDATA_PK_PCD);
    byte[] signature = (byte[]) internalData.get(EACConstants.IDATA_SIGNATURE);
    SecurityInfos securityInfos = (SecurityInfos) internalData.get(EACConstants.IDATA_SECURITY_INFOS);
    AuthenticatedAuxiliaryData aadObj;
    aadObj = (AuthenticatedAuxiliaryData) internalData.get(EACConstants.IDATA_AUTHENTICATED_AUXILIARY_DATA);
    // ///////////////////////////////////////////////////////////////////
    // BEGIN TA PART
    // ///////////////////////////////////////////////////////////////////
    // TA: Step 2 - MSE:SET AT
    byte[] oid = ObjectIdentifierUtils.getValue(terminalCertificate.getPublicKey().getObjectIdentifier());
    byte[] chr = terminalCertificate.getCHR().toByteArray();
    byte[] aad = aadObj.getData();
    // Calculate comp(key)
    EFCardAccess efca = new EFCardAccess(securityInfos);
    CASecurityInfos cas = efca.getCASecurityInfos();
    CADomainParameter cdp = new CADomainParameter(cas);
    CAKey caKey = new CAKey(cdp);
    caKey.decodePublicKey(key);
    byte[] compKey = caKey.getEncodedCompressedPublicKey();
    // TA: Step 4 - MSE SET AT
    ta.mseSetAT(oid, chr, compKey, aad);
    // TA: Step 4 - External Authentication
    ta.externalAuthentication(signature);
    // ///////////////////////////////////////////////////////////////////
    // END TA PART
    // ///////////////////////////////////////////////////////////////////
    // ///////////////////////////////////////////////////////////////////
    // BEGIN CA PART
    // ///////////////////////////////////////////////////////////////////
    // Read EF.CardSecurity
    byte[] efCardSecurity = ca.readEFCardSecurity();
    // CA: Step 1 - MSE:SET AT
    byte[] oID = ObjectIdentifierUtils.getValue(cas.getCAInfo().getProtocol());
    byte[] keyID = IntegerUtils.toByteArray(cas.getCAInfo().getKeyID());
    ca.mseSetAT(oID, keyID);
    // CA: Step 2 - General Authenticate
    byte[] responseData = ca.generalAuthenticate(key);
    TLV tlv = TLV.fromBER(responseData);
    byte[] nonce = tlv.findChildTags(0x81).get(0).getValue();
    byte[] token = tlv.findChildTags(0x82).get(0).getValue();
    // Disable Secure Messaging
    ca.destroySecureChannel();
    // ///////////////////////////////////////////////////////////////////
    // END CA PART
    // ///////////////////////////////////////////////////////////////////
    // Create response
    eac2Output.setEFCardSecurity(efCardSecurity);
    eac2Output.setNonce(nonce);
    eac2Output.setToken(token);
    return eac2Output;
}
Also used : CADomainParameter(org.openecard.crypto.common.asn1.eac.CADomainParameter) AuthenticatedAuxiliaryData(org.openecard.crypto.common.asn1.eac.AuthenticatedAuxiliaryData) CardVerifiableCertificate(org.openecard.crypto.common.asn1.cvc.CardVerifiableCertificate) EFCardAccess(org.openecard.crypto.common.asn1.eac.ef.EFCardAccess) CASecurityInfos(org.openecard.crypto.common.asn1.eac.CASecurityInfos) SecurityInfos(org.openecard.crypto.common.asn1.eac.SecurityInfos) CASecurityInfos(org.openecard.crypto.common.asn1.eac.CASecurityInfos) CAKey(org.openecard.sal.protocol.eac.crypto.CAKey) TLV(org.openecard.common.tlv.TLV)

Example 20 with TLV

use of org.openecard.common.tlv.TLV in project open-ecard by ecsec.

the class EF_ODTest method readEF_OD.

@Test
public void readEF_OD() throws TLVException, IOException {
    TLV tlv = ReadHelper.readCIAFile("EF_OD.bin");
    EF_OD od = new EF_OD(tlv);
}
Also used : TLV(org.openecard.common.tlv.TLV) Test(org.testng.annotations.Test)

Aggregations

TLV (org.openecard.common.tlv.TLV)21 Test (org.testng.annotations.Test)5 ByteArrayOutputStream (java.io.ByteArrayOutputStream)4 GeneralSecurityException (java.security.GeneralSecurityException)3 CardCommandAPDU (org.openecard.common.apdu.common.CardCommandAPDU)3 TLVException (org.openecard.common.tlv.TLVException)3 BigInteger (java.math.BigInteger)2 Cipher (javax.crypto.Cipher)2 CMac (org.openecard.bouncycastle.crypto.macs.CMac)2 ManageSecurityEnvironment (org.openecard.common.apdu.ManageSecurityEnvironment)2 CardResponseAPDU (org.openecard.common.apdu.common.CardResponseAPDU)2 ConnectionHandleType (iso.std.iso_iec._24727.tech.schema.ConnectionHandleType)1 DIDStructureType (iso.std.iso_iec._24727.tech.schema.DIDStructureType)1 DataMaskType (iso.std.iso_iec._24727.tech.schema.DataMaskType)1 DecipherResponse (iso.std.iso_iec._24727.tech.schema.DecipherResponse)1 SignResponse (iso.std.iso_iec._24727.tech.schema.SignResponse)1 ByteArrayInputStream (java.io.ByteArrayInputStream)1 IOException (java.io.IOException)1 InputStream (java.io.InputStream)1 MessageDigest (java.security.MessageDigest)1