Martin Fric
Martin Fric

Reputation: 730

Java throws clause - sonarqube issue

I have kind of old code where we run sonarqube. I am not expert on Java and Exception descendants etc. so I hope someone will be able to help me to fix this issue, as Sonar says it is a blocker.

This is the code:

package xxx;

import java.io.UnsupportedEncodingException;
import java.security.InvalidKeyException;
import java.security.Key;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.KeyGenerator;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.SecretKeySpec;

public class Encryptor {

    private static final String ALGORITHM = "AES";

    private static final String defaultSecretKey = "xxx";

    private Key secretKeySpec;

    public Encryptor() throws InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException,
            UnsupportedEncodingException {
        this(null);
    }

    public Encryptor(String secretKey) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException,
            UnsupportedEncodingException {
        this.secretKeySpec = generateKey(secretKey);
    }

    public String encrypt(String plainText) throws InvalidKeyException, NoSuchAlgorithmException,
            NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException, UnsupportedEncodingException {
        Cipher cipher = Cipher.getInstance(ALGORITHM);
        cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec);
        byte[] encrypted = cipher.doFinal(plainText.getBytes("UTF-8"));
        return asHexString(encrypted);
    }

    public String decrypt(String encryptedString) throws InvalidKeyException, IllegalBlockSizeException,
            BadPaddingException, NoSuchAlgorithmException, NoSuchPaddingException {
        Cipher cipher = Cipher.getInstance(ALGORITHM);
        cipher.init(Cipher.DECRYPT_MODE, secretKeySpec);
        byte[] original = cipher.doFinal(toByteArray(encryptedString));
        return new String(original);
    }

    private Key generateKey(String secretKey) throws UnsupportedEncodingException, NoSuchAlgorithmException {
        if (secretKey == null) {
            secretKey = defaultSecretKey;
        }
        byte[] key = (secretKey).getBytes("UTF-8");
        MessageDigest sha = MessageDigest.getInstance("SHA-256");
        key = sha.digest(key);
        key = Arrays.copyOf(key, 16); // use only the first 128 bit

        KeyGenerator kgen = KeyGenerator.getInstance("AES");
        kgen.init(256); // 192 and 256 bits may not be available

        return new SecretKeySpec(key, ALGORITHM);
    }

    private final String asHexString(byte buf[]) {
        StringBuffer strbuf = new StringBuffer(buf.length * 2);
        int i;
        for (i = 0; i < buf.length; i++) {
            if (((int) buf[i] & 0xff) < 0x10) {
                strbuf.append("0");
            }
            strbuf.append(Long.toString((int) buf[i] & 0xff, 16));
        }
        return strbuf.toString();
    }

    private final byte[] toByteArray(String hexString) {
        int arrLength = hexString.length() >> 1;
        byte buf[] = new byte[arrLength];
        for (int ii = 0; ii < arrLength; ii++) {
            int index = ii << 1;
            String l_digit = hexString.substring(index, index + 2);
            buf[ii] = (byte) Integer.parseInt(l_digit, 16);
        }
        return buf;
    }

    public static void main(String[] args) throws Exception {
        if (args.length == 1) {
            String plainText = args[0];
            Encryptor aes = new Encryptor();
            String encryptedString = aes.encrypt(plainText);
            //this line only ensures that decryption works
            String decryptedString = aes.decrypt(encryptedString);
            System.out.println("Original Password: " + plainText + " and Encrypted Password: " + encryptedString);
        } else {
            System.out.println("USAGE: java AES string-to-encrypt");
        }
    }
}

And problem is on this line:

public static void main(String[] args) throws Exception {

Sonar says Remove this throws clause

Does anybody know how to fix this or why is this happening?

Thanks a lot.

M.

Upvotes: 0

Views: 683

Answers (2)

Glains
Glains

Reputation: 2863

It is always a good apprach to use the least common denominator, or more specific, the exception class that provides the best abstraction over all of its descendents.

Consider the following method declaration:

public String encrypt(String plainText) 
    throws InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException,
        UnsupportedEncodingException, IllegalBlockSizeException, BadPaddingException,
        UnsupportedEncodingException  {
    // body
}

A closer inspection of all those exceptions reveals that all of them extend GeneralSecurityException. Therefore, you can refactor the above code as:

public String encrypt(String plainText) throws GeneralSecurityException,
    UnsupportedEncodingException  {
    // body
}

The only exception, which does not inherit GeneralSecurityException, is UnsupportedEncodingException so you have to explicitly declare it.

Think of it from the client side: Which version would you rather use?

try {
    String encrypted = cipher.encrypt("Test");
} catch(InvalidKeyException | NoSuchAlgorithmException | NoSuchPaddingException
        | UnsupportedEncodingException | IllegalBlockSizeException | BadPaddingException e) {
    // cannot encrypt
} catch(UnsupportedEncodingException e) {
    // wrong encoding
}
try {
    String encrypted = cipher.encrypt("Test");
} catch(GeneralSecurityException e) {
    // cannot encrypt
} catch(UnsupportedEncodingException e) {
    // wrong encoding
}

Upvotes: 0

Martin Fric
Martin Fric

Reputation: 730

Thanks to all comments:

This is solution (removal of generic exception and adding explicit exceptions):

public static void main(String[] args) throws InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException, UnsupportedEncodingException, IllegalBlockSizeException, BadPaddingException {

Upvotes: 0

Related Questions