AES-GCM:用Java加密文件,然后用JavaScript解密

时间:2020-05-20 06:19:27

标签: javascript java aes aes-gcm

我正在尝试用Java加密文件并将其解密,然后将其显示给UI。 我使用以下方法进行加密

public static void encrypt(String path, String key) {
    File f = new File(path);
    byte[] fileBytes = readFile(f);
    try {
        // // Prepare the nonce
        SecureRandom secureRandom = new SecureRandom();
        // Noonce should be 12 bytes
        byte[] iv = new byte[12];
        secureRandom.nextBytes(iv);

        // Another way
        SecretKeySpec secretKeySpec = generateSecretKeySpec(key);

        Cipher cipher = Cipher.getInstance("AES/GCM/PKCS5Padding");
        GCMParameterSpec ivSpec = new GCMParameterSpec(16 * Byte.SIZE, iv);

        // Encryption mode on!
        cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec, ivSpec);

        // Encrypt the data
        byte[] encryptedData = cipher.doFinal(fileBytes);

        // Concatenate everything and return the final data
        ByteBuffer resultBytes = ByteBuffer.allocate(4 + 12 + encryptedData.length);
        resultBytes.putInt(12);
        resultBytes.put(iv);
        resultBytes.put(encryptedData);

        Files.delete(f.toPath());

        writeFile(f.getAbsolutePath(), resultBytes.array());
    } catch (IOException | NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException
        | InvalidAlgorithmParameterException | IllegalBlockSizeException | BadPaddingException e) {
        LOGGER.error(e.getMessage());
    }
}

 public static SecretKeySpec generateSecretKeySpec(String password) {
    // Hashing key.
    MessageDigest md;
    byte[] hashedPassword = null;
    try {
        md = MessageDigest.getInstance("SHA-256");
        hashedPassword = md.digest(password.getBytes(StandardCharsets.UTF_8));

    } catch (NoSuchAlgorithmException e) {
        LOGGER.error(e.getMessage());
    }
    return new SecretKeySpec(hashedPassword, "AES");
}

public static byte[] readFile(File file) {

    byte[] fileData = new byte[(int) file.length()];

    try (FileInputStream fileInputStream = new FileInputStream(file)) {
        fileInputStream.read(fileData);
    } catch (IOException e) {
        LOGGER.error(e.getMessage());
    }

    return fileData;
}

public static void writeFile(String path, byte[] data) {

    try (FileOutputStream fileOutputStream = new FileOutputStream(path)) {
        fileOutputStream.write(data);
    } catch (IOException e) {
        LOGGER.error(e.getMessage());
    }
}

我在reactjs上找到了可以在GCM上运行的库,但是其中一些不能在IE11上运行。 因此,我尝试使用sjcl.mode.gcm,但无法使其在后端运行。

有没有人可以帮助我使其工作或建议我使用另一个库。

0 个答案:

没有答案