如何将字符串转换为128或256位密钥以进行chacha20加密。
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()";
}
}
其中
private String key2 = "19920099-564A-4869-99B3-363F8145C0BB";
private String plaintext = "Hello";
我也试过不同的钥匙。但它需要key2将其转换为128或256位。我搜索过SO。并找到一些链接
Java 256-bit AES Password-Based Encryption
Turn String to 128-bit key for AES
但这些看起来与我的要求无关
答案 0 :(得分:0)
没有破折号的密钥是一个完全有效的128位十六进制密钥。它是32个字符,即16个字节=> 128位。
您所要做的就是:
key2.replace("-","");
javax.xml.bind.DatatypeConverter
。像这样使用它:DatatypeConverter.parseHexBinary(hexString);
您的完整电话应如下所示:
chaCha20Encryptor.encrypt(
plaintext.getBytes(),
DatatypeConverter.parseHexBinary(key2.replace("-","")));