use of iso.std.iso_iec._24727.tech.schema.Decipher in project open-ecard by ecsec.
the class TinySAL method decipher.
/**
* The Decipher function decrypts a given cipher text. The detailed behaviour of this function depends on
* the protocol of the DID.
* See BSI-TR-03112-4, version 1.1.2, section 3.5.2.
*
* @param request Decipher
* @return DecipherResponse
*/
@Override
public DecipherResponse decipher(Decipher request) {
DecipherResponse response = WSHelper.makeResponse(DecipherResponse.class, WSHelper.makeResultOK());
try {
ConnectionHandleType connectionHandle = SALUtils.getConnectionHandle(request);
CardStateEntry cardStateEntry = SALUtils.getCardStateEntry(states, connectionHandle, false);
byte[] applicationID = cardStateEntry.getCurrentCardApplication().getApplicationIdentifier();
String didName = SALUtils.getDIDName(request);
byte[] cipherText = request.getCipherText();
Assert.assertIncorrectParameter(cipherText, "The parameter CipherText is empty.");
DIDScopeType didScope = request.getDIDScope();
if (didScope == null) {
didScope = DIDScopeType.LOCAL;
}
if (didScope.equals(DIDScopeType.LOCAL)) {
byte[] necessaryCardApp = cardStateEntry.getInfo().getApplicationIdByDidName(didName, didScope);
if (!Arrays.equals(necessaryCardApp, applicationID)) {
throw new SecurityConditionNotSatisfiedException("Wrong application selected.");
}
}
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.Decipher)) {
response = protocol.decipher(request);
removeFinishedProtocol(connectionHandle, protocolURI, protocol);
} else {
throw new InappropriateProtocolForActionException("Decipher", protocol.toString());
}
} catch (ECardException e) {
response.setResult(e.getResult());
} catch (Exception e) {
LOG.error(e.getMessage(), e);
throwThreadKillException(e);
response.setResult(WSHelper.makeResult(e));
}
return response;
}
use of iso.std.iso_iec._24727.tech.schema.Decipher in project open-ecard by ecsec.
the class PINCompareProtocolTest method testUnsupportedFunctions.
/*
* [TR-03112-7] The following functions are not supported with this protocol
* and, when called up, relay an error message to this effect
* /resultminor/sal#inappropriateProtocolForAction:
* CardApplicationStartSession, Encipher, Decipher, GetRandom, Hash, Sign,
* VerifySignature, VerifyCertificate
*/
/**
* This Test ensures that all functions unsupported by this protocol relay the correct error message when
* called.
*/
@Test(enabled = TESTS_ENABLED)
public void testUnsupportedFunctions() {
CardApplicationPath cardApplicationPath = new CardApplicationPath();
CardApplicationPathType cardApplicationPathType = new CardApplicationPathType();
cardApplicationPathType.setCardApplication(this.appIdentifier_ROOT);
cardApplicationPath.setCardAppPathRequest(cardApplicationPathType);
CardApplicationPathResponse cardApplicationPathResponse = instance.cardApplicationPath(cardApplicationPath);
CardApplicationConnect cardApplicationConnect = new CardApplicationConnect();
cardApplicationPathType = cardApplicationPathResponse.getCardAppPathResultSet().getCardApplicationPathResult().get(0);
cardApplicationConnect.setCardApplicationPath(cardApplicationPathType);
CardApplicationConnectResponse result1 = instance.cardApplicationConnect(cardApplicationConnect);
Encipher encipher = new Encipher();
encipher.setDIDName("PIN.home");
encipher.setPlainText(new byte[] { 0x0, 0x0, 0x0 });
encipher.setConnectionHandle(result1.getConnectionHandle());
EncipherResponse encipherResponse = instance.encipher(encipher);
assertEquals(encipherResponse.getResult().getResultMajor(), ECardConstants.Major.ERROR);
assertEquals(encipherResponse.getResult().getResultMinor(), ECardConstants.Minor.SAL.INAPPROPRIATE_PROTOCOL_FOR_ACTION);
// TODO remaining unsupported functions
}
use of iso.std.iso_iec._24727.tech.schema.Decipher in project open-ecard by ecsec.
the class GenericCryptographyProtocolTest method testDecipher.
/**
* Test for the Decipher Step of the Generic Cryptography protocol. After we connected to the ESIGN application
* of the eGK, we use DIDList to get a List of DIDs that support the Decipher function. We then authenticate with
* PIN.home and read the contents of the DIDs certificate. With it's public key we encrypt the contents of
* plaintext.txt and finally let the card decrypt it through a call to Decipher. In the end we match the result with
* the original plaintext.
*
* @throws Exception when something in this test went unexpectedly wrong
*/
@Test(enabled = TESTS_ENABLED)
public void testDecipher() throws Exception {
CardApplicationPath cardApplicationPath = new CardApplicationPath();
CardApplicationPathType cardApplicationPathType = new CardApplicationPathType();
cardApplicationPathType.setCardApplication(cardApplication);
cardApplicationPath.setCardAppPathRequest(cardApplicationPathType);
CardApplicationPathResponse cardApplicationPathResponse = instance.cardApplicationPath(cardApplicationPath);
WSHelper.checkResult(cardApplicationPathResponse);
CardApplicationConnect parameters = new CardApplicationConnect();
CardAppPathResultSet cardAppPathResultSet = cardApplicationPathResponse.getCardAppPathResultSet();
parameters.setCardApplicationPath(cardAppPathResultSet.getCardApplicationPathResult().get(0));
CardApplicationConnectResponse result = instance.cardApplicationConnect(parameters);
WSHelper.checkResult(result);
assertEquals(ECardConstants.Major.OK, result.getResult().getResultMajor());
DIDList didList = new DIDList();
didList.setConnectionHandle(result.getConnectionHandle());
DIDQualifierType didQualifier = new DIDQualifierType();
didQualifier.setApplicationIdentifier(cardApplication);
didQualifier.setObjectIdentifier(ECardConstants.Protocol.GENERIC_CRYPTO);
didQualifier.setApplicationFunction("Decipher");
didList.setFilter(didQualifier);
DIDListResponse didListResponse = instance.didList(didList);
assertTrue(didListResponse.getDIDNameList().getDIDName().size() > 0);
WSHelper.checkResult(didListResponse);
DIDAuthenticate didAthenticate = new DIDAuthenticate();
didAthenticate.setDIDName("PIN.home");
PinCompareDIDAuthenticateInputType didAuthenticationData = new PinCompareDIDAuthenticateInputType();
didAthenticate.setAuthenticationProtocolData(didAuthenticationData);
didAthenticate.setConnectionHandle(result.getConnectionHandle());
didAthenticate.getConnectionHandle().setCardApplication(cardApplication_ROOT);
didAuthenticationData.setProtocol(ECardConstants.Protocol.PIN_COMPARE);
didAthenticate.setAuthenticationProtocolData(didAuthenticationData);
DIDAuthenticateResponse didAuthenticateResult = instance.didAuthenticate(didAthenticate);
WSHelper.checkResult(didAuthenticateResult);
assertEquals(didAuthenticateResult.getAuthenticationProtocolData().getProtocol(), ECardConstants.Protocol.PIN_COMPARE);
assertEquals(didAuthenticateResult.getAuthenticationProtocolData().getAny().size(), 0);
assertEquals(ECardConstants.Major.OK, didAuthenticateResult.getResult().getResultMajor());
byte[] plaintextBytes = plaintext.getBytes();
for (int numOfDIDs = 0; numOfDIDs < didListResponse.getDIDNameList().getDIDName().size(); numOfDIDs++) {
String didName = didListResponse.getDIDNameList().getDIDName().get(numOfDIDs);
DIDGet didGet = new DIDGet();
didGet.setDIDName(didName);
didGet.setDIDScope(DIDScopeType.LOCAL);
didGet.setConnectionHandle(result.getConnectionHandle());
didGet.getConnectionHandle().setCardApplication(cardApplication);
DIDGetResponse didGetResponse = instance.didGet(didGet);
org.openecard.crypto.common.sal.did.CryptoMarkerType cryptoMarker = new org.openecard.crypto.common.sal.did.CryptoMarkerType((CryptoMarkerType) didGetResponse.getDIDStructure().getDIDMarker());
ByteArrayOutputStream ciphertext = new ByteArrayOutputStream();
// read the certificate
DSIRead dsiRead = new DSIRead();
dsiRead.setConnectionHandle(result.getConnectionHandle());
dsiRead.getConnectionHandle().setCardApplication(cardApplication);
dsiRead.setDSIName(cryptoMarker.getCertificateRefs().get(0).getDataSetName());
DSIReadResponse dsiReadResponse = instance.dsiRead(dsiRead);
assertEquals(ECardConstants.Major.OK, dsiReadResponse.getResult().getResultMajor());
assertTrue(dsiReadResponse.getDSIContent().length > 0);
// convert the contents to a certificate
Certificate cert = (X509Certificate) CertificateFactory.getInstance("X.509").generateCertificate(new ByteArrayInputStream(dsiReadResponse.getDSIContent()));
Cipher cipher;
int blocksize;
String algorithmUri = cryptoMarker.getAlgorithmInfo().getAlgorithmIdentifier().getAlgorithm();
if (algorithmUri.equals(GenericCryptoUris.RSA_ENCRYPTION)) {
cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
cipher.init(Cipher.ENCRYPT_MODE, cert);
// keysize/8-pkcspadding = (2048)/8-11
blocksize = 245;
} else if (algorithmUri.equals(GenericCryptoUris.RSAES_OAEP)) {
cipher = Cipher.getInstance("RSA/ECB/OAEPWithSHA-256AndMGF1Padding", new BouncyCastleProvider());
cipher.init(Cipher.ENCRYPT_MODE, cert);
blocksize = cipher.getBlockSize();
} else {
LOG.warn("Skipping decipher for the unsupported algorithmOID: {}", algorithmUri);
continue;
}
int rest = plaintextBytes.length % blocksize;
// encrypt block for block
for (int offset = 0; offset < plaintextBytes.length; offset += blocksize) {
if ((offset + blocksize) > plaintextBytes.length) {
ciphertext.write(cipher.doFinal(plaintextBytes, offset, rest));
} else {
ciphertext.write(cipher.doFinal(plaintextBytes, offset, blocksize));
}
}
Decipher decipher = new Decipher();
decipher.setCipherText(ciphertext.toByteArray());
decipher.setConnectionHandle(result.getConnectionHandle());
decipher.getConnectionHandle().setCardApplication(cardApplication);
decipher.setDIDName(didName);
decipher.setDIDScope(DIDScopeType.LOCAL);
DecipherResponse decipherResponse = instance.decipher(decipher);
assertEquals(decipherResponse.getPlainText(), plaintextBytes);
// test invalid ciphertext length (not divisible through blocksize without rest)
decipher = new Decipher();
decipher.setCipherText(ByteUtils.concatenate((byte) 0x00, ciphertext.toByteArray()));
decipher.setConnectionHandle(result.getConnectionHandle());
decipher.getConnectionHandle().setCardApplication(cardApplication);
decipher.setDIDName(didName);
decipher.setDIDScope(DIDScopeType.LOCAL);
decipherResponse = instance.decipher(decipher);
Result res = decipherResponse.getResult();
assertEquals(res.getResultMajor(), ECardConstants.Major.ERROR);
assertEquals(res.getResultMinor(), ECardConstants.Minor.App.INCORRECT_PARM);
}
}
use of iso.std.iso_iec._24727.tech.schema.Decipher in project open-ecard by ecsec.
the class TinySALTest method testDecipher.
/**
* Test of decipher method, of class TinySAL.
*/
@Test(enabled = TESTS_ENABLED)
public void testDecipher() {
System.out.println("decipher");
Decipher parameters = new Decipher();
DecipherResponse result = instance.decipher(parameters);
assertEquals(ECardConstants.Major.ERROR, result.getResult().getResultMajor());
}
use of iso.std.iso_iec._24727.tech.schema.Decipher 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;
}
Aggregations