Skip to content

Commit

Permalink
Merge pull request #7 from OlesjaSmirnov/RM-3063
Browse files Browse the repository at this point in the history
RM-3063: Fix SonarQube found issues
  • Loading branch information
OlesjaAarma authored Sep 2, 2024
2 parents b322ff5 + 77e1590 commit e56017a
Show file tree
Hide file tree
Showing 37 changed files with 182 additions and 162 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -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<Void> {

Expand Down Expand Up @@ -105,9 +105,6 @@ public Void call() throws Exception {
Arrays.toString(inputFiles));
}




CDocBuilder cDocBuilder = new CDocBuilder()
.withPayloadFiles(Arrays.asList(inputFiles));

Expand All @@ -116,7 +113,6 @@ public Void call() throws Exception {
cDocBuilder.withServerProperties(p);
}


List<EncryptionKeyMaterial> symmetricKMs =
SymmetricKeyUtil.getEncryptionKeyMaterialFromFormattedSecrets(recipient.secrets);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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<Void> {
// commented out until public key server is in live
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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")
Expand All @@ -44,18 +43,15 @@ private void setProperty(Map<String, String> props) {

@Override
public Void call() throws Exception {


List<Recipient> recipients = Envelope.parseHeader(Files.newInputStream(cdocFile.toPath()));
for (Recipient recipient: recipients) {

String type = getHumanReadableType(recipient);

Map<String, String> 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(
Expand All @@ -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) {
Expand All @@ -81,4 +77,5 @@ String getHumanReadableType(Recipient recipient) {
return recipient.getClass().toString();
}
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -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<Void> {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import ee.cyber.cdoc2.cli.CDocCli;
package cli;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
Expand All @@ -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;
Expand Down Expand Up @@ -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);
Expand Down
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
package cli;

import org.junit.jupiter.api.Test;

import ee.cyber.cdoc2.crypto.Crypto;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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<Void> {

private static final Logger log = LoggerFactory.getLogger(ConverterCmd.class);
Expand Down Expand Up @@ -48,8 +48,6 @@ public class ConverterCmd implements Callable<Void> {
@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) {
Expand All @@ -61,7 +59,6 @@ public static void main(String... args) {
System.exit(exitCode);
}


@Override
public Void call() throws Exception {

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -27,6 +29,7 @@ private static void purgeDirectory(File dir) {
if (file.isDirectory())
purgeDirectory(file);
file.delete();
log.info("Directory " + dir + " was deleted");
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -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();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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);

Expand Down Expand Up @@ -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");
}
}
}
Expand All @@ -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());
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -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
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand All @@ -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() {
Expand Down Expand Up @@ -59,4 +61,5 @@ public int hashCode() {
result = 31 * result + Arrays.hashCode(encryptedFmk);
return result;
}

}
2 changes: 1 addition & 1 deletion cdoc2-lib/src/main/java/ee/cyber/cdoc2/crypto/Crypto.java
Original file line number Diff line number Diff line change
Expand Up @@ -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");
Expand Down
4 changes: 3 additions & 1 deletion cdoc2-lib/src/main/java/ee/cyber/cdoc2/crypto/ECKeys.java
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}

Expand Down
Loading

0 comments on commit e56017a

Please sign in to comment.