4

所以我正在编写一个程序来加密和解密文本文件,但是当我使用“Blowfish”以外的加密(例如“Blowfish/CBC/PKCS5Padding”)时,我似乎总是遇到这个错误。我得到的例外是:

Exception in thread "main" java.security.NoSuchAlgorithmException: Blowfish/CBC/PKCS5Padding KeyGenerator not available
    at javax.crypto.KeyGenerator.<init>(DashoA13*..)
    at javax.crypto.KeyGenerator.getInstance(DashoA13*..)
    at Encryptor.<init>(Encryptor.java:87)
    at Encryptor.main(Encryptor.java:30)

我的一部分代码:

import java.security.MessageDigest;
import java.security.SecureRandom;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

public class Encryptor2 {
    private IvParameterSpec ivSpec;
    private SecretKeySpec keySpec;
    private Cipher cipher;

    public static void main(String[] args) throws Exception {
        Encryptor2 e = new Encryptor2(
                "averylongtext!@$@#$#@$#*&(*&}{23432432432dsfsdf");
        String enc = e.encrypt("john doe");
        String dec = e.decrypt(enc);
    }

    public Encryptor2(String pass) throws Exception {
        // setup AES cipher in CBC mode with PKCS #5 padding
        cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");

        // setup an IV (initialization vector) that should be
        // randomly generated for each input that's encrypted
        byte[] iv = new byte[cipher.getBlockSize()];
        new SecureRandom().nextBytes(iv);
        ivSpec = new IvParameterSpec(iv);

        // hash keyString with SHA-256 and crop the output to 128-bit for key
        MessageDigest digest = MessageDigest.getInstance("SHA-256");
        digest.update(pass.getBytes());
        byte[] key = new byte[16];
        System.arraycopy(digest.digest(), 0, key, 0, key.length);
        keySpec = new SecretKeySpec(key, "AES");
    }

    public String encrypt(String original) throws Exception {
        cipher.init(Cipher.ENCRYPT_MODE, keySpec, ivSpec);
        byte[] encrypted = cipher.doFinal(original.getBytes("UTF-8"));
        System.out.println("encrypted: `" + new String(encrypted) + "`");
        return new String(encrypted);
    }

    public String decrypt(String encrypted) throws Exception {
        cipher.init(Cipher.DECRYPT_MODE, keySpec, ivSpec);
        byte[] decrypted = cipher.doFinal(encrypted.getBytes("UTF-8"));
        System.out.println("decrypted: `" + new String(decrypted, "UTF-8")
                + "`");
        return new String(decrypted, "UTF-8");
    }
}

但现在它失败了Input length must be multiple of 16 when decrypting with padded cipher

4

1 回答 1

8

您使用算法指定的附加参数适用于Cipher. 对于KeyGenerator并且SecretKeySpec您只指定算法。其他参数用于密码操作模式和要使用的填充。例如,如果您在 CBC 模式下使用 Blowfish 并带有您想要的 PKCS #5 填充:

KeyGenerator keyGen = KeyGenerator.getInstance("Blowfish");
Cipher cipher = Cipher.getInstance("Blowfish/CBC/PKCS5Padding");

有关示例,请参阅使用 Java 加密和解密:无法获得相同的输出。它使用与您相同的模式和填充。唯一的区别是使用 AES 而不是 Blowfish,但它的工作原理完全相同。

于 2011-04-23T10:49:56.640 回答