繁体   English   中英

使用Java加密并使用Java解密Zip文件

[英]Encrypt in Javascript and Decrypt in Java For Zip File

我想用javascript加密本地zip文件,然后用java解密。

我使用了来自此链接的代码https://www.devglan.com/corejava/aes-encryption-javascript-and-decryption-in-java

用JavaScript加密

var AesUtil = function (keySize, iterationCount) {
    this.keySize = keySize / 32;
    this.iterationCount = iterationCount;
};

AesUtil.prototype.generateKey = function (salt, passPhrase) {
    var key = CryptoJS.PBKDF2(
        passPhrase,
        CryptoJS.enc.Hex.parse(salt),
        {keySize: this.keySize, iterations: this.iterationCount});
    return key;
};

AesUtil.prototype.encrypt = function (salt, iv, passPhrase, plainText) {
    var key = this.generateKey(salt, passPhrase);
    var encrypted = CryptoJS.AES.encrypt(
        plainText,
        key,
        {iv: CryptoJS.enc.Hex.parse(iv)});
    return encrypted.ciphertext.toString(CryptoJS.enc.Base64);
};

AesUtil.prototype.decrypt = function (salt, iv, passPhrase, cipherText) {
    var key = this.generateKey(salt, passPhrase);
    var cipherParams = CryptoJS.lib.CipherParams.create({
        ciphertext: CryptoJS.enc.Base64.parse(cipherText)
    });
    var decrypted = CryptoJS.AES.decrypt(
        cipherParams,
        key,
        {iv: CryptoJS.enc.Hex.parse(iv)});
    return decrypted.toString(CryptoJS.enc.Utf8);


};

var CryptoJS = require('crypto-js'),
    fs = require('fs');

var data = fs.readFileSync("C:\\<my_path>\\scripts.zip");

var passPhrase = "123456789123456789";
var iv = "a145525c53eafb0258999612b13d9d3e"; //CryptoJS.lib.WordArray.random(128 / 8).toString(CryptoJS.enc.Hex);
var salt = "ca70e17a698096cfb42047926713dd62";// CryptoJS.lib.WordArray.random(128 / 8).toString(CryptoJS.enc.Hex);

var aesUtil = new AesUtil(128, 1000);
var ciphertext = aesUtil.encrypt(salt, iv, passPhrase, data.toString());

fs.writeFileSync('C:/Output.encrypted', ciphertext);

Java中的解密是这样的: AesUtil.java

import org.apache.commons.codec.DecoderException;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.codec.binary.Hex;

import javax.crypto.*;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.SecretKeySpec;
import java.io.UnsupportedEncodingException;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.KeySpec;

public class AesUtil {
    private final int keySize;
    private final int iterationCount;
    private final Cipher cipher;

    public AesUtil(int keySize, int iterationCount) {
        this.keySize = keySize;
        this.iterationCount = iterationCount;
        try {
            cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        }
        catch (NoSuchAlgorithmException | NoSuchPaddingException e) {
            throw fail(e);
        }
    }

    public String decrypt(String salt, String iv, String passphrase, String ciphertext) {
        try {
            SecretKey key = generateKey(salt, passphrase);
            byte[] decrypted = doFinal(Cipher.DECRYPT_MODE, key, iv, base64(ciphertext));
            return new String(decrypted, "UTF-8");
        }
        catch (UnsupportedEncodingException e) {
            return null;
        }catch (Exception e){
            return null;
        }
    }

    public byte[] doFinal(int encryptMode, SecretKey key, String iv, byte[] bytes) {
        try {
            cipher.init(encryptMode, key, new IvParameterSpec(hex(iv)));
            return cipher.doFinal(bytes);
        }
        catch (InvalidKeyException
                | InvalidAlgorithmParameterException
                | IllegalBlockSizeException
                | BadPaddingException e) {
            return null;
        }
    }

    public SecretKey generateKey(String salt, String passphrase) {
        try {
            SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
            KeySpec spec = new PBEKeySpec(passphrase.toCharArray(), hex(salt), iterationCount, keySize);
            SecretKey key = new SecretKeySpec(factory.generateSecret(spec).getEncoded(), "AES");
            return key;
        }
        catch (NoSuchAlgorithmException | InvalidKeySpecException e) {
            return null;
        }
    }

    public static byte[] base64(String str) {
        return Base64.decodeBase64(str);
    }

    public static byte[] hex(String str) {
        try {
            return Hex.decodeHex(str.toCharArray());
        }
        catch (DecoderException e) {
            throw new IllegalStateException(e);
        }
    }

    private IllegalStateException fail(Exception e) {
        return null;
    }

}

主要方法:

private static void mainScan(String[] args) {
        try {
            String keyString = "123456789123456789";


            int keySize = 128;
            int iterationCount = 1000;
            String iv = "a145525c53eafb0258999612b13d9d3e";
            String salt = "ca70e17a698096cfb42047926713dd62";
            AesUtil aesUtil = new AesUtil(keySize, iterationCount);


            String encryptedPath = "C:/Output.encrypted";
            String decryptedPath = "C:/Output.zip";


            String fileString = new String(Files.readAllBytes(Paths.get(encryptedPath)));
            String decryptedText = aesUtil.decrypt(salt, iv, keyString, fileString);

            FileUtils.writeStringToFile(new File(decryptedPath), decryptedText);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

但仍然,在解密后,我得到了一个比原始zip更大的zip文件,它不是有效的zip文件。

  • 注意:当文本仅是字符串并且未从文件获取字符串到文件时,此代码有效

在大多数语言中,将Zip文件之类的二进制内容当作字符串来对待通常是一个大错误。 在Javascript方面,CryptoJS希望将任意字节序列作为CryptoJS.lib.WordArray参数提供。

所以,代替

var ciphertext = aesUtil.encrypt(salt, iv, passPhrase, data.toString());

你应该有

var ciphertext = aesUtil.encrypt(salt, iv, passPhrase, CryptoJS.lib.WordArray.create(data));

在Java方面,将函数delete更改为返回byte[]

public byte[] decrypt(String salt, String iv, String passphrase, String ciphertext) {
    SecretKey key = generateKey(salt, passphrase);
    byte[] decrypted = doFinal(Cipher.DECRYPT_MODE, key, iv, base64(ciphertext));
    return decrypted;
}

并且main ,将代码更改为类似

String fileString = new String(Files.readAllBytes(Paths.get(encryptedPath)));
byte [] decryptedText = aesUtil.decrypt(salt, iv, keyString, fileString);
Files.write(Paths.get(decryptedPath), decryptedText);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM