I use keystore to generate a key for encryption. It worked fine, but somehow it stopped generating the key. Below is the code:
private void createKey() throws NoSuchProviderException,
NoSuchAlgorithmException, InvalidAlgorithmParameterException {
Calendar start = new GregorianCalendar();
Calendar end = new GregorianCalendar();
end.add(Calendar.YEAR, 1);
Context context = SNContext.getInstance().getContext();
KeyPairGeneratorSpec spec =
new KeyPairGeneratorSpec.Builder(context)
.setAlias(FNConstants.ALIAS)
.setSubject(new X500Principal(String.format("CN=%s, OU=%s", FNConstants.ALIAS, context.getPackageName())))
.setSerialNumber(BigInteger.valueOf(1337))
.setStartDate(start.getTime())
.setEndDate(end.getTime())
.build();
KeyPairGenerator kpGenerator = KeyPairGenerator
.getInstance(FNConstants.TYPE_RSA,
FNConstants.KEYSTORE_PROVIDER_ANDROID);
kpGenerator.initialize(spec);
KeyPair kp = kpGenerator.generateKeyPair();
}
Now, when I try to get this key in my encryption method, I get the record value as null. I am doing something wrong in ks.load (null). I tested it before and it worked fine.
public static String encryptData(String inputStr) throws KeyStoreException,
UnrecoverableEntryException, NoSuchAlgorithmException, InvalidKeyException,
SignatureException, IOException, CertificateException, NoSuchProviderException, NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException {
String result = "";
KeyStore ks = KeyStore.getInstance(FNConstants.KEYSTORE_PROVIDER_ANDROID);
ks.load(null);
KeyStore.Entry entry = ks.getEntry(FNConstants.ALIAS, null);
if (entry == null) {
return null;
}
PublicKey publicKey = ks.getCertificate(FNConstants.ALIAS).getPublicKey();
byte[] encodedBytes = null;
Cipher cipher = Cipher.getInstance(FNConstants.TRANSFORMATION, FNConstants.PROVIDER);
cipher.init(Cipher.ENCRYPT_MODE, publicKey);
encodedBytes = cipher.doFinal(inputStr.getBytes());
result = Base64.encodeToString(encodedBytes, Base64.DEFAULT);
return result;
}
source
share