diff --git a/cdoc2-cli/src/main/java/ee/cyber/cdoc2/cli/commands/CDocCreateCmd.java b/cdoc2-cli/src/main/java/ee/cyber/cdoc2/cli/commands/CDocCreateCmd.java index 6bb23cb5..0f76e693 100644 --- a/cdoc2-cli/src/main/java/ee/cyber/cdoc2/cli/commands/CDocCreateCmd.java +++ b/cdoc2-cli/src/main/java/ee/cyber/cdoc2/cli/commands/CDocCreateCmd.java @@ -25,7 +25,7 @@ //S106 - Standard outputs should not be used directly to log anything //CLI needs to interact with standard outputs -@SuppressWarnings("java:S106") +@SuppressWarnings({"java:S106", "java:S125"}) @Command(name = "create", aliases = {"c", "encrypt"}, showAtFileInUsageHelp = true) public class CDocCreateCmd implements Callable { @@ -105,9 +105,6 @@ public Void call() throws Exception { Arrays.toString(inputFiles)); } - - - CDocBuilder cDocBuilder = new CDocBuilder() .withPayloadFiles(Arrays.asList(inputFiles)); @@ -116,7 +113,6 @@ public Void call() throws Exception { cDocBuilder.withServerProperties(p); } - List symmetricKMs = SymmetricKeyUtil.getEncryptionKeyMaterialFromFormattedSecrets(recipient.secrets); diff --git a/cdoc2-cli/src/main/java/ee/cyber/cdoc2/cli/commands/CDocDecryptCmd.java b/cdoc2-cli/src/main/java/ee/cyber/cdoc2/cli/commands/CDocDecryptCmd.java index b56a6fcc..36602108 100644 --- a/cdoc2-cli/src/main/java/ee/cyber/cdoc2/cli/commands/CDocDecryptCmd.java +++ b/cdoc2-cli/src/main/java/ee/cyber/cdoc2/cli/commands/CDocDecryptCmd.java @@ -21,7 +21,7 @@ //S106 Standard outputs should not be used directly to log anything //CLI needs to interact with standard outputs -@SuppressWarnings("java:S106") +@SuppressWarnings({"java:S106", "java:S125"}) @Command(name = "decrypt", aliases = {"x", "extract"}, showAtFileInUsageHelp = true) public class CDocDecryptCmd implements Callable { // commented out until public key server is in live diff --git a/cdoc2-cli/src/main/java/ee/cyber/cdoc2/cli/commands/CDocInfoCmd.java b/cdoc2-cli/src/main/java/ee/cyber/cdoc2/cli/commands/CDocInfoCmd.java index f939f9dd..ee352f6d 100644 --- a/cdoc2-cli/src/main/java/ee/cyber/cdoc2/cli/commands/CDocInfoCmd.java +++ b/cdoc2-cli/src/main/java/ee/cyber/cdoc2/cli/commands/CDocInfoCmd.java @@ -21,7 +21,6 @@ import static ee.cyber.cdoc2.crypto.KeyLabelTools.keyLabelParamsForDisplaying; - //S106 Standard outputs should not be used directly to log anything //CLI needs to interact with standard outputs @SuppressWarnings("java:S106") @@ -44,18 +43,15 @@ private void setProperty(Map props) { @Override public Void call() throws Exception { - - List recipients = Envelope.parseHeader(Files.newInputStream(cdocFile.toPath())); for (Recipient recipient: recipients) { - String type = getHumanReadableType(recipient); Map keyLabelParams = extractKeyLabelParams(recipient.getRecipientKeyLabel()); - String server = (recipient instanceof ServerRecipient) - ? "(server: " + ((ServerRecipient) recipient).getKeyServerId() + ")" + String server = (recipient instanceof ServerRecipient serverRecipient) + ? "(server: " + serverRecipient.getKeyServerId() + ")" : ""; System.out.println( @@ -69,8 +65,8 @@ public Void call() throws Exception { String getHumanReadableType(Recipient recipient) { Objects.requireNonNull(recipient); //can't have null recipient, fail with exception - if (recipient instanceof PublicKeyRecipient) { - return ((PublicKeyRecipient) recipient).getRecipientPubKey().getAlgorithm() + " PublicKey"; + if (recipient instanceof PublicKeyRecipient publicKeyRecipient) { + return publicKeyRecipient.getRecipientPubKey().getAlgorithm() + " PublicKey"; } else if (recipient instanceof SymmetricKeyRecipient) { return "SymmetricKey"; } else if (recipient instanceof PBKDF2Recipient) { @@ -81,4 +77,5 @@ String getHumanReadableType(Recipient recipient) { return recipient.getClass().toString(); } } + } diff --git a/cdoc2-cli/src/main/java/ee/cyber/cdoc2/cli/commands/CDocReEncryptCmd.java b/cdoc2-cli/src/main/java/ee/cyber/cdoc2/cli/commands/CDocReEncryptCmd.java index 508a6671..3465b907 100644 --- a/cdoc2-cli/src/main/java/ee/cyber/cdoc2/cli/commands/CDocReEncryptCmd.java +++ b/cdoc2-cli/src/main/java/ee/cyber/cdoc2/cli/commands/CDocReEncryptCmd.java @@ -25,7 +25,7 @@ //S106 Standard outputs should not be used directly to log anything //CLI needs to interact with standard outputs -@SuppressWarnings("java:S106") +@SuppressWarnings({"java:S106", "java:S125"}) @CommandLine.Command(name = "re-encrypt", aliases = {"re", "reencrypt"}, showAtFileInUsageHelp = true) public class CDocReEncryptCmd implements Callable { diff --git a/cdoc2-cli/src/test/java/CDocCliTest.java b/cdoc2-cli/src/test/java/cli/CDocCliTest.java similarity index 99% rename from cdoc2-cli/src/test/java/CDocCliTest.java rename to cdoc2-cli/src/test/java/cli/CDocCliTest.java index b3c3ffbe..b7d26521 100644 --- a/cdoc2-cli/src/test/java/CDocCliTest.java +++ b/cdoc2-cli/src/test/java/cli/CDocCliTest.java @@ -1,4 +1,4 @@ -import ee.cyber.cdoc2.cli.CDocCli; +package cli; import java.io.ByteArrayOutputStream; import java.io.IOException; @@ -21,6 +21,9 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import picocli.CommandLine; + +import ee.cyber.cdoc2.cli.CDocCli; + import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; @@ -92,7 +95,7 @@ void testSuccessfulCreateDecryptDocWithPassword() throws IOException { } @Test - @Disabled + @Disabled("Requires user interaction for inserting password 'myPlainTextPassword'") void testSuccessfulCreateDecryptDocWithPasswordWhenItIsInsertedInteractively() throws IOException { encrypt(PASSWORD_OPTION); diff --git a/cdoc2-cli/src/test/java/CryptoTest.java b/cdoc2-cli/src/test/java/cli/CryptoTest.java similarity index 98% rename from cdoc2-cli/src/test/java/CryptoTest.java rename to cdoc2-cli/src/test/java/cli/CryptoTest.java index 6da5e75a..669d9128 100644 --- a/cdoc2-cli/src/test/java/CryptoTest.java +++ b/cdoc2-cli/src/test/java/cli/CryptoTest.java @@ -1,3 +1,5 @@ +package cli; + import org.junit.jupiter.api.Test; import ee.cyber.cdoc2.crypto.Crypto; diff --git a/cdoc2-client/src/main/java/ee/cyber/cdoc2/client/Cdoc2KeyCapsuleApiClient.java b/cdoc2-client/src/main/java/ee/cyber/cdoc2/client/Cdoc2KeyCapsuleApiClient.java index cfd3d8a8..d6c4b4d9 100644 --- a/cdoc2-client/src/main/java/ee/cyber/cdoc2/client/Cdoc2KeyCapsuleApiClient.java +++ b/cdoc2-client/src/main/java/ee/cyber/cdoc2/client/Cdoc2KeyCapsuleApiClient.java @@ -190,6 +190,7 @@ protected void customizeClientBuilder(ClientBuilder clientBuilder) { return new Cdoc2KeyCapsuleApiClient(new Cdoc2KeyCapsulesApi(apiClient)); } + @SuppressWarnings("java:S2139") private SSLContext createSslContext() throws NoSuchAlgorithmException, InvalidAlgorithmParameterException, KeyStoreException, KeyManagementException { SSLContext sslContext; diff --git a/cdoc2-example-app/src/main/java/ee/cyber/cdoc2/converter/ConverterCmd.java b/cdoc2-example-app/src/main/java/ee/cyber/cdoc2/converter/ConverterCmd.java index 0d6d1477..66729a18 100644 --- a/cdoc2-example-app/src/main/java/ee/cyber/cdoc2/converter/ConverterCmd.java +++ b/cdoc2-example-app/src/main/java/ee/cyber/cdoc2/converter/ConverterCmd.java @@ -17,8 +17,8 @@ import java.util.Arrays; import java.util.concurrent.Callable; -@Command( name = "cdoc-convert" -) +@Command( name = "cdoc-convert") +@SuppressWarnings("squid:S106") public class ConverterCmd implements Callable { private static final Logger log = LoggerFactory.getLogger(ConverterCmd.class); @@ -48,8 +48,6 @@ public class ConverterCmd implements Callable { @Option(names = { "-h", "--help" }, usageHelp = false, description = "display a help message") private boolean helpRequested = false; - - public static void main(String... args) { if (args.length == 0) { @@ -61,7 +59,6 @@ public static void main(String... args) { System.exit(exitCode); } - @Override public Void call() throws Exception { diff --git a/cdoc2-example-app/src/main/java/ee/cyber/cdoc2/converter/util/AutoRemovableDir.java b/cdoc2-example-app/src/main/java/ee/cyber/cdoc2/converter/util/AutoRemovableDir.java index 1e32caa2..6c64a719 100644 --- a/cdoc2-example-app/src/main/java/ee/cyber/cdoc2/converter/util/AutoRemovableDir.java +++ b/cdoc2-example-app/src/main/java/ee/cyber/cdoc2/converter/util/AutoRemovableDir.java @@ -8,6 +8,8 @@ public class AutoRemovableDir implements AutoCloseable { + private static final Logger log = LoggerFactory.getLogger(AutoRemovableDir.class); + Path pathToRemove; public AutoRemovableDir(Path pathToRemove) { this.pathToRemove = pathToRemove; @@ -27,6 +29,7 @@ private static void purgeDirectory(File dir) { if (file.isDirectory()) purgeDirectory(file); file.delete(); + log.info("Directory " + dir + " was deleted"); } } } diff --git a/cdoc2-example-app/src/main/java/ee/cyber/cdoc2/converter/util/PasswordCheckUtil.java b/cdoc2-example-app/src/main/java/ee/cyber/cdoc2/converter/util/PasswordCheckUtil.java index 5db9dd55..1dc93d4b 100644 --- a/cdoc2-example-app/src/main/java/ee/cyber/cdoc2/converter/util/PasswordCheckUtil.java +++ b/cdoc2-example-app/src/main/java/ee/cyber/cdoc2/converter/util/PasswordCheckUtil.java @@ -59,6 +59,7 @@ public static boolean isPwned(char[] passwd) throws NoSuchAlgorithmException, UR byte[] bytes = StandardCharsets.UTF_8.encode(CharBuffer.wrap(passwd)).array(); + @SuppressWarnings("java:S4790") MessageDigest sha1 = MessageDigest.getInstance("SHA-1"); sha1.update(bytes); String digest = HexFormat.of().formatHex(sha1.digest()).toUpperCase(); diff --git a/cdoc2-example-app/src/main/java/ee/cyber/cdoc2/converter/util/Util.java b/cdoc2-example-app/src/main/java/ee/cyber/cdoc2/converter/util/Util.java index bd1f8b25..d5823296 100644 --- a/cdoc2-example-app/src/main/java/ee/cyber/cdoc2/converter/util/Util.java +++ b/cdoc2-example-app/src/main/java/ee/cyber/cdoc2/converter/util/Util.java @@ -32,6 +32,10 @@ public class Util { + private Util() { + // utility class + } + static final int LABEL_LEN_BYTES = 64/8; private static final Logger log = LoggerFactory.getLogger(Util.class); @@ -61,9 +65,9 @@ public static char[] readPasswordInteractively(String prompt) { if (result == JOptionPane.OK_OPTION) { return pf.getPassword(); } else if (result == JOptionPane.OK_CANCEL_OPTION) { - throw new RuntimeException("Password entry cancelled by user"); + throw new CDocUserException("Password entry cancelled by user"); } else { - throw new RuntimeException("Password not entered"); + throw new CDocUserException("Password not entered"); } } } @@ -80,6 +84,7 @@ public static void reEncrypt(InputStream cdoc, Token cdocToken, @Nullable Path tempDir) throws CDocException, IOException, CDocValidationException, CDOCException { + @SuppressWarnings("java:S5443") Path outDir = (tempDir != null) ? Files.createDirectories(tempDir.resolve(UUID.randomUUID().toString())) : Files.createTempDirectory(UUID.randomUUID().toString()); diff --git a/cdoc2-example-app/src/test/java/ee/cyber/cdoc2/converter/ConverterTest.java b/cdoc2-example-app/src/test/java/ee/cyber/cdoc2/converter/ConverterTest.java index 9a257f99..722396c5 100644 --- a/cdoc2-example-app/src/test/java/ee/cyber/cdoc2/converter/ConverterTest.java +++ b/cdoc2-example-app/src/test/java/ee/cyber/cdoc2/converter/ConverterTest.java @@ -27,15 +27,14 @@ class ConverterTest { Logger log = LoggerFactory.getLogger(ConverterTest.class); // cdoc4j sample files from https://github.com/open-eid/cdoc4j/tree/master/src/test/resources - final static String CDOC_FILE = "src/test/resources/cdoc/valid_cdoc11_ECC.cdoc"; - final static String ECC_P12 = "src/test/resources/ecc/ecc.p12"; + static final String CDOC_FILE = "src/test/resources/cdoc/valid_cdoc11_ECC.cdoc"; + static final String ECC_P12 = "src/test/resources/ecc/ecc.p12"; // password for ECC_P12 - final static String ECC_P12_PW = "test"; - + static final String ECC_P12_PW = "test"; // password used to derive bytes for re-encryption - final static char[] CDOC2_TEST_PW = {'t', 'e', 's', 't', ' ', 't', 's', 'e', 't'}; + static final char[] CDOC2_TEST_PW = {'t', 'e', 's', 't', ' ', 't', 's', 'e', 't'}; // cdoc2 requires label with password public static final String CDOC2_TEST_LABEL = "pw_label"; diff --git a/cdoc2-lib/src/main/java/ee/cyber/cdoc2/client/EcCapsuleClientImpl.java b/cdoc2-lib/src/main/java/ee/cyber/cdoc2/client/EcCapsuleClientImpl.java index 34df39f1..c5cfbb17 100644 --- a/cdoc2-lib/src/main/java/ee/cyber/cdoc2/client/EcCapsuleClientImpl.java +++ b/cdoc2-lib/src/main/java/ee/cyber/cdoc2/client/EcCapsuleClientImpl.java @@ -12,6 +12,8 @@ import java.security.interfaces.ECPublicKey; import java.util.Optional; + +@SuppressWarnings("java:S2139") public class EcCapsuleClientImpl implements EcCapsuleClient { private static final Logger log = LoggerFactory.getLogger(EcCapsuleClientImpl.class); diff --git a/cdoc2-lib/src/main/java/ee/cyber/cdoc2/container/Envelope.java b/cdoc2-lib/src/main/java/ee/cyber/cdoc2/container/Envelope.java index cc8049a9..004a7d2b 100644 --- a/cdoc2-lib/src/main/java/ee/cyber/cdoc2/container/Envelope.java +++ b/cdoc2-lib/src/main/java/ee/cyber/cdoc2/container/Envelope.java @@ -463,7 +463,9 @@ private static void drainStream(CipherInputStream cis, @Nullable Runnable cleanU byte[] ignored = new byte[1024]; try { - while (cis.read(ignored) > 0) { } + while (cis.read(ignored) > 0) { + // do nothing + } } catch (IOException drainingException) { // MAC check error is thrown as IOException if (cleanUpFunc != null) { cleanUpFunc.run(); diff --git a/cdoc2-lib/src/main/java/ee/cyber/cdoc2/container/recipients/PBKDF2Recipient.java b/cdoc2-lib/src/main/java/ee/cyber/cdoc2/container/recipients/PBKDF2Recipient.java index a8858beb..bac69751 100644 --- a/cdoc2-lib/src/main/java/ee/cyber/cdoc2/container/recipients/PBKDF2Recipient.java +++ b/cdoc2-lib/src/main/java/ee/cyber/cdoc2/container/recipients/PBKDF2Recipient.java @@ -25,8 +25,8 @@ public class PBKDF2Recipient extends Recipient { private final byte[] encryptionSalt; private final byte[] passwordSalt; - private final byte kdfAlgorithmIdentifier = KDFAlgorithmIdentifier.PBKDF2WithHmacSHA256; - private final int kdfIterations = PBKDF2_ITERATIONS; + private final byte kdfAlgorithmIdentifier; + private final int kdfIterations; public PBKDF2Recipient( byte[] encSalt, @@ -37,6 +37,8 @@ public PBKDF2Recipient( super(encFmk, recipientLabel); this.encryptionSalt = encSalt.clone(); this.passwordSalt = passwordSalt; + this.kdfAlgorithmIdentifier = KDFAlgorithmIdentifier.PBKDF2WithHmacSHA256; + this.kdfIterations = PBKDF2_ITERATIONS; } @Override diff --git a/cdoc2-lib/src/main/java/ee/cyber/cdoc2/container/recipients/Recipient.java b/cdoc2-lib/src/main/java/ee/cyber/cdoc2/container/recipients/Recipient.java index 09b93193..1bb42227 100644 --- a/cdoc2-lib/src/main/java/ee/cyber/cdoc2/container/recipients/Recipient.java +++ b/cdoc2-lib/src/main/java/ee/cyber/cdoc2/container/recipients/Recipient.java @@ -7,6 +7,7 @@ import java.util.Arrays; import java.util.Objects; + /** * Java POJO that represents flatbuffers {@link RecipientRecord header.RecipientRecord} * Capsule union field(s) will be implemented by subclasses. @@ -15,11 +16,12 @@ public abstract class Recipient implements KekDerivable, SerializableFBS { // header.RecipientRecord specific fields protected final byte[] encryptedFmk; protected final String recipientKeyLabel; - protected final byte fmkEncryptionMethod = FMKEncryptionMethod.XOR; + protected final byte fmkEncryptionMethod; protected Recipient(byte[] encFmk, String recipientLabel) { this.recipientKeyLabel = recipientLabel; this.encryptedFmk = encFmk.clone(); + this.fmkEncryptionMethod = FMKEncryptionMethod.XOR; } public String getRecipientKeyLabel() { @@ -59,4 +61,5 @@ public int hashCode() { result = 31 * result + Arrays.hashCode(encryptedFmk); return result; } + } diff --git a/cdoc2-lib/src/main/java/ee/cyber/cdoc2/crypto/Crypto.java b/cdoc2-lib/src/main/java/ee/cyber/cdoc2/crypto/Crypto.java index 6eaac531..b8f8e31a 100644 --- a/cdoc2-lib/src/main/java/ee/cyber/cdoc2/crypto/Crypto.java +++ b/cdoc2-lib/src/main/java/ee/cyber/cdoc2/crypto/Crypto.java @@ -197,7 +197,7 @@ public static byte[] calcEcDhSharedSecret(PrivateKey ecPrivateKey, ECPublicKey o // As pkcs11 loaded key is not instance of ECPrivateKey, then it's possible to differentiate between keys // ECPublicKey is always "soft" key Provider configuredPKCS11Provider = Pkcs11Tools.getConfiguredPKCS11Provider(); - if (isECPKCS11Key(ecPrivateKey) && (configuredPKCS11Provider != null)) { + if (isECPKCS11Key(ecPrivateKey) && configuredPKCS11Provider != null) { keyAgreement = KeyAgreement.getInstance("ECDH", configuredPKCS11Provider); } else { keyAgreement = KeyAgreement.getInstance("ECDH"); diff --git a/cdoc2-lib/src/main/java/ee/cyber/cdoc2/crypto/ECKeys.java b/cdoc2-lib/src/main/java/ee/cyber/cdoc2/crypto/ECKeys.java index 8d0072cb..2d9a6d40 100644 --- a/cdoc2-lib/src/main/java/ee/cyber/cdoc2/crypto/ECKeys.java +++ b/cdoc2-lib/src/main/java/ee/cyber/cdoc2/crypto/ECKeys.java @@ -253,7 +253,9 @@ public static boolean isValidSecP384R1(ECPublicKey ecPublicKey) throws GeneralSe } if (!isEcSecp384r1Curve(ecPublicKey)) { - log.debug("EC pub key curve OID {} is not secp384r1", getCurveOid(ecPublicKey)); + if (log.isDebugEnabled()) { + log.debug("EC pub key curve OID {} is not secp384r1", getCurveOid(ecPublicKey)); + } return false; } diff --git a/cdoc2-lib/src/main/java/ee/cyber/cdoc2/crypto/EllipticCurve.java b/cdoc2-lib/src/main/java/ee/cyber/cdoc2/crypto/EllipticCurve.java index daa807c6..b0cdb03b 100644 --- a/cdoc2-lib/src/main/java/ee/cyber/cdoc2/crypto/EllipticCurve.java +++ b/cdoc2-lib/src/main/java/ee/cyber/cdoc2/crypto/EllipticCurve.java @@ -12,11 +12,13 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; + /** * Curve values from {@link ee.cyber.cdoc2.fbs.recipients.EllipticCurve} defined as enum and mapped to * known elliptic curve names and oid's */ public enum EllipticCurve { + UNKNOWN(ee.cyber.cdoc2.fbs.recipients.EllipticCurve.UNKNOWN, null, null), SECP384R1(ee.cyber.cdoc2.fbs.recipients.EllipticCurve.secp384r1, ECKeys.SECP_384_R_1, ECKeys.SECP_384_OID); @@ -31,6 +33,7 @@ public enum EllipticCurve { this.name = name; this.oid = oid; } + public byte getValue() { return value; } @@ -43,43 +46,34 @@ public String getOid() { } public boolean isValidKey(ECPublicKey key) throws GeneralSecurityException { - switch (this) { - case SECP384R1: - return ECKeys.isValidSecP384R1(key); - default: - throw new IllegalStateException("isValidKey not implemented for " + this); + if (this == EllipticCurve.SECP384R1) { + return ECKeys.isValidSecP384R1(key); } + throw new IllegalStateException("isValidKey not implemented for " + this); } public boolean isValidKeyPair(KeyPair keyPair) throws GeneralSecurityException { - switch (this) { - case SECP384R1: - return ECKeys.isECSecp384r1(keyPair); - default: - throw new IllegalStateException("isValidKeyPair not implemented for " + this); + if (this == EllipticCurve.SECP384R1) { + return ECKeys.isECSecp384r1(keyPair); } + throw new IllegalStateException("isValidKeyPair not implemented for " + this); } /** * Key length in bytes. For secp384r1, its 384/8=48 */ public int getKeyLength() { - switch (this) { - case SECP384R1: - return ECKeys.SECP_384_R_1_LEN_BYTES; - default: - throw new IllegalStateException("getKeyLength not implemented for " + this); + if (this == EllipticCurve.SECP384R1) { + return ECKeys.SECP_384_R_1_LEN_BYTES; } + throw new IllegalStateException("getKeyLength not implemented for " + this); } public ECPublicKey decodeFromTls(ByteBuffer encoded) throws GeneralSecurityException { - switch (this) { - case SECP384R1: - // calls also isValidSecP384R1 - return ECKeys.decodeSecP384R1EcPublicKeyFromTls(encoded); - default: - throw new IllegalStateException("decodeFromTls not implemented for " + this); + if (this == EllipticCurve.SECP384R1) { // calls also isValidSecP384R1 + return ECKeys.decodeSecP384R1EcPublicKeyFromTls(encoded); } + throw new IllegalStateException("decodeFromTls not implemented for " + this); } public KeyPair generateEcKeyPair() throws GeneralSecurityException { @@ -101,17 +95,15 @@ public static EllipticCurve forOid(String oid) throws NoSuchAlgorithmException { } public static EllipticCurve forValue(byte value) throws NoSuchAlgorithmException { - switch (value) { - case ee.cyber.cdoc2.fbs.recipients.EllipticCurve.secp384r1: - return SECP384R1; - default: - throw new NoSuchAlgorithmException("Unknown EC curve value " + value); + if (value == ee.cyber.cdoc2.fbs.recipients.EllipticCurve.secp384r1) { + return SECP384R1; } + throw new NoSuchAlgorithmException("Unknown EC curve value " + value); } /** * @param publicKey ECPublicKey - * @return + * @return EllipticCurve * @throws NoSuchAlgorithmException if publicKey EC curve is not supported * @throws InvalidParameterSpecException * @throws NoSuchProviderException @@ -120,8 +112,7 @@ public static EllipticCurve forValue(byte value) throws NoSuchAlgorithmException public static EllipticCurve forPubKey(PublicKey publicKey) throws NoSuchAlgorithmException, InvalidParameterSpecException, NoSuchProviderException, InvalidKeyException { - if (publicKey instanceof ECPublicKey) { - ECPublicKey ecPublicKey = (ECPublicKey) publicKey; + if (publicKey instanceof ECPublicKey ecPublicKey) { return forOid(ECKeys.getCurveOid(ecPublicKey)); } else { throw new InvalidKeyException("Unsupported key algorithm " + publicKey.getAlgorithm()); @@ -150,4 +141,5 @@ public static boolean isSupported(PublicKey publicKey) { public static String[] names() { return ee.cyber.cdoc2.fbs.recipients.EllipticCurve.names; } + } diff --git a/cdoc2-lib/src/main/java/ee/cyber/cdoc2/crypto/KekTools.java b/cdoc2-lib/src/main/java/ee/cyber/cdoc2/crypto/KekTools.java index 6d5826a7..d115b68f 100644 --- a/cdoc2-lib/src/main/java/ee/cyber/cdoc2/crypto/KekTools.java +++ b/cdoc2-lib/src/main/java/ee/cyber/cdoc2/crypto/KekTools.java @@ -60,7 +60,9 @@ public static byte[] deriveKekForSymmetricKey( secretKey, recipient.getSalt(), FMKEncryptionMethod.name(recipient.getFmkEncryptionMethod())); - log.debug("kek={}", HexFormat.of().formatHex(kek.getEncoded())); + if (log.isDebugEnabled()) { + log.debug("kek={}", HexFormat.of().formatHex(kek.getEncoded())); + } return kek.getEncoded(); } @@ -105,6 +107,7 @@ public static byte[] deriveKekForEcc( return Crypto.deriveKeyDecryptionKey(recipientKeyPair, senderPubKey, Crypto.CEK_LEN_BYTES); } + @SuppressWarnings("java:S2139") public static byte[] deriveKekForEccServer( EccServerKeyRecipient keyRecipient, KeyPairDecryptionKeyMaterial keyMaterial, diff --git a/cdoc2-lib/src/main/java/ee/cyber/cdoc2/crypto/PemTools.java b/cdoc2-lib/src/main/java/ee/cyber/cdoc2/crypto/PemTools.java index b5a58ff6..ab787202 100644 --- a/cdoc2-lib/src/main/java/ee/cyber/cdoc2/crypto/PemTools.java +++ b/cdoc2-lib/src/main/java/ee/cyber/cdoc2/crypto/PemTools.java @@ -303,6 +303,7 @@ public static KeyPair loadKeyPairFromP12File(String p12) throws GeneralSecurityE return new KeyPair(publicKey, key); } + @SuppressWarnings("java:S4790") private static String getCertFingerprint(X509Certificate cert) { try { return DigestUtils.sha1Hex(cert.getEncoded()); diff --git a/cdoc2-lib/src/main/java/ee/cyber/cdoc2/crypto/Pkcs11Tools.java b/cdoc2-lib/src/main/java/ee/cyber/cdoc2/crypto/Pkcs11Tools.java index 4e51c790..0ceae119 100644 --- a/cdoc2-lib/src/main/java/ee/cyber/cdoc2/crypto/Pkcs11Tools.java +++ b/cdoc2-lib/src/main/java/ee/cyber/cdoc2/crypto/Pkcs11Tools.java @@ -309,6 +309,7 @@ static Path createSunPkcsConfigurationFile(String name, String openScLibrary, In return confPath; } + @SuppressWarnings("java:S2139") private static KeyStore getConfiguredPkcs11KeyStore(KeyStore.ProtectionParameter keyProtection) throws KeyStoreException { try { diff --git a/cdoc2-lib/src/main/java/ee/cyber/cdoc2/crypto/SymmetricKeyTools.java b/cdoc2-lib/src/main/java/ee/cyber/cdoc2/crypto/SymmetricKeyTools.java index 0db64acc..069a7978 100644 --- a/cdoc2-lib/src/main/java/ee/cyber/cdoc2/crypto/SymmetricKeyTools.java +++ b/cdoc2-lib/src/main/java/ee/cyber/cdoc2/crypto/SymmetricKeyTools.java @@ -96,13 +96,6 @@ public static EncryptionKeyMaterial getEncryptionKeyMaterialFromSecret( return EncryptionKeyMaterial.fromSecret(entry.getKey(), entry.getValue()); } -// public static EncryptionKeyMaterial getEncryptionKeyMaterial( -// AbstractMap.SimpleEntry entry, String payloadFileName -// ) { -// return EncryptionKeyMaterial.builder() -// .fromSecret(entry.getKey(), entry.getValue(), payloadFileName); -// } - public static EncryptionKeyMaterial getEncryptionKeyMaterialFromPassword( FormattedOptionParts splitPasswordAndLabel ) { diff --git a/cdoc2-lib/src/main/java/ee/cyber/cdoc2/crypto/keymaterial/DecryptionKeyMaterial.java b/cdoc2-lib/src/main/java/ee/cyber/cdoc2/crypto/keymaterial/DecryptionKeyMaterial.java index a5bc6f6c..79fc396c 100644 --- a/cdoc2-lib/src/main/java/ee/cyber/cdoc2/crypto/keymaterial/DecryptionKeyMaterial.java +++ b/cdoc2-lib/src/main/java/ee/cyber/cdoc2/crypto/keymaterial/DecryptionKeyMaterial.java @@ -30,13 +30,13 @@ public interface DecryptionKeyMaterial { EncryptionKeyOrigin getKeyOrigin(); /** - * Deprecated decryption key. Will be removed later. * Creates decryption key material with secret key. + * @deprecated decryption key * @param secretKey secret key * @param label key label * @return DecryptionKeyMaterial key material required for decryption */ - @Deprecated + @Deprecated(forRemoval = true) static DecryptionKeyMaterial fromSecretKey(SecretKey secretKey, String label) { return new SecretDecryptionKeyMaterial(secretKey, label); } diff --git a/cdoc2-lib/src/main/java/ee/cyber/cdoc2/crypto/keymaterial/EncryptionKeyMaterial.java b/cdoc2-lib/src/main/java/ee/cyber/cdoc2/crypto/keymaterial/EncryptionKeyMaterial.java index 3471d83b..1a0d7b03 100644 --- a/cdoc2-lib/src/main/java/ee/cyber/cdoc2/crypto/keymaterial/EncryptionKeyMaterial.java +++ b/cdoc2-lib/src/main/java/ee/cyber/cdoc2/crypto/keymaterial/EncryptionKeyMaterial.java @@ -41,11 +41,12 @@ public interface EncryptionKeyMaterial { * For backward compatibility. This method doesn't support correct keylabel generation as there * is no info, where pubKey is coming from (pubkey, cert, LDAP) * Use {@link #fromPublicKey(PublicKey, KeyLabelParams)} instead. - * @param pubKey - * @param keyLabel - * @return + * @deprecated ecryption key + * @param pubKey public key + * @param keyLabel key label + * @return EncryptionKeyMaterial */ - @Deprecated + @Deprecated(forRemoval = true) static EncryptionKeyMaterial fromPublicKey( PublicKey pubKey, String keyLabel diff --git a/cdoc2-lib/src/main/java/ee/cyber/cdoc2/crypto/keymaterial/decrypt/PasswordDecryptionKeyMaterial.java b/cdoc2-lib/src/main/java/ee/cyber/cdoc2/crypto/keymaterial/decrypt/PasswordDecryptionKeyMaterial.java index 93afacb4..f31db80a 100644 --- a/cdoc2-lib/src/main/java/ee/cyber/cdoc2/crypto/keymaterial/decrypt/PasswordDecryptionKeyMaterial.java +++ b/cdoc2-lib/src/main/java/ee/cyber/cdoc2/crypto/keymaterial/decrypt/PasswordDecryptionKeyMaterial.java @@ -39,6 +39,7 @@ public int hashCode() { } @Override + @SuppressWarnings("java:S2068") public String toString() { return "PasswordDecryptionKeyMaterial{" + "password=[hidden]" diff --git a/cdoc2-lib/src/main/java/ee/cyber/cdoc2/crypto/keymaterial/encrypt/EncryptionKeyMaterialCollectionBuilder.java b/cdoc2-lib/src/main/java/ee/cyber/cdoc2/crypto/keymaterial/encrypt/EncryptionKeyMaterialCollectionBuilder.java index e4137d4a..1f410bf2 100644 --- a/cdoc2-lib/src/main/java/ee/cyber/cdoc2/crypto/keymaterial/encrypt/EncryptionKeyMaterialCollectionBuilder.java +++ b/cdoc2-lib/src/main/java/ee/cyber/cdoc2/crypto/keymaterial/encrypt/EncryptionKeyMaterialCollectionBuilder.java @@ -94,7 +94,7 @@ public EncryptionKeyMaterialCollectionBuilder fromEId(String[] identificationCod List keyMaterials = certData.stream() .filter(entry -> EllipticCurve.isSupported(entry.getPublicKey())) .map(SkLdapUtil::toEncryptionKeyMaterial) - .collect(Collectors.toList()); + .toList(); recipients.addAll(keyMaterials); return this; diff --git a/cdoc2-lib/src/main/java/ee/cyber/cdoc2/crypto/keymaterial/encrypt/PasswordEncryptionKeyMaterial.java b/cdoc2-lib/src/main/java/ee/cyber/cdoc2/crypto/keymaterial/encrypt/PasswordEncryptionKeyMaterial.java index 3ff5126f..c79fbad4 100644 --- a/cdoc2-lib/src/main/java/ee/cyber/cdoc2/crypto/keymaterial/encrypt/PasswordEncryptionKeyMaterial.java +++ b/cdoc2-lib/src/main/java/ee/cyber/cdoc2/crypto/keymaterial/encrypt/PasswordEncryptionKeyMaterial.java @@ -38,6 +38,7 @@ public int hashCode() { } @Override + @SuppressWarnings("java:S2068") public String toString() { return "PasswordEncryptionKeyMaterial{" + "password=[hidden]" diff --git a/cdoc2-lib/src/main/java/ee/cyber/cdoc2/util/OperatingSystem.java b/cdoc2-lib/src/main/java/ee/cyber/cdoc2/util/OperatingSystem.java index 30cfbc4b..45e048a3 100644 --- a/cdoc2-lib/src/main/java/ee/cyber/cdoc2/util/OperatingSystem.java +++ b/cdoc2-lib/src/main/java/ee/cyber/cdoc2/util/OperatingSystem.java @@ -18,7 +18,9 @@ public enum OperatingSystem { * @return the operating system */ public static OperatingSystem getOS() { - log.debug("os.family: {}, os.name: {}", System.getProperty("os.family"), System.getProperty(OS_NAME)); + if (log.isDebugEnabled()) { + log.debug("os.family: {}, os.name: {}", System.getProperty("os.family"), System.getProperty(OS_NAME)); + } String os = System.getProperty(OS_NAME).toLowerCase(); if (os.contains("win")) { @@ -31,9 +33,11 @@ public static OperatingSystem getOS() { return OperatingSystem.MAC; } - log.error("Unknown operating system: os.family: {}, os.name: {}", - System.getProperty("os.family"), System.getProperty(OS_NAME) - ); + if (log.isErrorEnabled()) { + log.error("Unknown operating system: os.family: {}, os.name: {}", + System.getProperty("os.family"), System.getProperty(OS_NAME) + ); + } throw new IllegalStateException("Unknown OS"); } } diff --git a/cdoc2-lib/src/main/java/ee/cyber/cdoc2/util/SkLdapUtil.java b/cdoc2-lib/src/main/java/ee/cyber/cdoc2/util/SkLdapUtil.java index 40f215f3..e437be58 100644 --- a/cdoc2-lib/src/main/java/ee/cyber/cdoc2/util/SkLdapUtil.java +++ b/cdoc2-lib/src/main/java/ee/cyber/cdoc2/util/SkLdapUtil.java @@ -59,6 +59,7 @@ private SkLdapUtil() { // distinguished name fragment for authentication certificates using e-resident digi-id private static final String AUTH_E_RESIDENT_DIGI_ID = AUTH_CERT_PART + E_RESIDENT_DIGI_ID; + @SuppressWarnings("java:S1149") private static DirContext initDirContext() throws NamingException { Hashtable env = new Hashtable<>(11); env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory"); @@ -78,11 +79,11 @@ private static DirContext initDirContext() throws NamingException { * @throws CertificateException If parsing found certificate fails * @see SK LDAP */ - public static Map findAuthenticationEstEidCertificates(DirContext ctx, - String identificationCode) throws NamingException, CertificateException { - + public static Map findAuthenticationEstEidCertificates( + DirContext ctx, + String identificationCode + ) throws NamingException, CertificateException { Map certificateNameMap = new LinkedHashMap<>(); - CertificateFactory certFactory = CertificateFactory.getInstance("X.509"); SearchControls searchControls = new SearchControls(); searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE); @@ -99,30 +100,40 @@ public static Map findAuthenticationEstEidCertificates( String dn = searchResult.getName(); if (dn.contains(AUTH_ID_CARD) || dn.contains(AUTH_DIGI_ID) || dn.contains(AUTH_E_RESIDENT_DIGI_ID)) { - - // there can be more than one 'userCertificate;binary' attribute - var certAttrs = (NamingEnumeration) attrs.get("userCertificate;binary").getAll(); - while (certAttrs.hasMore()) { - Object certObject = certAttrs.nextElement(); - if (certObject != null) { - byte[] certBuf = (byte[]) certObject; - try { - X509Certificate cert = (X509Certificate) certFactory.generateCertificate( - new ByteArrayInputStream(certBuf)); - log.debug("Found cert for {}, name:{}", identificationCode, dn); - certificateNameMap.put(cert, dn); - } catch (CertificateException ce) { - log.error("Invalid certificate for {}", identificationCode); - throw ce; - } - } - } + mapCertificates(certificateNameMap, attrs, identificationCode, dn); } } return certificateNameMap; } + private static void mapCertificates( + Map certificateNameMap, + Attributes attrs, + String identificationCode, + String distinguishedName + ) throws CertificateException, NamingException { + // there can be more than one 'userCertificate;binary' attribute + var certAttrs = (NamingEnumeration) attrs.get("userCertificate;binary").getAll(); + CertificateFactory certFactory = CertificateFactory.getInstance("X.509"); + + while (certAttrs.hasMore()) { + Object certObject = certAttrs.nextElement(); + if (certObject != null) { + byte[] certBuf = (byte[]) certObject; + try { + X509Certificate cert = (X509Certificate) certFactory.generateCertificate( + new ByteArrayInputStream(certBuf)); + log.debug("Found cert for {}, name:{}", identificationCode, distinguishedName); + certificateNameMap.put(cert, distinguishedName); + } catch (CertificateException ce) { + log.error("Invalid certificate for {}", identificationCode); + throw ce; + } + } + } + } + /** * Find id-kaart (o=Identity card of Estonian citizen) and digi-id (o=Digital identity card) * authentication (ou=Authentication) certificate for each ESTEID identification code from sk ESTEID LDAP and @@ -242,7 +253,9 @@ public static class CertificateData { @Nullable private BigInteger serialNumber; - public CertificateData() { } + public CertificateData() { + // utility class + } public PublicKey getPublicKey() { return this.publicKey; diff --git a/cdoc2-lib/src/test/java/ee/cyber/cdoc2/KeyUtil.java b/cdoc2-lib/src/test/java/ee/cyber/cdoc2/KeyUtil.java index 89d96e15..86284107 100644 --- a/cdoc2-lib/src/test/java/ee/cyber/cdoc2/KeyUtil.java +++ b/cdoc2-lib/src/test/java/ee/cyber/cdoc2/KeyUtil.java @@ -17,7 +17,7 @@ public final class KeyUtil { @SuppressWarnings({"checkstyle:OperatorWrap", "squid:S6706"}) - private static final String bobKeyPem = """ + private static final String BOB_KEY_PEM = """ -----BEGIN EC PRIVATE KEY----- MIGkAgEBBDAFxoHAdX8mU9cjiXOy46Gljmongxto0nHwRQs5cb93vIcysAaYLmhL mH4DPqnSXJWgBwYFK4EEACKhZANiAAR5Yacpp5H4aBAIxkDtdBXcw/BFyMNEQu4B @@ -33,7 +33,7 @@ public static KeyPairGenerator getKeyPairRsaInstance() throws NoSuchAlgorithmExc } public static KeyPair createKeyPair() throws Exception { - return PemTools.loadKeyPair(bobKeyPem); + return PemTools.loadKeyPair(BOB_KEY_PEM); } public static PublicKey createPublicKey() throws Exception { diff --git a/cdoc2-lib/src/test/java/ee/cyber/cdoc2/container/EnvelopeTestUtils.java b/cdoc2-lib/src/test/java/ee/cyber/cdoc2/container/EnvelopeTestUtils.java index c0e32099..0fbf3a60 100644 --- a/cdoc2-lib/src/test/java/ee/cyber/cdoc2/container/EnvelopeTestUtils.java +++ b/cdoc2-lib/src/test/java/ee/cyber/cdoc2/container/EnvelopeTestUtils.java @@ -171,8 +171,6 @@ static byte[] createTarWithExtraData() throws IOException { log.debug("Compressed {} into {}", randomBytes.length, destTarZlib.size()); - // Tar is able to process empty tar without exceptions - //assertTrue(Tar.listFiles(new ByteArrayInputStream(destTarZlib.toByteArray())).isEmpty()); return destTarZlib.toByteArray(); } @@ -180,7 +178,6 @@ static byte[] createTarWithIllegalFileType() throws IOException { String validFileName = "validFile"; byte[] data = new byte[10 * 1024]; - //new Random().nextBytes(data); ByteArrayOutputStream dest = new ByteArrayOutputStream(); diff --git a/cdoc2-lib/src/test/java/ee/cyber/cdoc2/container/TarDeflateTest.java b/cdoc2-lib/src/test/java/ee/cyber/cdoc2/container/TarDeflateTest.java index 30f788a7..362f04ce 100644 --- a/cdoc2-lib/src/test/java/ee/cyber/cdoc2/container/TarDeflateTest.java +++ b/cdoc2-lib/src/test/java/ee/cyber/cdoc2/container/TarDeflateTest.java @@ -132,13 +132,11 @@ void testArchiveData(@TempDir Path tempDir) throws IOException { void testTarGzBomb(@TempDir Path tempDir) throws IOException { byte[] zeros = new byte[1024]; //1KB + // can multiply with 1024 ones more for 1GM size long bigFileSize = 1024 //1KB * 1024; //1MB - //*1024 //1GB - //; Path bombPath = tempDir.resolve("bomb.tgz"); - //bombPath.toFile().deleteOnExit(); try (TarArchiveOutputStream tarOs = new TarArchiveOutputStream(new DeflateCompressorOutputStream( new BufferedOutputStream(Files.newOutputStream(bombPath))))) { @@ -161,14 +159,14 @@ void testTarGzBomb(@TempDir Path tempDir) throws IOException { tarOs.closeArchiveEntry(); } - Path outDir = tempDir.resolve("testTarGzBomb"); Files.createDirectories(outDir); log.debug("Extracting {} to {}", bombPath, outDir); - Exception exception = assertThrows(IllegalStateException.class, () -> { - try (TarDeflate tar = new TarDeflate(Files.newInputStream(bombPath))) { + InputStream inputStream = Files.newInputStream(bombPath); + Exception exception = assertThrows(IllegalStateException.class, () -> { + try (TarDeflate tar = new TarDeflate(inputStream)) { tar.extractToDir(outDir); } }); @@ -198,7 +196,7 @@ void testMaxExtractEntries(@TempDir Path tempDir) { @Test void shouldValidateFileNameWhenCreatingTar(@TempDir Path tempDir) throws IOException { - File outputTarFile = tempDir.resolve(TGZ_FILE_NAME).toFile(); + tempDir.resolve(TGZ_FILE_NAME).toFile(); assertFalse(INVALID_FILE_NAMES.isEmpty()); @@ -206,9 +204,10 @@ void shouldValidateFileNameWhenCreatingTar(@TempDir Path tempDir) throws IOExcep for (String fileName: INVALID_FILE_NAMES) { File file = createAndWriteToFile(tempDir, fileName, PAYLOAD); OutputStream os = new ByteArrayOutputStream(); + List files = List.of(file); assertThrows( InvalidPathException.class, - () -> Tar.archiveFiles(os, List.of(file)), + () -> Tar.archiveFiles(os, files), "File with name '" + file + "' should not be allowed in created tar" ); } @@ -243,7 +242,7 @@ void shouldValidateFileNameWhenExtractingTar(@TempDir Path tempDir) throws IOExc File file = createTar(tempDir, TGZ_FILE_NAME + '.' + i++, fileName, PAYLOAD); var result = new TarDeflate(new FileInputStream(file)) .extractFilesToDir(List.of(fileName), tempDir); - assertTrue(result.size() == 1); + assertEquals(1, result.size()); } } @@ -284,7 +283,7 @@ void findZlibMinSize() throws IOException { } @Test - void shouldSupportLongFileName(@TempDir Path tempDir) throws IOException { + void shouldSupportLongFileName() throws IOException { byte[] data = {0x00}; ByteArrayOutputStream destTarZ = new ByteArrayOutputStream(); diff --git a/cdoc2-lib/src/test/java/ee/cyber/cdoc2/crypto/ChaChaChipherTest.java b/cdoc2-lib/src/test/java/ee/cyber/cdoc2/crypto/ChaChaChipherTest.java index 8c1ccff7..2e7642e3 100644 --- a/cdoc2-lib/src/test/java/ee/cyber/cdoc2/crypto/ChaChaChipherTest.java +++ b/cdoc2-lib/src/test/java/ee/cyber/cdoc2/crypto/ChaChaChipherTest.java @@ -94,11 +94,6 @@ void testTarGZipChaChaCipherStream() byte[] additionalData = Envelope.getAdditionalData(header, headerHMAC); String payload = "secret"; - - //Path encryptedPath = Path.of(System.getProperty("java.io.tmpdir")).resolve( "encrypted.tar.gz"); - //encrypted.toFile().deleteOnExit(); - - ByteBuffer encryptedTarGzBuf; String tarEntryName = "payload-" + UUID.randomUUID(); @@ -168,7 +163,7 @@ void testChaChaCipherSpeed(@TempDir Path tempDir) throws IOException, GeneralSec String bigFileNameEncrypted = "bigFile.enc"; byte[] buf = new byte[4096]; - int read = 0; + int read; long totalread = 0; byte[] oneMb = new byte[1024 * 1024]; // 1 MB @@ -199,9 +194,9 @@ void testChaChaCipherSpeed(@TempDir Path tempDir) throws IOException, GeneralSec totalread += read; } } + assertTrue(totalread > 0); log.debug("Read {}B in {} seconds", totalread, Duration.between(readStart, Instant.now()).toSeconds()); - log.debug("Encrypting"); OutputStream destChaChaStream = Files.newOutputStream(tempDir.resolve(bigFileNameEncrypted)); InputStream inputStream = Files.newInputStream(biggerFile.toPath()); @@ -219,7 +214,6 @@ void testChaChaCipherSpeed(@TempDir Path tempDir) throws IOException, GeneralSec Instant decryptStart = Instant.now(); log.debug("Decrypting {}", tempDir.resolve(bigFileNameEncrypted)); - read = 0; totalread = 0; try (CipherInputStream cis = ChaChaCipher.initChaChaInputStream( Files.newInputStream(tempDir.resolve(bigFileNameEncrypted)), cek, aad)) { @@ -227,9 +221,8 @@ void testChaChaCipherSpeed(@TempDir Path tempDir) throws IOException, GeneralSec totalread += read; } } + assertTrue(totalread > 0); log.debug("Decrypted {}B in {} seconds", totalread, Duration.between(decryptStart, Instant.now()).toSeconds()); - } - } diff --git a/cdoc2-lib/src/test/java/ee/cyber/cdoc2/crypto/ECKeysTest.java b/cdoc2-lib/src/test/java/ee/cyber/cdoc2/crypto/ECKeysTest.java index 73c3c410..98db1758 100644 --- a/cdoc2-lib/src/test/java/ee/cyber/cdoc2/crypto/ECKeysTest.java +++ b/cdoc2-lib/src/test/java/ee/cyber/cdoc2/crypto/ECKeysTest.java @@ -37,6 +37,7 @@ class ECKeysTest { private static final Logger log = LoggerFactory.getLogger(ECKeysTest.class); @Test + @SuppressWarnings({"java:S1481", "java:S1854"}) void testBigInteger() { byte[] neg = new BigInteger("-255").toByteArray(); //0xff, 0x01 byte[] neg254 = new BigInteger("-254").toByteArray(); //0xff, 0x02 @@ -70,12 +71,14 @@ void testEcPubKeyEncodeDecode() throws GeneralSecurityException { void testLoadEcPrivKey() throws GeneralSecurityException, IOException { @SuppressWarnings("checkstyle:OperatorWrap") String privKeyPem = - "-----BEGIN EC PRIVATE KEY-----\n" + - "MIGkAgEBBDBh1UAT832Nh2ZXvdc5JbNv3BcEZSYk90esUkSPFmg2XEuoA7avS/kd\n" + - "4HtHGRbRRbagBwYFK4EEACKhZANiAASERl1rD+bm2aoiuGicY8obRkcs+jt8ks4j\n" + - "C1jD/f/EQ8KdFYrJ+KwnM6R8rIXqDnUnLJFiF3OzDpu8TUjVOvdXgzQL+n67QiLd\n" + - "yerTE6f5ujIXoXNkZB8O2kX/3vADuDA=\n" + - "-----END EC PRIVATE KEY-----\n"; + """ + -----BEGIN EC PRIVATE KEY----- + MIGkAgEBBDBh1UAT832Nh2ZXvdc5JbNv3BcEZSYk90esUkSPFmg2XEuoA7avS/kd + 4HtHGRbRRbagBwYFK4EEACKhZANiAASERl1rD+bm2aoiuGicY8obRkcs+jt8ks4j + C1jD/f/EQ8KdFYrJ+KwnM6R8rIXqDnUnLJFiF3OzDpu8TUjVOvdXgzQL+n67QiLd + yerTE6f5ujIXoXNkZB8O2kX/3vADuDA= + -----END EC PRIVATE KEY----- + """; // openssl ec -in key.pem -text -noout // read EC key @@ -108,11 +111,13 @@ void testLoadEcPubKey() throws GeneralSecurityException, IOException { //openssl ecparam -name secp384r1 -genkey -noout -out key.pem //openssl ec -in key.pem -pubout -out public.pem @SuppressWarnings("checkstyle:OperatorWrap") - String pubKeyPem = "-----BEGIN PUBLIC KEY-----\n" + - "MHYwEAYHKoZIzj0CAQYFK4EEACIDYgAEhEZdaw/m5tmqIrhonGPKG0ZHLPo7fJLO\n" + - "IwtYw/3/xEPCnRWKyfisJzOkfKyF6g51JyyRYhdzsw6bvE1I1Tr3V4M0C/p+u0Ii\n" + - "3cnq0xOn+boyF6FzZGQfDtpF/97wA7gw\n" + - "-----END PUBLIC KEY-----\n"; + String pubKeyPem = """ + -----BEGIN PUBLIC KEY----- + MHYwEAYHKoZIzj0CAQYFK4EEACIDYgAEhEZdaw/m5tmqIrhonGPKG0ZHLPo7fJLO + IwtYw/3/xEPCnRWKyfisJzOkfKyF6g51JyyRYhdzsw6bvE1I1Tr3V4M0C/p+u0Ii + 3cnq0xOn+boyF6FzZGQfDtpF/97wA7gw + -----END PUBLIC KEY----- + """; // openssl ec -in key.pem -text -noout // read EC key @@ -144,7 +149,7 @@ void testLoadEcPubKey() throws GeneralSecurityException, IOException { assertTrue(ECKeys.isEcSecp384r1Curve(ecPublicKey)); - log.debug("{} {}", ECKeys.getCurveOid(ecPublicKey), ecPublicKey.getParams().toString()); + log.debug("{} {}", ECKeys.getCurveOid(ecPublicKey), ecPublicKey.getParams()); assertEquals(expectedHex, HexFormat.of().formatHex(ECKeys.encodeEcPubKeyForTls(ecPublicKey))); } @@ -281,19 +286,21 @@ void testLoadKeyPairFromPemShort() throws GeneralSecurityException, IOException ECPrivateKey ecPrivKey = (ECPrivateKey) keyPair.getPrivate(); ECPublicKey ecPublicKey = (ECPublicKey) keyPair.getPublic(); - //log.debug("key: {}", ecPrivKey.getS().toString(16)); + if (log.isDebugEnabled()) { + log.debug("key: {}", ecPrivKey.getS().toString(16)); + } assertTrue(KeyAlgorithm.isEcKeysAlgorithm(ecPrivKey.getAlgorithm())); assertEquals(expectedSecretHex, ecPrivKey.getS().toString(16)); - - //log.debug("pub: {}", HexFormat.of().formatHex(ECKeys.encodeEcPubKeyForTls(ecPublicKey))); + if (log.isDebugEnabled()) { + log.debug("pub: {}", HexFormat.of().formatHex(ECKeys.encodeEcPubKeyForTls(ecPublicKey))); + } assertTrue(KeyAlgorithm.isEcKeysAlgorithm(ecPublicKey.getAlgorithm())); assertEquals(expectedPubHex, HexFormat.of().formatHex(ECKeys.encodeEcPubKeyForTls(ecPublicKey))); } - @Test - void testLoadCertWithLabel() throws CertificateException, IOException { + void testLoadCertWithLabel() throws CertificateException { @SuppressWarnings("checkstyle:OperatorWrap") final String igorCertificate = @@ -351,7 +358,7 @@ public static ECPublicKey getInfinityPublicKey() throws InvalidParameterSpecExce ECParameterSpec ecParameterSpec = params.getParameterSpec(ECParameterSpec.class); - ECPublicKey infinityPublicKey = new ECPublicKey() { + return new ECPublicKey() { @Override public ECPoint getW() { return ECPoint.POINT_INFINITY; @@ -377,8 +384,6 @@ public ECParameterSpec getParams() { return ecParameterSpec; } }; - - return infinityPublicKey; } @Test diff --git a/cdoc2-lib/src/test/java/ee/cyber/cdoc2/crypto/RsaTest.java b/cdoc2-lib/src/test/java/ee/cyber/cdoc2/crypto/RsaTest.java index edeea0ee..5955b7a0 100644 --- a/cdoc2-lib/src/test/java/ee/cyber/cdoc2/crypto/RsaTest.java +++ b/cdoc2-lib/src/test/java/ee/cyber/cdoc2/crypto/RsaTest.java @@ -21,7 +21,7 @@ class RsaTest { // openssl genrsa -out rsa_priv.pem 2048 @SuppressWarnings({"checkstyle:OperatorWrap", "squid:S6706"}) - static final String rsaKeyPem = + static final String RSA_KEY_PEM = """ -----BEGIN RSA PRIVATE KEY----- MIIEogIBAAKCAQEAs18v09QVTnzSTRrFnVhkxDWM2rSHOua2rPz60CVazfOk5Vv9 @@ -63,7 +63,7 @@ class RsaTest { // INTEGER 65537 // openssl rsa -in rsa_priv.pem -outform PEM -pubout -out rsa_pub.pem @SuppressWarnings("checkstyle:OperatorWrap") - static final String pubKeyPem = """ + static final String PUB_KEY_PEM = """ -----BEGIN PUBLIC KEY----- MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAs18v09QVTnzSTRrFnVhk xDWM2rSHOua2rPz60CVazfOk5Vv9Jo4Nq6Uzo3yWS4DZ+3JgO5iRntFeI0NWZGsP @@ -81,7 +81,7 @@ class RsaTest { // INTEGER (2048 bit) 226435949622400733452861302723380091312050670462871263385722374431288… // INTEGER 65537 @SuppressWarnings("checkstyle:OperatorWrap") - static final String pubKeyRSAPublicKeyB64 = + static final String PUB_KEY_RSA_PUB_KEY_B64 = //-----BEGIN RSA PUBLIC KEY----- "MIIBCgKCAQEAs18v09QVTnzSTRrFnVhkxDWM2rSHOua2rPz60CVazfOk5Vv9Jo4N" + "q6Uzo3yWS4DZ+3JgO5iRntFeI0NWZGsPGbMWGWKlb4OYlbK0gnBdwsi4LS6LnRx7" + @@ -119,8 +119,8 @@ static void checkRsaEncryption(String plainSecret, RSAPublicKey publicKey, RSAPr @Test void testLoadRsaKeys() throws Exception { - PublicKey publicKey = PemTools.loadPublicKey(pubKeyPem); - KeyPair keyPair = PemTools.loadKeyPair(rsaKeyPem); + PublicKey publicKey = PemTools.loadPublicKey(PUB_KEY_PEM); + KeyPair keyPair = PemTools.loadKeyPair(RSA_KEY_PEM); assertTrue(KeyAlgorithm.isRsaKeysAlgorithm(keyPair.getPublic().getAlgorithm())); assertEquals(publicKey, keyPair.getPublic()); @@ -130,19 +130,19 @@ void testLoadRsaKeys() throws Exception { @Test void testRsaPubKeyEncode() throws IOException { - RSAPublicKey rsaPublicKey = (RSAPublicKey) PemTools.loadPublicKey(pubKeyPem); + RSAPublicKey rsaPublicKey = (RSAPublicKey) PemTools.loadPublicKey(PUB_KEY_PEM); byte[] encoded = RsaUtils.encodeRsaPubKey(rsaPublicKey); - assertEquals(pubKeyRSAPublicKeyB64, Base64.getEncoder().encodeToString(encoded)); + assertEquals(PUB_KEY_RSA_PUB_KEY_B64, Base64.getEncoder().encodeToString(encoded)); } @Test void testRsaPubKeyDecode() throws IOException, GeneralSecurityException { - byte[] rsaPubDer = Base64.getDecoder().decode(pubKeyRSAPublicKeyB64); + byte[] rsaPubDer = Base64.getDecoder().decode(PUB_KEY_RSA_PUB_KEY_B64); RSAPublicKey rsaPublicKey = RsaUtils.decodeRsaPubKey(rsaPubDer); - RSAPublicKey expected = (RSAPublicKey) PemTools.loadPublicKey(pubKeyPem); + RSAPublicKey expected = (RSAPublicKey) PemTools.loadPublicKey(PUB_KEY_PEM); assertEquals(expected, rsaPublicKey); } diff --git a/cdoc2-schema/src/test/java/ee/cyber/cdoc2/fbs/header/FbsHeaderTest.java b/cdoc2-schema/src/test/java/ee/cyber/cdoc2/fbs/header/FbsHeaderTest.java index 59b670d8..6471f3c1 100644 --- a/cdoc2-schema/src/test/java/ee/cyber/cdoc2/fbs/header/FbsHeaderTest.java +++ b/cdoc2-schema/src/test/java/ee/cyber/cdoc2/fbs/header/FbsHeaderTest.java @@ -9,18 +9,19 @@ import com.google.flatbuffers.FlatBufferBuilder; -import java.io.IOException; import java.nio.ByteBuffer; import java.util.Arrays; import static ee.cyber.cdoc2.fbs.header.Capsule.recipients_KeyServerCapsule; + class FbsHeaderTest { public static final int KEYLEN_BYTES = 256 / 8; @Test - void testFbsHeaderSerialization() throws IOException { + @SuppressWarnings("java:S125") + void testFbsHeaderSerialization() { byte payloadEnc = PayloadEncryptionMethod.CHACHA20POLY1305;