use of org.bouncycastle.crypto.PBEParametersGenerator in project robovm by robovm.
the class BcKeyStoreSpi method engineStore.
public void engineStore(OutputStream stream, char[] password) throws IOException {
DataOutputStream dOut = new DataOutputStream(stream);
byte[] salt = new byte[STORE_SALT_SIZE];
int iterationCount = MIN_ITERATIONS + (random.nextInt() & 0x3ff);
random.nextBytes(salt);
dOut.writeInt(version);
dOut.writeInt(salt.length);
dOut.write(salt);
dOut.writeInt(iterationCount);
HMac hMac = new HMac(new SHA1Digest());
MacOutputStream mOut = new MacOutputStream(hMac);
PBEParametersGenerator pbeGen = new PKCS12ParametersGenerator(new SHA1Digest());
byte[] passKey = PBEParametersGenerator.PKCS12PasswordToBytes(password);
pbeGen.init(passKey, salt, iterationCount);
if (version < 2) {
hMac.init(pbeGen.generateDerivedMacParameters(hMac.getMacSize()));
} else {
hMac.init(pbeGen.generateDerivedMacParameters(hMac.getMacSize() * 8));
}
for (int i = 0; i != passKey.length; i++) {
passKey[i] = 0;
}
saveStore(new TeeOutputStream(dOut, mOut));
byte[] mac = new byte[hMac.getMacSize()];
hMac.doFinal(mac, 0);
dOut.write(mac);
dOut.close();
}
use of org.bouncycastle.crypto.PBEParametersGenerator in project samourai-wallet-android by Samourai-Wallet.
the class AESUtil method encryptWithSetMode.
public static String encryptWithSetMode(String cleartext, CharSequenceX password, int iterations, int mode, @Nullable BlockCipherPadding padding) throws DecryptionException, UnsupportedEncodingException {
final int AESBlockSize = 4;
if (password == null) {
throw new DecryptionException("Password null");
}
// Use secure random to generate a 16 byte iv
SecureRandom random = new SecureRandom();
byte[] iv = new byte[AESBlockSize * 4];
random.nextBytes(iv);
byte[] clearbytes = cleartext.getBytes("UTF-8");
PBEParametersGenerator generator = new PKCS5S2ParametersGenerator();
generator.init(PBEParametersGenerator.PKCS5PasswordToUTF8Bytes(password.toString().toCharArray()), iv, iterations);
KeyParameter keyParam = (KeyParameter) generator.generateDerivedParameters(256);
CipherParameters params = new ParametersWithIV(keyParam, iv);
BlockCipher cipherMode;
if (mode == MODE_CBC) {
cipherMode = new CBCBlockCipher(new AESEngine());
} else {
// mode == MODE_OFB
cipherMode = new OFBBlockCipher(new AESEngine(), 128);
}
BufferedBlockCipher cipher;
if (padding != null) {
cipher = new PaddedBufferedBlockCipher(cipherMode, padding);
} else {
cipher = new BufferedBlockCipher(cipherMode);
}
cipher.reset();
cipher.init(true, params);
byte[] outBuf = cipherData(cipher, clearbytes);
// Append to IV to the output
int len1 = iv.length;
int len2 = outBuf.length;
byte[] ivAppended = new byte[len1 + len2];
System.arraycopy(iv, 0, ivAppended, 0, len1);
System.arraycopy(outBuf, 0, ivAppended, len1, len2);
// String ret = Base64.encodeBase64String(ivAppended);
byte[] raw = Base64.encodeBase64(ivAppended);
return new String(raw);
}
Aggregations