@Test public void testVerify() throws Exception { Signer signer = new Signer(createStringSignerSecretProvider()); String t = "test"; String s = signer.sign(t); String e = signer.verifyAndExtract(s); Assert.assertEquals(t, e); }
@Test public void testSignature() throws Exception { Signer signer = new Signer(createStringSignerSecretProvider()); String s1 = signer.sign("ok"); String s2 = signer.sign("ok"); String s3 = signer.sign("wrong"); Assert.assertEquals(s1, s2); Assert.assertNotEquals(s1, s3); }
@Test public void testMultipleSecrets() throws Exception { TestSignerSecretProvider secretProvider = new TestSignerSecretProvider(); Signer signer = new Signer(secretProvider); secretProvider.setCurrentSecret("secretB"); String t1 = "test"; String s1 = signer.sign(t1); String e1 = signer.verifyAndExtract(s1); Assert.assertEquals(t1, e1); secretProvider.setPreviousSecret("secretA"); String t2 = "test"; String s2 = signer.sign(t2); String e2 = signer.verifyAndExtract(s2); Assert.assertEquals(t2, e2); Assert.assertEquals(s1, s2); // check is using current secret for signing secretProvider.setCurrentSecret("secretC"); secretProvider.setPreviousSecret("secretB"); String t3 = "test"; String s3 = signer.sign(t3); String e3 = signer.verifyAndExtract(s3); Assert.assertEquals(t3, e3); Assert.assertNotEquals(s1, s3); // check not using current secret for signing String e1b = signer.verifyAndExtract(s1); Assert.assertEquals(t1, e1b); // previous secret still valid secretProvider.setCurrentSecret("secretD"); secretProvider.setPreviousSecret("secretC"); try { signer.verifyAndExtract(s1); // previous secret no longer valid Assert.fail(); } catch (SignerException ex) { // Expected } }
@Test public void testInvalidSignedText() throws Exception { Signer signer = new Signer(createStringSignerSecretProvider()); try { signer.verifyAndExtract("test"); Assert.fail(); } catch (SignerException ex) { // Expected } catch (Throwable ex) { Assert.fail(); } }
@Test public void testTampering() throws Exception { Signer signer = new Signer(createStringSignerSecretProvider()); String t = "test"; String s = signer.sign(t); s += "x"; try { signer.verifyAndExtract(s); Assert.fail(); } catch (SignerException ex) { // Expected } catch (Throwable ex) { Assert.fail(); } }
@Override public ResponseMessage execute() { SessionManager sm = sessionManager; Session session = sm.getSession(sessionHandler); if (session == null) { return ResponseMessage.ErrorMessage("Bad session handler."); } Signer signer = session.getSigner(); try { signer.init(this.mechanism, this.privateKeyHandler); return ResponseMessage.OKMessage(); } catch (Exception e) { return ResponseMessage.ErrorMessage(e.getLocalizedMessage()); } }
/** * Test scenario taken from, https://tools.ietf.org/html/rfc7515#appendix-A.1 * * <p>There is a modification in which the sign input does not contain \r\n Which is why the * signature is different than the rfc. */ @Test public void shouldSignBytesCorrectly() { String input = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9." + "eyJpc3MiOiJqb2UiLCJleHAiOjEzMDA4MTkzODAsImh0dHA6Ly9leGFtcGxlLmNvbS9pc19yb290Ijp0cnVlfQ"; String actual = subject.run(input.getBytes()); assertThat(actual, is("lliDzOlRAdGUCfCHCPx_uisb6ZfZ1LRQa0OJLeYTTpY")); }
@Test public void testNullAndEmptyString() throws Exception { Signer signer = new Signer(createStringSignerSecretProvider()); try { signer.sign(null); Assert.fail(); } catch (IllegalArgumentException ex) { // Expected } catch (Throwable ex) { Assert.fail(); } try { signer.sign(""); Assert.fail(); } catch (IllegalArgumentException ex) { // Expected } catch (Throwable ex) { Assert.fail(); } }
@Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (obj instanceof Signer == false) return false; Signer other = (Signer) obj; if (other.getAwsAccountNumber() == null ^ this.getAwsAccountNumber() == null) return false; if (other.getAwsAccountNumber() != null && other.getAwsAccountNumber().equals(this.getAwsAccountNumber()) == false) return false; if (other.getSelf() == null ^ this.getSelf() == null) return false; if (other.getSelf() != null && other.getSelf().equals(this.getSelf()) == false) return false; if (other.getKeyPairIds() == null ^ this.getKeyPairIds() == null) return false; if (other.getKeyPairIds() != null && other.getKeyPairIds().equals(this.getKeyPairIds()) == false) return false; return true; }
/** * Test scenario taken from, https://tools.ietf.org/html/rfc7515#appendix-A.1 * * <p>There is a modification in which the sign input does not contain \r\n Which is why the * signature is different than the rfc. */ @Test public void shouldSignJwtCorrectly() throws JwtToJsonException { // header Header header = new Header(); header.setAlgorithm(Algorithm.HS256); header.setType(Optional.of(TokenType.JWT)); // claim of the jwt. Claim claim = new Claim(); Optional<String> issuer = Optional.of("joe"); Optional<Long> expirationTime = Optional.of(1300819380L); claim.setUriIsRoot(true); claim.setIssuer(issuer); claim.setExpirationTime(expirationTime); JsonWebToken jwt = new JsonWebToken(header, claim); String actual = subject.run(jwt); assertThat(actual, is("lliDzOlRAdGUCfCHCPx_uisb6ZfZ1LRQa0OJLeYTTpY")); }
public void signRequest(SignedService request) { signer.sign(request, accessToken); }
// // обработка исходящего каталога АБС // public boolean processOutDirectory() { boolean result = true; try { // // читаем control.xml // File controlFile = new File(ABS_OUTPUT_DIR + "/control.xml"); if (!controlFile.exists()) { logger.error("Нет файла " + controlFile.getName()); if (new File(ABS_OUTPUT_DIR + "/control.zip").exists()) { logger.info("Обнаружен архив " + ABS_OUTPUT_DIR + "/control.zip"); return true; } return false; } DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); Document controlDoc = builder.parse(controlFile); // готовимся изменять файл XPath searchPath = XPathFactory.newInstance().newXPath(); // ищем каталоги с контейнерами File[] directoryList = (new File(ABS_OUTPUT_DIR)).listFiles(p -> p.isDirectory()); // // просматриваем каталоги типа FILES/out/.... // for (int i = 0; i < directoryList.length; i++) { // // в каталоге должен быть файл data.zip и файлы-вложения // файл data.zip нужно подписать и зазиповать // logger.info("Обрабатываем каталог " + directoryList[i].getAbsolutePath()); // // просматриваем содержимое каталога с контейнером // File[] currentDir = (directoryList[i]).listFiles(p -> p.isFile()); // // создаем zip-file // File zip = new File(directoryList[i].getAbsolutePath() + "/data_" + i + ".zip"); logger.info("Создаем архив " + zip.getAbsolutePath()); FileOutputStream zipStream = new FileOutputStream(zip); ZipOutputStream dataZip = new ZipOutputStream(zipStream); for (File curFile : currentDir) { if ("data.xml.sig".equals(curFile.getName())) continue; appendZipFile(dataZip, curFile); // // для файла data.zip создаем цифровую подпись и записываем файл с подписью в архив // if ("data.xml".equals(curFile.getName())) { fileSigner.cades(curFile.getAbsolutePath()); String fName = curFile.getAbsolutePath(); File signFile = new File(fName.substring(0, fName.length() - 3) + "sign"); appendZipFile(dataZip, signFile); signFile.delete(); } // // удаляем файл после включения в архив // curFile.delete(); } // // закрываем архив и его поток // dataZip.close(); zipStream.close(); logger.info("Запись в архив " + zip.getAbsolutePath() + " завершена"); // // вычисляем crc32 // long crc32 = Utils.calculateCRC32(zip); long zipSize = zip.length(); // // в файле control.xml ищем соответствующий узел контейнера и меняем его атрибуты // String xpathQuery = "//Containers[@ReqUID='" + directoryList[i].getName() + "']"; Node containerNode = (Node) searchPath.evaluate(xpathQuery, controlDoc, XPathConstants.NODE); if (containerNode == null) { logger.error( "В файле control.xml не найдено описание для контейнера " + directoryList[i].getName()); System.exit(1); } Element containerElement = (Element) containerNode; containerElement.setAttribute("name", zip.getName()); containerElement.setAttribute("size", zipSize + ""); containerElement.setAttribute("CRC", crc32 + ""); } // сохраняем control.xml DOMSource domSource = new DOMSource(controlDoc); StreamResult streamResult = new StreamResult(controlFile); Transformer transformer = TransformerFactory.newInstance().newTransformer(); transformer.transform(domSource, streamResult); transformer.reset(); // // подписываем файл // fileSigner.cades(controlFile.getAbsolutePath()); // // записываем файл control.xml и подпись в архив // File zip = new File(ABS_OUTPUT_DIR + "/control.zip"); logger.info("Создаем архив " + zip.getAbsolutePath()); FileOutputStream zipStream = new FileOutputStream(zip); ZipOutputStream dataZip = new ZipOutputStream(zipStream); // // дописываем управляющий файл // File cFile = new File(ABS_OUTPUT_DIR + "/control.xml"); appendZipFile(dataZip, cFile); cFile.delete(); // // дописываем подпись // cFile = new File(ABS_OUTPUT_DIR + "/control.sign"); appendZipFile(dataZip, cFile); cFile.delete(); logger.info("Запись в архив " + zip.getAbsolutePath() + " завершена"); // // закрываем архив и его поток // dataZip.close(); zipStream.close(); } catch (Exception e) { logger.error(e.getMessage()); e.printStackTrace(); } return result; }
@Test public void verifyResult() { BasicPackageCreationExample basicPackageCreationExample = new BasicPackageCreationExample(Props.get()); basicPackageCreationExample.run(); DocumentPackage documentPackage = basicPackageCreationExample.getRetrievedPackage(); // Verify if the package is created correctly. assertFalse( "Package enableInPerson setting was not set correctly.", documentPackage.getSettings().getEnableInPerson()); assertThat( "Package description was not set correctly.", documentPackage.getDescription(), is("This is a package created using the e-SignLive SDK")); assertThat( "Package expiry date was not set correctly.", documentPackage.getExpiryDate(), is(now().plusMonths(1).toDate())); assertThat( "Package message was not set correctly.", documentPackage.getPackageMessage(), is("This message should be delivered to all signers")); // Verify if the sdk version is set correctly assertThat("Package attributes are null", documentPackage.getAttributes(), is(notNullValue())); assertThat( "Package attributes are empty", documentPackage.getAttributes().getContents(), is(notNullValue())); assertThat( "SDK version was not set", documentPackage.getAttributes().toMap().containsKey("sdk"), is(true)); assertThat( "SDK version was not set to the correct value", documentPackage.getAttributes().toMap().get("sdk").toString(), is(equalTo("Java v" + VersionUtil.getVersion()))); // Signer 1 Signer signer = documentPackage.getSigner(basicPackageCreationExample.email1); assertThat("Signer 1 ID was not set correctly.", signer.getId(), is("Client1")); assertThat("Signer 1 first name was not set correctly.", signer.getFirstName(), is("John")); assertThat("Signer 1 last name was not set correctly.", signer.getLastName(), is("Smith")); assertThat("Signer 1 title was not set correctly.", signer.getTitle(), is("Managing Director")); assertThat("Signer 1 company was not set correctly.", signer.getCompany(), is("Acme Inc.")); // Signer 2 signer = documentPackage.getSigner(basicPackageCreationExample.email2); assertThat("Signer 2 first name was not set correctly.", signer.getFirstName(), is("Patty")); assertThat("Signer 2 last name was not set correctly.", signer.getLastName(), is("Galant")); // Document 1 Document document = documentPackage.getDocument("First Document pdf"); Iterator<Signature> signatures = document.getSignatures().iterator(); Signature signature; Field field; if (signatures.hasNext()) { signature = signatures.next(); assertThat( "Signature's signer Email was not set correctly for First Document.", signature.getSignerEmail(), is(basicPackageCreationExample.email1)); assertThat( "Signature page was not set correctly for First Document.", signature.getPage(), is(0)); Iterator<Field> fields = signature.getFields().iterator(); if (fields.hasNext()) { field = fields.next(); assertThat( "Field style for signature was not set correctly in First Document.", field.getStyle(), is(FieldStyle.UNBOUND_CHECK_BOX)); assertThat( "Field Page number was not set correctly in First Document.", field.getPage(), is(0)); assertThat( "Field value of signature was not set correctly in First Document.", field.getValue(), is(FieldBuilder.RADIO_SELECTED)); } } // Document 2 document = documentPackage.getDocument("Second Document PDF"); signatures = document.getSignatures().iterator(); if (signatures.hasNext()) { signature = signatures.next(); assertThat( "Signature's signer Email was not set correctly for Second Document.", signature.getSignerEmail(), is("*****@*****.**")); assertThat( "Signature page was not set correctly for Second Document.", signature.getPage(), is(0)); Iterator<Field> fields = signature.getFields().iterator(); if (fields.hasNext()) { field = fields.next(); assertThat( "First radio button style for signature was not set correctly in Second Document.", field.getStyle(), is(FieldStyle.UNBOUND_RADIO_BUTTON)); assertThat( "First radio button Page number was not set correctly in Second Document.", field.getPage(), is(0)); assertThat( "First radio button value of signature was not set correctly in Second Document.", field.getValue(), is("")); assertThat( "First radio button group was not set correctly in Second Document.", field.getFieldValidator().getOptions().get(0), equalTo(basicPackageCreationExample.group1)); field = fields.next(); assertThat( "Second radio button style for signature was not set correctly in Second Document.", field.getStyle(), is(FieldStyle.UNBOUND_RADIO_BUTTON)); assertThat( "Second radio button Page number was not set correctly in Second Document.", field.getPage(), is(0)); assertThat( "Second radio button value of signature was not set correctly in Second Document.", field.getValue(), is(FieldBuilder.RADIO_SELECTED)); assertThat( "Second radio button group was not set correctly in Second Document.", field.getFieldValidator().getOptions().get(0), equalTo(basicPackageCreationExample.group1)); field = fields.next(); assertThat( "Third radio button style for signature was not set correctly in Second Document.", field.getStyle(), is(FieldStyle.UNBOUND_RADIO_BUTTON)); assertThat( "Third radio button Page number was not set correctly in Second Document.", field.getPage(), is(0)); assertThat( "Third radio button value of signature was not set correctly in Second Document.", field.getValue(), is(FieldBuilder.RADIO_SELECTED)); assertThat( "Third radio button group was not set correctly in Second Document.", field.getFieldValidator().getOptions().get(0), equalTo(basicPackageCreationExample.group2)); field = fields.next(); assertThat( "Third radio button style for signature was not set correctly in Second Document.", field.getStyle(), is(FieldStyle.UNBOUND_RADIO_BUTTON)); assertThat( "Third radio button Page number was not set correctly in Second Document.", field.getPage(), is(0)); assertThat( "Third radio button value of signature was not set correctly in Second Document.", field.getValue(), is("")); assertThat( "Third radio button group was not set correctly in Second Document.", field.getFieldValidator().getOptions().get(0), equalTo(basicPackageCreationExample.group2)); } } }