Android securely store a string into KeyStore - java

I know it's not secure to store a String into Keystore but I need it at this point. I am super new to cryptography and asymmetric in particular.
I am trying to store a String (and the private key) in the keystore using RSA algorithm. This is what I did so far and it worked but is this the easiest way to do it?
NOTE 1: I support only API 21 and newer so should I use keystore or keychain instead?
NOTE 2: It does not work on API 23 M it give an error when casting the private key to RSAPrivateKey
public static final String TAG = KeyStoreManager.class.getName();
static final String CIPHER_TYPE = "RSA/ECB/PKCS1Padding";
static final String CIPHER_PROVIDER = "AndroidOpenSSL";
public static final String PHRASE_ALIAS = "phrase";
public static final String ANDROID_KEY_STORE = "AndroidKeyStore";
public static final String MIHAIL_GUTAN_X500 = "CN=some name";
public static boolean setKeyStoreString(String fileName, String strToStore, String alias, Context context) {
try {
KeyStore keyStore = KeyStore.getInstance(ANDROID_KEY_STORE);
keyStore.load(null);
int nBefore = keyStore.size();
// Create the keys if necessary
if (!keyStore.containsAlias(alias)) {
Calendar notBefore = Calendar.getInstance();
Calendar notAfter = Calendar.getInstance();
notAfter.add(Calendar.YEAR, 1);
KeyPairGenerator generator = KeyPairGenerator.getInstance(
KeyProperties.KEY_ALGORITHM_RSA, ANDROID_KEY_STORE);
KeyPairGeneratorSpec spec = new KeyPairGeneratorSpec.Builder(context)
.setAlias(alias)
.setKeyType(KeyProperties.KEY_ALGORITHM_RSA)
.setKeySize(2048)
.setSubject(new X500Principal(MIHAIL_GUTAN_X500))
.setSerialNumber(BigInteger.ONE)
.setStartDate(notBefore.getTime())
.setEndDate(notAfter.getTime())
.build();
generator.initialize(spec);
KeyPair keyPair = generator.generateKeyPair(); // needs to be here
Log.v(TAG, "The keypair" + keyPair.toString());
}
int nAfter = keyStore.size();
Log.v(TAG, "Before = " + nBefore + " After = " + nAfter);
// Retrieve the keys
KeyStore.PrivateKeyEntry privateKeyEntry = (KeyStore.PrivateKeyEntry) keyStore.getEntry(alias, null);
RSAPrivateKey privateKey = (RSAPrivateKey) privateKeyEntry.getPrivateKey();
RSAPublicKey publicKey = (RSAPublicKey) privateKeyEntry.getCertificate().getPublicKey();
Log.v(TAG, "private key = " + privateKey.toString());
Log.v(TAG, "public key = " + publicKey.toString());
// Encrypt the text
String dataDirectory = context.getApplicationInfo().dataDir;
String filesDirectory = context.getFilesDir().getAbsolutePath();
String encryptedDataFilePath = filesDirectory + File.separator + fileName;
Log.v(TAG, "strPhrase = " + strToStore);
Log.v(TAG, "dataDirectory = " + dataDirectory);
Log.v(TAG, "filesDirectory = " + filesDirectory);
Log.v(TAG, "encryptedDataFilePath = " + encryptedDataFilePath);
Cipher inCipher = Cipher.getInstance(CIPHER_TYPE, CIPHER_PROVIDER);
inCipher.init(Cipher.ENCRYPT_MODE, publicKey);
CipherOutputStream cipherOutputStream =
new CipherOutputStream(
new FileOutputStream(encryptedDataFilePath), inCipher);
cipherOutputStream.write(strToStore.getBytes("UTF-8"));
cipherOutputStream.close();
return true;
} catch (NoSuchAlgorithmException e) {
Log.e(TAG, Log.getStackTraceString(e));
} catch (NoSuchProviderException e) {
Log.e(TAG, Log.getStackTraceString(e));
} catch (InvalidAlgorithmParameterException e) {
Log.e(TAG, Log.getStackTraceString(e));
} catch (KeyStoreException e) {
Log.e(TAG, Log.getStackTraceString(e));
} catch (CertificateException e) {
Log.e(TAG, Log.getStackTraceString(e));
} catch (IOException e) {
Log.e(TAG, Log.getStackTraceString(e));
} catch (UnrecoverableEntryException e) {
Log.e(TAG, Log.getStackTraceString(e));
} catch (NoSuchPaddingException e) {
Log.e(TAG, Log.getStackTraceString(e));
} catch (InvalidKeyException e) {
Log.e(TAG, Log.getStackTraceString(e));
} catch (UnsupportedOperationException e) {
Log.e(TAG, Log.getStackTraceString(e));
}
return false;
}
then I retrieve the string:
public static String getKeyStoreString(String fileName, String alias, Context context) {
KeyStore keyStore;
String recoveredSecret = "";
String filesDirectory = context.getFilesDir().getAbsolutePath();
String encryptedDataFilePath = filesDirectory + File.separator + fileName;
try {
keyStore = KeyStore.getInstance(ANDROID_KEY_STORE);
keyStore.load(null);
// Retrieve the keys
KeyStore.PrivateKeyEntry privateKeyEntry = (KeyStore.PrivateKeyEntry)
keyStore.getEntry(alias, null);
RSAPrivateKey privateKey = (RSAPrivateKey) privateKeyEntry.getPrivateKey();
Cipher outCipher = Cipher.getInstance(CIPHER_TYPE, CIPHER_PROVIDER);
outCipher.init(Cipher.DECRYPT_MODE, privateKey);
CipherInputStream cipherInputStream = new CipherInputStream(
new FileInputStream(encryptedDataFilePath), outCipher);
byte[] roundTrippedBytes = new byte[1000];
int index = 0;
int nextByte;
while ((nextByte = cipherInputStream.read()) != -1) {
roundTrippedBytes[index] = (byte) nextByte;
index++;
}
recoveredSecret = new String(roundTrippedBytes, 0, index, "UTF-8");
Log.e(TAG, "round tripped string = " + recoveredSecret);
} catch (KeyStoreException e) {
e.printStackTrace();
} catch (UnrecoverableEntryException e) {
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (CertificateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (NoSuchProviderException e) {
e.printStackTrace();
} catch (NoSuchPaddingException e) {
e.printStackTrace();
} catch (InvalidKeyException e) {
e.printStackTrace();
} catch (NullPointerException e) {
e.printStackTrace();
}
Log.e(TAG, "recovered: " + recoveredSecret);
return recoveredSecret;
}

Related

FileNotFound Exception When Trying To Read File Using getServletContext().getRealPath()

My program is able to create and write to a file using the path-file:
private static final String PUBLIC_KEY_FILE = "WebContent/Config/MyPublic.key";
private static final String PRIVATE_KEY_FILE = "WebContent/Config/MyPrivate.key";
And the correct files are generated within the folders according to the path declared above.
But then a FileNotFoundException error occurs when I try to read from those files using the path files:
private String REAL_PUBLIC_PATH = getServletContext().getRealPath("/WebContent/Config/MyPublic.key");
private String REAL_PRIVATE_PATH = getServletContext().getRealPath("/WebContent/Config/MyPrivate.key");
This is the lines of code that is causing the error:
PublicKey pubKey = readPublicKeyFromFile(this.REAL_PUBLIC_PATH);
PrivateKey privKey = readPrivateKeyFromFile(this.REAL_PRIVATE_PATH);
Which is tied to the variables REAL_PUBLIC_PATH and REAL_PUBLIC_PATH. Meaning there's something wrong with how the path file is being read.
My folder structure goes:
> MyProject
>Web-Content
>Config
>MyPublic.key
>MyPrivate.key
>WEB-INF
>META-INF
My full class code is below for context:
public class RSAEncryptionHelper extends HttpServlet {
private static final String PUBLIC_KEY_FILE = "WebContent/Config/MyPublic.key";
private static final String PRIVATE_KEY_FILE = "WebContent/Config/MyPrivate.key";
private String REAL_PUBLIC_PATH = getServletContext().getRealPath("/WebContent/Config/MyPublic.key");
private String REAL_PRIVATE_PATH = getServletContext().getRealPath("/WebContent/Config/MyPrivate.key");
public static void main(String[] args) throws IOException{
try
{
System.out.println("--GENERATE PUBLIC and PRIVATE KEY --");
KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
keyPairGenerator.initialize(2048); //1024 for normal securities
KeyPair keyPair = keyPairGenerator.generateKeyPair();
PublicKey publicKey = keyPair.getPublic();
PrivateKey privateKey = keyPair.getPrivate();
System.out.println("\n--PULLING OUT PARAMETERS WHICH MAKES KEYPAIR--\n");
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
RSAPublicKeySpec rsaPubKeySpec = keyFactory.getKeySpec(publicKey, RSAPublicKeySpec.class);
RSAPrivateKeySpec rsaPrivKeySpec = keyFactory.getKeySpec(privateKey, RSAPrivateKeySpec.class);
System.out.println("\n--SAVING PUBLIC KEY AND PRIVATE KEY TO FILES--\n");
RSAEncryptionHelper rsaObj = new RSAEncryptionHelper();
rsaObj.saveKeys(PUBLIC_KEY_FILE, rsaPubKeySpec.getModulus(), rsaPubKeySpec.getPublicExponent());
rsaObj.saveKeys(PRIVATE_KEY_FILE, rsaPrivKeySpec.getModulus(), rsaPrivKeySpec.getPrivateExponent());
}
catch (NoSuchAlgorithmException | InvalidKeySpecException e)
{
System.out.println(e);
}
}
private void saveKeys(String fileName, BigInteger mod, BigInteger exp) throws IOException {
FileOutputStream fos = null;
ObjectOutputStream oos = null;
try
{
System.out.println("Generating: " + fileName + "...");
fos = new FileOutputStream(fileName);
oos = new ObjectOutputStream(new BufferedOutputStream(fos));
oos.writeObject(mod);
oos.writeObject(exp);
System.out.println(fileName + "generated successfully");;
}
catch (Exception e)
{
e.printStackTrace();
}
finally
{
if (oos!=null)
{
oos.close();
if (fos!= null)
{
fos.close();
}
}
}
}
public PublicKey readPublicKeyFromFile(String fileName) throws IOException{
FileInputStream fis = null;
ObjectInputStream ois = null;
PublicKey publicKey = null;
try
{
fis = new FileInputStream(new File(fileName));
ois = new ObjectInputStream(fis);
BigInteger modulus = (BigInteger) ois.readObject();
BigInteger exponent = (BigInteger) ois.readObject();
//Get Public Key
RSAPublicKeySpec rsaPublicKeySpec = new RSAPublicKeySpec(modulus, exponent);
KeyFactory fact = KeyFactory.getInstance("RSA");
publicKey = fact.generatePublic(rsaPublicKeySpec);
return publicKey;
}
catch (IOException e)
{
e.printStackTrace();
}
catch (ClassNotFoundException e)
{
e.printStackTrace();
}
catch (NoSuchAlgorithmException e)
{
e.printStackTrace();
}
catch (InvalidKeySpecException e)
{
e.printStackTrace();
}
finally
{
if (ois != null)
{
ois.close();
if (fis != null)
{
fis.close();
}
}
}
return publicKey;
}
public PrivateKey readPrivateKeyFromFile(String fileName) throws IOException{
FileInputStream fis = null;
ObjectInputStream ois = null;
PrivateKey privateKey = null;
try
{
fis = new FileInputStream(new File(fileName));
ois = new ObjectInputStream(fis);
BigInteger modulus = (BigInteger) ois.readObject();
BigInteger exponent = (BigInteger) ois.readObject();
//Get Public Key
RSAPrivateKeySpec rsaPrivateKeySpec = new RSAPrivateKeySpec(modulus, exponent);
KeyFactory fact = KeyFactory.getInstance("RSA");
privateKey = fact.generatePrivate(rsaPrivateKeySpec);
return privateKey;
}
catch (IOException e)
{
e.printStackTrace();
}
catch (ClassNotFoundException e)
{
e.printStackTrace();
}
catch (NoSuchAlgorithmException e)
{
e.printStackTrace();
}
catch (InvalidKeySpecException e)
{
e.printStackTrace();
}
finally
{
if (ois != null)
{
ois.close();
if (fis != null)
{
fis.close();
}
}
}
return privateKey;
}
public byte[] encryptData(String data) throws IOException {
System.out.println("\n--ENCRYPTION STARTED--");
System.out.println("Data Before Encryption: " + data);
byte[] dataToEncrypt = data.getBytes();
byte[] encryptedData = null;
try
{
PublicKey pubKey = readPublicKeyFromFile(this.REAL_PUBLIC_PATH);
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.ENCRYPT_MODE, pubKey);
encryptedData = cipher.doFinal(dataToEncrypt);
System.out.println("Encrypted Data: " + encryptedData);
}
catch (IOException e)
{
e.printStackTrace();
}
catch (NoSuchAlgorithmException e)
{
e.printStackTrace();
}
catch (InvalidKeyException e)
{
e.printStackTrace();
}
catch (IllegalBlockSizeException e)
{
e.printStackTrace();
}
catch (BadPaddingException e)
{
e.printStackTrace();
}
catch (NoSuchPaddingException e)
{
e.printStackTrace();
}
System.out.println("--ENCRYPTION COMPLETED--");
return encryptedData;
}
public String decryptData(byte[] data) throws IOException {
System.out.println("\n--DECRYPTION STARTED--");
byte[] decryptedData = null;
String decData = "";
try
{
PrivateKey privateKey = readPrivateKeyFromFile(this.REAL_PRIVATE_PATH);
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.DECRYPT_MODE, privateKey);
decryptedData = cipher.doFinal(data);
decData = new String(decryptedData);
System.out.println("Decrypted Data: " + decData);
return decData;
}
catch (IOException e)
{
e.printStackTrace();
}
catch (NoSuchAlgorithmException e)
{
e.printStackTrace();
}
catch (NoSuchPaddingException e)
{
e.printStackTrace();
}
catch (InvalidKeyException e)
{
e.printStackTrace();
}
catch ( IllegalBlockSizeException e)
{
e.printStackTrace();
}
catch (BadPaddingException e)
{
e.printStackTrace();
}
System.out.println("--DECRYPTION COMPLETED--");
return decData;
}
}
Do your keys already exist before you run the program? if not, then getRealPath to a file that doesn't exist isn't going to work.
But that shouldn't matter because if you can access the files using private static final String PUBLIC_KEY_FILE, why not use that same path to read the files.
So instead of this:
PrivateKey privateKey = readPrivateKeyFromFile(this.REAL_PRIVATE_PATH);
Why not do this?
PrivateKey privateKey = readPrivateKeyFromFile(this.PRIVATE_KEY_FILE);
If you've sucessfully written to a file using PRIVATE_KEY_FILE path, you can also read from the same path.

