IllegalArgumentException ChaCha20 requires 128 bit or 256 bit key

走远了吗. 提交于 2019-12-13 05:54:44

问题


How could I convert String to 128 or 256 bit key for chacha20 Encryption .

    ChaCha20Encryptor chaCha20Encryptor = new ChaCha20Encryptor();
    byte[] data = chaCha20Encryptor.encrypt(plaintext.getBytes(),key2.getBytes());
    String enStr = BaseUtilityHelper.encodeBase64URLSafeString(data);
    encryptedTv.setText(enStr);

ChaCha20Encryptor

public class ChaCha20Encryptor implements Encryptor {

    private final byte randomIvBytes[] = {0, 1, 2, 3, 4, 5, 6, 7};

    static {
        Security.addProvider(new BouncyCastleProvider());
    }

    @Override
    public byte[] encrypt(byte[] data, byte[] randomKeyBytes) throws IOException, InvalidKeyException,
            InvalidAlgorithmParameterException, InvalidCipherTextException {

        ChaChaEngine cipher = new ChaChaEngine();
        cipher.init(true, new ParametersWithIV(new KeyParameter(randomKeyBytes), randomIvBytes));

        byte[] result = new byte[data.length];
        cipher.processBytes(data, 0, data.length, result, 0);
        return result;
    }

    @Override
    public byte[] decrypt(byte[] data, byte[] randomKeyBytes)
            throws InvalidKeyException, InvalidAlgorithmParameterException, IOException,
            IllegalStateException, InvalidCipherTextException {

        ChaChaEngine cipher = new ChaChaEngine();
        cipher.init(false, new ParametersWithIV(new KeyParameter(randomKeyBytes), randomIvBytes));

        byte[] result = new byte[data.length];
        cipher.processBytes(data, 0, data.length, result, 0);
        return result;
    }

    @Override
    public int getKeyLength() {
        return 32;
    }

    @Override
    public String toString() {
        return "ChaCha20()";
    }
}

where

private String key2 = "19920099-564A-4869-99B3-363F8145C0BB";
private String plaintext = "Hello";

I have also tried different keys. but it requires key2 to convert it to 128 or 256 bits. I have searched on SO. and find some links

Java 256-bit AES Password-Based Encryption

Turn String to 128-bit key for AES

but these doesn't look like relevant to my requirement


回答1:


Your key, without the dashes, is a perfectly valid 128 bits hexadecimal key. It is 32 characters, which is 16 bytes => 128 bits.

All you have to do is :

  1. remove the dashes key2.replace("-","");
  2. Convert the hexadecimal String to its byte[] representation. I personally use javax.xml.bind.DatatypeConverter available for java 1.7 and above. Use it like this : DatatypeConverter.parseHexBinary(hexString);

Your complete call should look like this :

chaCha20Encryptor.encrypt(
             plaintext.getBytes(),
             DatatypeConverter.parseHexBinary(key2.replace("-","")));


来源:https://stackoverflow.com/questions/38050559/illegalargumentexception-chacha20-requires-128-bit-or-256-bit-key

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!