vico
vico

Reputation: 18175

Error while initializing Cipher

I have function that crypts string:

BASE64Decoder decoder = new BASE64Decoder();
BASE64Encoder encoder = new BASE64Encoder();

public String encryptValueWithBlowfish(String data, String secretKey) {

    Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
    try {
        SecretKeySpec key = new SecretKeySpec(decoder.decodeBuffer(secretKey), "Blowfish");
        Cipher cipher = Cipher.getInstance("Blowfish/CBC/NoPadding", "BC");
        String iv = "\0\0\0\0\0\0\0\0";
        IvParameterSpec ivs = new IvParameterSpec(iv.getBytes());
        cipher.init(Cipher.ENCRYPT_MODE, key, ivs);
        MessageDigest sha = MessageDigest.getInstance("SHA-1");
        return encoder.encode(sha.digest(cipher.doFinal(decoder.decodeBuffer(data))));
    } catch (Exception e) {
        lg.info("Failed to encryptValueWithBlowfish: " + e.getMessage());
        return "";
    }
}

Line cipher.init(Cipher.ENCRYPT_MODE, key, ivs); rises exception "Unsupported keysize or algorithm parameters". This code forks fine in another Linux machine. Parameters passed in both cases are the same. I'm not strong in crypto things. What might be wrong?

Upvotes: 0

Views: 827

Answers (1)

Jon Skeet
Jon Skeet

Reputation: 1499840

What might be wrong?

Well, you're using the default character encoding here: iv.getBytes() - that's never a good start. Perhaps the two different machines have different default encodings.

If you want to create a byte array of all-zeroes and a particular size, why not just use:

IvParameterSpec ivs = new IvParameterSpec(new byte[8]);

Or use 16 if you wanted a 16 byte IV.

It's not clear what decoder is here - but you use it twice and again, if that's using the default character encoding it could vary by machine.

Upvotes: 1

Related Questions