返回字节数组时出错

时间:2016-04-19 15:45:24

标签: java encryption

我正在使用以下代码

 public byte[] encrypt(byte[] unencryptedString,String k)throws Exception {
    String encryptedString = null;

    String k1 = String.format("%024d", Integer.parseInt(k));
    myEncryptionKey = k1;
    myEncryptionScheme = DESEDE_ENCRYPTION_SCHEME;
    arrayBytes = myEncryptionKey.getBytes(UNICODE_FORMAT);
    ks = new DESedeKeySpec(arrayBytes);
    skf = SecretKeyFactory.getInstance(myEncryptionScheme);
    cipher = Cipher.getInstance(myEncryptionScheme);
    key = skf.generateSecret(ks);

    try {
        cipher.init(Cipher.ENCRYPT_MODE, key);
        byte[] plainText =
                unencryptedString/*.getBytes(UNICODE_FORMAT)*/;
        byte[] encryptedText = cipher.doFinal(plainText);
       // encryptedString = new String(Base64.encodeBase64(encryptedText));
    } catch (Exception e) {
        e.printStackTrace();
    }
    return encryptedText;
}

return语句给出以下错误:

  

encryptedText无法解析为变量

4 个答案:

答案 0 :(得分:2)

与其他答案相反,如果您未对文本进行加密,我将不会更改您的代码以返回null - 我会让这个失败冒出来作为例外。我不会声明您的方法可以抛出Exception - 我指定它可以抛出哪些异常。您可以在非常细粒度的级别上执行此操作,或者在这种情况下使用GeneralSecurityException,其中包含您感兴趣的所有加密特定的例外。

我进一步停止使用不必要的字段 - 您不需要在此更改任何状态。

完成所有这些重构后,您的方法将成为:

public static byte[] encrypt(String unencryptedString, String k)
    throws GeneralSecurityException {
    String keySpecText = String.format("%024d", Integer.parseInt(k));
    byte[] keySpecBytes = keySpecText.getBytes(StandardCharsets.UTF_16);
    KeySpec ks = new DESedeKeySpec(keySpecBytes);
    SecretKeyFactory skf = SecretKeyFactory.getInstance(DESEDE_ENCRYPTION_SCHEME);
    Key key = skf.generateSecret(ks);
    Cipher cipher = Cipher.getInstance(DESEDE_ENCRYPTION_SCHEME);
    cipher.init(Cipher.ENCRYPT_MODE, key);
    byte[] plainText = unencryptedString.getBytes(StandardCharsets.UTF_16);
    return cipher.doFinal(plainText);
}

我完全不确定这是提供密钥的好方法 - 您在这里仅限于2个 32 键,这不是很好,即使你对此感到满意,为什么要为密钥而不是int取一个字符串?但至少代码会编译,当它失败时它会正常失败。

答案 1 :(得分:0)

在范围的开头声明变量,因为在try块中它甚至可能不存在。所以你不能回报smth。可能不存在。

把它放在那里

String encryptedString = null;
byte[] encryptedText

答案 2 :(得分:0)

encrytpedText只有try块内的范围。试试这个:

byte[] encrytpedText = null;
try {
    cipher.init(Cipher.ENCRYPT_MODE, key);
    byte[] plainText =
            unencryptedString/*.getBytes(UNICODE_FORMAT)*/;
    encryptedText = cipher.doFinal(plainText);
   // encryptedString = new String(Base64.encodeBase64(encryptedText));
} catch (Exception e) {
    e.printStackTrace();
}
return encryptedText;

答案 3 :(得分:0)

AES所有长度128,192,256位加密中都很有用。

只需更改KEY_LEN_IN_BITS静态值。

我们走了 -

private static final String ALGORITHM = "AES/CBC/PKCS5Padding";
private static int ITERATIONS = 65536;
private static SecretKey secretKey = null;
final private static short KEY_LEN_IN_BITS = (short)128;
final private static byte[] BUFFER = new byte[1024 * 64];

private static byte[] generateSalt() throws NoSuchAlgorithmException {  
    Random random = SecureRandom.getInstance("SHA1PRNG");
    byte[] salt = new byte[8];
    random.nextBytes(salt);
    return salt;
}

static ArrayList<Object> encrypt256(final FileInputStream fis, final String encryptFileTarget, final String fileTitle, final String keyVal) throws Exception{

    final ArrayList<Object> encryptInfo = new ArrayList<Object>();

    try{
        byte[] saltBytes = new byte[8];
        saltBytes = generateSalt();

        SecretKeyFactory skf = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
        KeySpec spec = new PBEKeySpec(keyVal.toCharArray(), saltBytes, ITERATIONS, KEY_LEN_IN_BITS);
        secretKey = skf.generateSecret(spec);
        SecretKey secret = new SecretKeySpec(secretKey.getEncoded(), "AES");//"ISO-8859-1"

        Cipher cipher = Cipher.getInstance(ALGORITHM);
        cipher.init(Cipher.ENCRYPT_MODE, secret);

        AlgorithmParameters params = cipher.getParameters ();
        byte[] initIVVector = params.getParameterSpec (IvParameterSpec.class).getIV();

        FileOutputStream fos = new FileOutputStream(encryptFileTarget, true);
        CipherOutputStream cos = new CipherOutputStream(fos, cipher);

        InputStream is = new BufferedInputStream(fis);
        int bytesRead = -1;
        int count = 0;

        while((bytesRead = is.read(BUFFER)) != -1){
            //System.out.println("bytesRead values is : " + bytesRead);
            cos.write(BUFFER, 0, bytesRead);
        }

        cos.flush();
        cos.close();
        is.close();
        fos.flush();
        fos.close();
        fis.close();

        encryptInfo.add(Hex.encodeHexString(initIVVector));
        encryptInfo.add(Hex.encodeHexString(saltBytes));

    }catch(Exception exp){
        exp.printStackTrace();
    }

    return encryptInfo;
}