Android RSA decryption using private key, non-sense result

I am doing RSA decryption in my Android project, and somehow the result makes non-sense. I am showing my code here:
private static final int MAX_DECRYPT_BLOCK = 256;
private static RSAPrivateKey loadPrivateKey(InputStream in) throws Exception {
RSAPrivateKey priKey;
try {
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String readLine = null;
StringBuilder sb = new StringBuilder();
while ((readLine = br.readLine()) != null) {
if (readLine.charAt(0) == '-') {
continue;
} else {
sb.append(readLine);
sb.append('\r');
}
}
byte[] priKeyData = Base64.decode(new String(sb), Base64.NO_WRAP);
PKCS8EncodedKeySpec keySpec= new PKCS8EncodedKeySpec(priKeyData);
KeyFactory keyFactory= KeyFactory.getInstance("RSA",new BouncyCastleProvider());
priKey= (RSAPrivateKey) keyFactory.generatePrivate(keySpec);
} catch (IOException e) {
throw new Exception("error reading the key");
} catch (NullPointerException e) {
throw new Exception("inputstream is null");
}
return priKey;
}
/**
* decrypt with a private key
*
* #param privateKey
* #param cipherData
* #return
* #throws Exception
*/
private static byte[] decrypt(RSAPrivateKey privateKey, byte[] cipherData) throws Exception {
if (privateKey == null) {
throw new Exception("key is null");
}
Cipher cipher = null;
try {
cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.DECRYPT_MODE, privateKey);
int inputLen = cipherData.length;
ByteArrayOutputStream out = new ByteArrayOutputStream();
int offSet = 0;
byte[] cache;
int i = 0;
while (inputLen - offSet > 0) {
if (inputLen - offSet > MAX_DECRYPT_BLOCK) {
cache = cipher.doFinal(cipherData, offSet, MAX_DECRYPT_BLOCK);
} else {
cache = cipher.doFinal(cipherData, offSet, inputLen - offSet);
}
out.write(cache, 0, cache.length);
i++;
offSet = i * MAX_DECRYPT_BLOCK;
}
byte[] decryptedData = out.toByteArray();
out.close();
return decryptedData;
} catch (NoSuchAlgorithmException e) {
throw new Exception("no such algorithm");
} catch (NoSuchPaddingException e) {
e.printStackTrace();
return null;
} catch (InvalidKeyException e) {
throw new Exception("InvalidKeyException");
} catch (IllegalBlockSizeException e) {
throw new Exception("IllegalBlockSizeException");
} catch (BadPaddingException e) {
throw new Exception("BadPaddingException");
}
}
public static String RSADecrypt(Context context, String KeyFileNameInAssetFolder, byte[] content) {
try {
InputStream inputStream = context.getResources().getAssets().open(KeyFileNameInAssetFolder);
RSAPrivateKey privateKey = loadPrivateKey(inputStream);
byte[] b = decrypt(privateKey, content);
return new String(b,"utf-8");
} catch (Exception e) {
e.printStackTrace();
}
return "error";
}
and I am calling with this statement:
String result = RSAUtils.RSADecrypt(getApplicationContext(), Constant.PRIVATE_KEY_PKCS8_FILE_NAME,Base64.decode(qrcode_result,Base64.NO_WRAP));
And this is the private key:
> -----BEGIN PRIVATE KEY-----
MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQCsQTbkXviKG1od
wVp0t15JB4OkdDUo8O36/yzLoJmsmPf3yFzAJ3YzEAaWAKKpUx92c9yfW4vW849F
pno/GUJLwPkIG5ss1YR55P5UI76kpLM74ZXume9+WfEuQ3B/HHkcnmCVl4CV/Xqq
4X4d3Rc7zGTbGSHdVui1QJ5ubQoqHjSGaO9j2SvMsqDSU20S1DjrL/8sb0e7B63a
fJVzOZFi7E62zqYzfBOEupY+24Ac8i7s8tyX3Bd4OJ1zdQ+si5yeIkaRiD8ZeUbJ
3yS2MlUohvuwmJy7uxpP8mYXmaXM1ZtMFLaLRUc4leA7KDRlDXHJLSYAkFxCyw8J
RTK2QOcTAgMBAAECggEARRrUnsHLC/z1JkLPu0tlM/8jvPIx8X7Wun9sxTRk8m1b
7bggHaa3ML0ZJ0yR9UQ3txm8ROJBM7b6n4KuQGotwp5kSfBpTI9MWmqX7cF5ViwN
C9TwhYyUHCiRLXI4y4XswKJ5NQpWt9W9RJi6M9ji3Uaen5dxko6vRSfrZ3mvPj2/
blW5HV8j3RIzJ3942CzQw2IX/hQWhityFxTwGY3f3Rh05jpI+SowJlOTIheOHqlR
2VFTLTYIvmoZJduFzxlM4t5W3VzGZl/KmC1apNh2N3xPcmimq/YsrDqN5GgkNhuh
/WTTB7pa3qsQlFPKnwylLc2LviQafiR+yunolImCwQKBgQDS9TIth96x+McD2Gu7
1QQlalhDK1+s/O9rjQV4la9FykEFdJB7+Q9xyq9vIqqSVIFj8rI1wqziHp3czUkY
Ijqcgp0DB1Stbwp3DPh3Rq4zVHHnKplzhMwAaDBOVaHmEGaiyB/LwspCcDoON+i+
70Bzdc6EW/KqNpGlP3OPJT2pSwKBgQDRCIlyklOnKQnzbCaMwFkBZBJlHHqgIl1Z
S7jdFaTX7uUkbXF3WVtJlY1+r6h0rK075hX/61VlhfoFjBIR/7ZDaBkrH3Nd6cdU
PJIOgnQEYobRAF4ugWSPTsf0A6bjd7tsVZ7+1ediKwg1QY9Pk2hj/jRb0FD2nKZ+
yWI3RPekWQKBgBM1DfeFSmpr2zrnZo+4imMZtqWO+mwWr3ncYiYjgszY6Gilv036
VESpDqYQwvUFyq4d98nbSsBfx0HGUyRmYW3EmqUe8r/Dv3EtdiXuAohb5O8GOuiA
q85RrixDsbTvw1iI3hRATQgVjcOjpYZU5Epe7ImykXqb81DXYR8kZePXAoGBAJWk
CuFeJ0yPcHQ2hBJW0GDShuijTpW8hB8cuiZrDCsY9ijxwDy0V0mCKlz62xlLVGiA
+lbO3b9j/exirbz81jnDF+FrDme4p92Bzv1cHjnVXrXYEZQxRQ/iUfo5cwt790xC
ryO3dYEtVR7q4/EPkbejj0/6/TrOQdKZ0BnI4Y9hAoGBALlFBlvCRspXYBOXf0XM
5V0Q4t1vAxgcfNaKi4h612UZDF2GluYIwtuF+uJlxYvhRxq1gzmgP5+Z9gblMb6d
8ysWfWPl2RWGYNw0nwOYhWI1/cWRNpfH7W+OY2kHmB3G1bHnf5PxUb+1JL2PvfXS
fZ8JY1/xKqYSoSORJYQh2Z7D
-----END PRIVATE KEY-----
and this is the string I tried to decrypt:
JRhdX3DLGbMVcxN6jV3697yUkfZUBfz/ee6P8pGlgHFnOo5OWgXH0fc10Ps4li3UKkyVqo1+iz10/zzhjVTbSKC5Fai6dLnQgrFVz6lOqOeR83+x4ezyF75kORdgAyEp5MiW0LHsK13ryYEqZ1GHiZdJ6E54nbLZsZGKJJkRZ2OVQW9hovqBQXAP3M8dGk1liruiY+xAHfKkeS73m+IPYPTNGQT+y5IDACoq8dLUvV4nw76p2ZUfyYFgoYOir9KBN2SbfcndR71DZUPWdRnZoDLNFCfvMjC2Ui27j3CxcQLzJSt4K4K+kmU6n5t8Xb6YyGb2j+5pduXcnZMgc5cjsm6NBIXUv+DQzXeRo61vHrXKWeamJ+Whl0RnA9HjIl6medxfE64xHgF+aD6lqbQcwWwHWm/s3f5XkS0xP21bYuOt8mgmHC90qhJNRGKmTGgyxxls/18aV4eZEIRUg82wCIXavvQGLA3hk5UWl4YkrpaGYh+SX1t3yfi+wQ8f30lQBrKl4A0iKk4WHKNCka6nd3sc8bDwD42cvQiFSPCp7m4DRtXy1CRzNmRG7FmSK8SgkQOWSWE+6KRKat88j0Nw+Rg6U1YaMBofJOLKfIswLHgW44Bpf2c0eynJEZdLi94oOh7lkTHcaqwBiO1MWg9eiYT/j7qXCPjoi9q3PzPhxoA=
and the decryption result is like this:
result image

