Java throws子句-Sonarqube问题

问题描述

我有一些旧的代码用于运行声纳。我不是Java和Exception后代等方面的专家,所以我希望有人能够帮助我解决此问题,就像Sonar所说的那样,它是一个 blocker

这是代码:

    <div class="additional-guests ml-3">
            </div>
            
                <div class="form-group">
        <button type="button" id="new-guest-button" class="btn btn-secondary btn-block">
            Weiterer Gast
        </button>
    </div>

问题就在这条线上:

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,InvalidKeyException,UnsupportedEncodingException {
        this.secretKeySpec = generateKey(secretKey);
    }

    public String encrypt(String plainText) throws InvalidKeyException,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,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");
        }
    }
}

声纳说 删除此throw子句

有人知道如何解决此问题或为什么会发生这种情况?

非常感谢。

M。

解决方法

感谢所有评论:

这是解决方案(删除通用异常并添加显式异常):

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

使用最小公分母,或更具体地讲,为所有后代提供最佳抽象的异常类始终是一个好方法。

考虑以下方法声明:

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

仔细检查所有这些异常,发现它们都扩展了GeneralSecurityException。因此,您可以将上述代码重构为:

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

唯一不继承GeneralSecurityException的异常是UnsupportedEncodingException,因此您必须显式声明它。

从客户端考虑:您希望使用哪个版本?

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
}

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...