【发布时间】:2016-06-27 09:39:32
【问题描述】:
如何将字符串转换为 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
但这些看起来与我的要求无关
【问题讨论】:
-
如果
key2的生成具有非常好的随机性,并且在破折号旁边没有内部结构,那么简单的散列可能足以获得 128 位密钥。
标签: java android string encryption byte