Pkcs7 padding in java

Iam using TripleDes /cbc/pkcs7padding in C#.net to encrypt file.
and i need to decrypt in java.In java am using DESede/CBC/PKcs5padding
But the file is decrypted,but corrupted.
*In java is it possible to use pkcs7padding?
or any other solution to decrypt the file in java with encrypted using pkcs7 padding
C# code
namespace EncryptEpubFiles
{
public class Encryptor
{
public static bool EncryptBook(FileInfo fileToEncrypt,string outPathWithoutExtension,string keyString)
{
try
{
byte[] encryptedFileByteArray;
//Start Encryption service provider
TripleDESCryptoServiceProvider tDES = new TripleDESCryptoServiceProvider();
//Read all bytes from input file
byte[] _fileByteArray = File.ReadAllBytes(fileToEncrypt.FullName);
tDES.Key = GetBytes(keyString);
tDES.Mode = CipherMode.CBC;
//tDES.Padding = PaddingMode.PKCS7;
tDES.Padding = PaddingMode.PKCS7;
ICryptoTransform trans = tDES.CreateEncryptor();
//Create Encrypted file byte array
encryptedFileByteArray = (trans.TransformFinalBlock(_fileByteArray, 0, ((_fileByteArray).Length)));
//Write Encrypted file byte array to a filr with proper extension
System.IO.File.WriteAllBytes((outPathWithoutExtension + ".akr"), encryptedFileByteArray);
return true;
}
catch (Exception ex)
{
return false;
}
}
Java code
public class DecryptFinal {
private static Cipher dcipher;
private static byte[] iv = {
(byte)0xB2, (byte)0x12, (byte)0xD5, (byte)0xB2,
(byte)0x44, (byte)0x21, (byte)0xC3, (byte)0xC3
};
public static void main(String[] args){
try {
String s = "123456789123456789111234";
AlgorithmParameterSpec paramSpec = new IvParameterSpec(iv);
SecretKeyFactory keyfactory=SecretKeyFactory.getInstance("DESede");
byte[] encodedkey=s.getBytes();
System.out.println();
SecretKey key = keyfactory.generateSecret(new DESedeKeySpec(encodedkey));
System.out.println(new DESedeKeySpec(encodedkey));
SecretKeySpec(encodedKey,0,encodedKey.length,"DESede" );
dcipher = Cipher.getInstance("DESede/CBC/PKCS5Padding");
dcipher.init(Cipher.DECRYPT_MODE, key, paramSpec);
FileInputStream fs =new FileInputStream("E:\\Test1\\Test1\\Encrypted Files\\Wedding bells.akr");
FileOutputStream os= new FileOutputStream("E:\\Test1\\Test1\\Encrypted Files\\Encrypted Files\\E-pub Totorials");
byte[] buf = new byte[1024];// bytes read from stream will be decrypted
CipherInputStream cis = new CipherInputStream(fs, dcipher);// read in the decrypted bytes and write the clear text to out
int numRead = 0;
while ((numRead = cis.read(buf)) >= 0) {
os.write(buf, 0, numRead);
}
cis.close();// close all streams
fs.close();
os.close();
}
catch(FileNotFoundException e) {
System.out.println("File Not Found:" + e.getMessage());
return;
} catch (NoSuchAlgorithmException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchPaddingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvalidKeyException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvalidAlgorithmParameterException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (IOException e) {
System.out.println("I/O Error:" + e.getMessage());
}
catch (InvalidKeySpecException e) {
// TODO: handle exception
e.printStackTrace();
}

How older version of android before 4.0 store data like password, accesstoken securly?

I am building an android application that needs to store secure data on android device which also support older version of android before 4.0. I know that android 4.0 and version after that support key chain but my application needs to support older version.
So can any one help and let me know which method used in older os version of Android.
On Android versions previous to ICS you can use KeyStore, here is an example of storing to KeyStore:
public boolean setEntry(String alias, String secretKey) {
boolean keyStoreEntryWritten = false;
if (mKeystore != null && secretKey != null) {
// store something in the key store
SecretKeySpec sks = new SecretKeySpec(secretKey.getBytes(), "MD5");
KeyStore.SecretKeyEntry ske = new KeyStore.SecretKeyEntry(sks);
KeyStore.ProtectionParameter pp = new KeyStore.PasswordProtection(null);
try {
mKeystore.setEntry(alias, ske, pp);
// save key store
boolean success = saveKeyStore();
if (success) {
keyStoreEntryWritten = true;
}
} catch (KeyStoreException ex) {
Log.e(TAG, "Failed to read keystore" + mKeyStoreName);
}
}
return keyStoreEntryWritten;
}
private boolean saveKeyStore() {
FileOutputStream fos = null;
boolean keyStoreSaved = true;
// generate key store path
String keyStoreFilePath = generateKeyStoreFilePath(mKeyStoreName, mKeystoreDirectoryPath);
try {
fos = new FileOutputStream(keyStoreFilePath);
mKeystore.store(fos, mKeyStorePassword.toCharArray());
} catch (Exception ex) {
keyStoreSaved = false;
Log.e(TAG, "Failed to save keystore " + mKeyStoreName);
} finally {
if (fos != null) {
try {
fos.close();
} catch (IOException ex) {
keyStoreSaved = false;
Log.e(TAG, "Failed to close FileOutputStream");
}
}
}
return keyStoreSaved;
}
You can find some more info here: http://developer.android.com/reference/java/security/KeyStore.html
EDIT:
Here is how you retrieve a key:
public String getEntry(String alias) {
String secretStr = null;
byte[] secret = null;
if (mKeystore != null) {
try {
if (!mKeystore.containsAlias(alias)) {
Log.w(TAG, new StringBuilder().append("Keystore ").append(mKeyStoreName)
.append(" does not contain entry ").append(alias).toString());
return null;
}
} catch (KeyStoreException ex) {
Log.e(TAG, "Failed to read keystore entry " + alias);
}
// get my entry from the key store
KeyStore.ProtectionParameter pp = new KeyStore.PasswordProtection(null);
KeyStore.SecretKeyEntry ske = null;
try {
ske = (KeyStore.SecretKeyEntry) mKeystore.getEntry(alias, pp);
} catch (Exception ex) {
Log.e(TAG, "Failed to read keystore entry " + alias);
}
if (ske != null) {
SecretKeySpec sks = (SecretKeySpec) ske.getSecretKey();
secret = sks.getEncoded();
if (secret != null) {
secretStr = new String(secret);
} else {
Log.e(TAG, new StringBuilder().append("Read empty keystore entry ").append(alias).toString());
}
} else {
Log.e(TAG, "Failed to read keystore entry " + alias);
}
}
return secretStr;
}

Java function for Encrypt/Decrypt like Mysql's AES_ENCRYPT and AES_DECRYPT

Is there any way to get the same result as doing in MySQL
SELECT AES_ENCRYPT("text", "key")
using a Java function?
And if possible, what's the other function to simulate the AES_DECRYPT.
If you need the code to decrypt the algorithm is here JAVA
public static String aes_decrypt(String passwordhex, String strKey) throws Exception {
try {
byte[] keyBytes = Arrays.copyOf(strKey.getBytes("ASCII"), 16);
SecretKey key = new SecretKeySpec(keyBytes, "AES");
Cipher decipher = Cipher.getInstance("AES");
decipher.init(Cipher.DECRYPT_MODE, key);
char[] cleartext = passwordhex.toCharArray();
byte[] decodeHex = Hex.decodeHex(cleartext);
byte[] ciphertextBytes = decipher.doFinal(decodeHex);
return new String(ciphertextBytes);
} catch (Exception e) {
e.getMessage();
}
return null;
}
It received a standard hex format string but variable and returns the password. Test with those in main method
System.out.println(aes_encrypt("your_string_password", "your_string_key"));
System.out.println(aes_decrypt("standard_hex_format_string ", "your_string_key"));
firstable test only with encrypt, then just with decrypt.
By the way you must install 'commons-codec-1.6.jar' so you can use the Hex class
http://commons.apache.org/proper/commons-codec/download_codec.cgi
Greetings from Ecuador, Ibarra
Ok, I've managed to get it working like this.
MySQL Query:
SELECT HEX(aes_encrypt("password", "0123456789012345"));
Java function:
public static String aes_encrypt(String password, String strKey) {
try {
byte[] keyBytes = Arrays.copyOf(strKey.getBytes("ASCII"), 16);
SecretKey key = new SecretKeySpec(keyBytes, "AES");
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.ENCRYPT_MODE, key);
byte[] cleartext = password.getBytes("UTF-8");
byte[] ciphertextBytes = cipher.doFinal(cleartext);
return new String(Hex.encodeHex(ciphertextBytes));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (NoSuchPaddingException e) {
e.printStackTrace();
} catch (InvalidKeyException e) {
e.printStackTrace();
} catch (IllegalBlockSizeException e) {
e.printStackTrace();
} catch (BadPaddingException e) {
e.printStackTrace();
} return null;
}
in my case i just code like this
private static final char[] HEX_ARRAY = "0123456789ABCDEF".toCharArray();
public static String bytesToHex(byte[] bytes) {
char[] hexChars = new char[bytes.length * 2];
for (int j = 0; j < bytes.length; j++) {
int v = bytes[j] & 0xFF;
hexChars[j * 2] = HEX_ARRAY[v >>> 4];
hexChars[j * 2 + 1] = HEX_ARRAY[v & 0x0F];
}
return new String(hexChars);
}
and than create method aes 128
public static String aes_encrypt(String password, String strKey) {
try {
byte[] keyBytes = Arrays.copyOf(strKey.getBytes("ASCII"), 16);
SecretKey key = new SecretKeySpec(keyBytes, "AES");
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.ENCRYPT_MODE, key);
byte[] cleartext = password.getBytes("UTF-8");
byte[] ciphertextBytes = cipher.doFinal(cleartext);
return new String(bytesToHex(ciphertextBytes));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (NoSuchPaddingException e) {
e.printStackTrace();
} catch (InvalidKeyException e) {
e.printStackTrace();
} catch (IllegalBlockSizeException e) {
e.printStackTrace();
} catch (BadPaddingException e) {
e.printStackTrace();
}
return null;
}
example :
mysql code
SELECT HEX(aes_encrypt("text", "0123456889812345"))
java code
System.out.println(aes_encrypt("text", "0123456889812345"));

Categories