Encryption & Decryption algorithm - android

I am working on mobile product. We are using the data in xml document. In order to keep our data secure we need an encryption algorithm(but we don't want the existing algorithm to import)
Can u give me some steps to encrypt the data.(if code example is most welcome).

To be more secure, you have to do with your own secret key. Try to use this code
KeyStore ks = KeyStore.getInstance();
// get the names of all keys created by our app
String[] keyNames = ks.saw("");
// store a symmetric key in the keystore
SecretKey key = Crypto.generateKey();
boolean success = ks.put("secretKey1", key.getEncoded());
// check if operation succeeded and get error code if not
if (!success) {
int errorCode = ks.getLastError();
throw new RuntimeException("Keystore error: " + errorCode);
}
// get a key from the keystore
byte[] keyBytes = ks.get("secretKey1");
SecretKey key = new SecretKeySpec(keyBytes, "AES");
// delete a key
boolean success = ks.delete("secretKey1");

If you want to develop your own encryption scheme, be prepared to embark on a research project. You can use any of standard encryption algorithms like AES/DES etc, with your private keys that are sufficiently long and difficult to crack.

public string PassEncrypt(string Password)
{
// Encrypting the password entered by User
// ======================================================
MD5 md5 = new MD5CryptoServiceProvider();
md5.ComputeHash(ASCIIEncoding.ASCII.GetBytes(Password));
byte[] result = md5.Hash;
StringBuilder strBuilder = new StringBuilder();
for (int i = 0; i < result.Length; i++)
{
strBuilder.Append(result[i].ToString("x2"));
}
return strBuilder.ToString();
// ======================================================
}
OR
You may refer on this links :
developer.motorala.com
codereview.stackexchange.com
android snippets
java-tips.org

Related

How to generate Live hash key for PayUMoney android

I am trying integrate PayUmoney android SDK in my application,i integrate successfully But i face one problem.
in test mode they provide url to generate hask key but live they wont provide
Test mode: https://test.payumoney.com/payment/op/calculateHashForTest
For Live Mode:???
i am trying below Code to generate Live Hash key
String salt="saltkey";
String hashSequence=key+"|"+txnid+"|"+amount+"|"+productinfo+"|"
+firstname+"|"+email+"|"+""+"|"+"|"+""+"|"+""+"|"+""+"|"+salt;
String serverCalculatedHash= hashCal("SHA-512", hashSequence);
paymentParam.setMerchantHash(serverCalculatedHash);
PayUmoneySdkInitilizer.startPaymentActivityForResult((Activity)
context, paymentParam);
BUt i got below response from sdk
{"status":-1,"message":"key is not valid","result":null,"errorCode":null,"responseCode":null}
{"status":-1,"message":"payment status for :1111322345","result":"PP1 not updated till now from P2","errorCode":null,"responseCode":null}
please give solution to:
1. generate live hash key using url,
2.why above mention response return from PayUMoney SDk
Expecting your valuble answer.
You can use this function for generate Live hash key for PayUMoney android
public static String hashCal(String type, String str) {
byte[] hashseq = str.getBytes();
StringBuffer hexString = new StringBuffer();
try {
MessageDigest algorithm = MessageDigest.getInstance(type);
algorithm.reset();
algorithm.update(hashseq);
byte messageDigest[] = algorithm.digest();
for (int i = 0; i<messageDigest.length; i++) {
String hex = Integer.toHexString(0xFF &messageDigest[i]);
if (hex.length() == 1) {
hexString.append("0");
}
hexString.append(hex);
}
} catch (NoSuchAlgorithmException nsae) {
}
return hexString.toString();
}
And call like
String serverCalculatedHash = hashCal("SHA-512",MERCHANT_KEY+"|"+txnId+"|"+Double.parseDouble(totalPrices)+"|"+productName+"|"
+userName+"|"+userEmail+"|"+udf1+"|"+udf2+"|"+udf3+"|"+udf4+"|"+udf5+"|"+MERCHANT_SALT);
serverCalculatedHash contain hash key for PayUMoney
Check your payu dashboard at Integration Credentials: Merchant Key and Merchant Salt will be available.
Also check the .setIsDebug(true) // For Integration environment - true, For Production - false.
You specified that Hash
String hashSequence=key+"|"+txnid+"|"+amount+"|"+productinfo+"|"+firstname+"|"+email+"|"+""+"|"+"|"+""+"|"+""+"|"+""+"|"+salt;
It should be :
hashSequence=key+"|"+txnid+"|"+amount+"|"+productinfo+"|"+firstname+"|"+email+"|"+udf1+"|"+udf2+"|"+udf3+"|"+udf4+"|"+udf5+"|"+udf6+"|"+udf7+"|"+udf8+"|"+udf9+"|"+udf10+"|"+salt;
user define string can be empty, but it has to passed in hash sequence.

Save data on KeyStore and retrieve it using keychain

I want to save some of my sensitive data (string) in keyStore. I found that keyStore only accepts secretKey objects. But, I'm not able to store it and and retreive it later using keyChain callback by using the alias name of the secretKey
Any help will be appreciated..!
I think you are looking something like MD5. An MD5 hash is created by taking a string of an any length and encoding it into a 128-bit fingerprint. Encoding the same string using the MD5 algorithm will always result in the same 128-bit hash output. MD5 hashes are commonly used with smaller strings when storing passwords, credit card numbers or other sensitive data in databases such as the popular MySQL. This tool provides a quick and easy way to encode an MD5 hash from a simple string of up to 256 characters in length.
MD5 hashes are also used to ensure the data integrity of files. Because the MD5 hash algorithm always produces the same output for the same given input, users can compare a hash of the source file with a newly created hash of the destination file to check that it is intact and unmodified.
Hashing String with MD5:
public class JavaMD5Hash {
public static void main(String[] args) {
String password = "MyPassword123";
System.out.println("MD5 in hex: " + md5(password));
System.out.println("MD5 in hex: " + md5(null));
//= d41d8cd98f00b204e9800998ecf8427e
System.out.println("MD5 in hex: "
+ md5("The quick brown fox jumps over the lazy dog"));
//= 9e107d9d372bb6826bd81d3542a419d6
}
public static String md5(String input) {
String md5 = null;
if(null == input) return null;
try {
//Create MessageDigest object for MD5
MessageDigest digest = MessageDigest.getInstance("MD5");
//Update input string in message digest
digest.update(input.getBytes(), 0, input.length());
//Converts message digest value in base 16 (hex)
md5 = new BigInteger(1, digest.digest()).toString(16);
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
return md5;
}
}
referance :
http://viralpatel.net/blogs/java-md5-hashing-salting-password/
https://www.mkyong.com/java/java-md5-hashing-example/
http://www.asjava.com/core-java/java-md5-example/
you can use shared preferance which is very easy to handle also.
https://developer.android.com/training/basics/data-storage/shared-preferences.html
Android Shared preferences example

How to verify a public key in string/byte[] format against certificates in bks store

I want to verify if a certificate with a certain public key exits in android keystore or not.I have key which is holded in a string.How do I verify if the corresponding certificate is present in keystore.
When checked the apis i found certificate.verify(mykey); is the only option.but mykey sholud be of type PublicKey and I have it in string.
String is 0r1wxn7wIXJuS/hDnDvectD2VTmel9akk8awIWAXIRo= .....this is a hash of public key..i have to return back the certficate corresponding to this key.
Can anyone help me ?
Can anyone help me ?
Regards
kozlov
KeyStore store = ... ;
byte[] target = ... ; // Base-64 decode your string.
MessageDigest digest = MessageDigest.getInstance(algorithm);
Enumeration<String> aliases = store.aliases();
while(aliases.hasMoreElements()) {
String alias = aliases.nextElement();
Certificate c = store.getCertificate(alias);
if (c == null)
continue;
PublicKey pub = c.getPublicKey();
byte[] hash = digest.digest(pub.getEncoded());
if (MessageDigest.isEqual(hash, target)) {
// Certificate "c" is a match.
}
}

How to Generate HMAC MD5 In Android?

I am new in this Field!I have this Message and Key also i want HMAC MD5 using this two so how it is possible if possible then give some example or sample code of this.The Given link display the overall functionality i want such kind of code.Please help me.
Messgae = POSTuserMon,28Jun201010:18:33GMT7FF4471B-13C0-5A9F-BB7B-7309F1AB7F08
key = d6fc3a4a06ed55d24fecde188aaa9161
Link = http://hash.online-convert.com/md5-generator
Here are working codes.
Generated result is same as Link = http://hash.online-convert.com/md5-generator
public String calcHmac(String src) throws Exception {
String key = "d6fc3a4a06ed55d24fecde188aaa9161";
Mac mac = Mac.getInstance("HmacSHA1");
SecretKeySpec sk = new SecretKeySpec(key.getBytes(),mac.getAlgorithm());
mac.init(sk);
byte[] result = mac.doFinal(src.getBytes());
return Base64.encodeToString(result ,Base64.URL_SAFE);
}
Look at the javax.crypto.Mac class. Try Mac.getInstance("HmacMD5"); and then use the init method with your key and then use the update and doFinal methods just as you would with a MessageDigest object.

how to encrypt data in android?

I am new to android. I am trying to learn and work on it. Can some one help me with the following issue.
I have some fields to be encrypted and uploaded to a DB using android.
The fields which should be encrypted are DOB, Email id, Phone number and some other numeric values.
Now I am doing some formal encryption by substitution.
Can some one help me with an example to do some standard form of encryption.
There are a lot of encryption libraries out there, but it depends on which language you are using. For Java, take a look here: http://www.androidsnippets.com/encryptdecrypt-strings.
Or use Google and search for
android +encryption +library +<your programming language>
The biggest challenge I believe is what encryption to use and how to keep the secret key safe. It doesn't matter what data you want to encrypt or where you want to store it. The key has to remain a secret. And you need to be able to use the exact same key to get the data decrypted.
You can 't store the key together with the data itself. Even not within the protected app resources. Some alternatives:
Getting the key from a service
Get the key (in a secure way) from a remote service. This adds the challenge to protect that communication channel but if possible it might be a valid approach.
The below code example can be used with a key retrieved elsewhere. Just check the encrypt and decrypt parts of the code.
Using a Password derived Key
Another option is using secret input from the user (aka password) to generate a key. The method that generates the key will always return the same key for each unique password. Hence you can recover the key if the user enters the password.
Ideally this password is never stored and always prompted for on each encryption/decryption need. This also relies on a proper password choice from the user.
A code example that shows key generation, encryption and decryption of some sample data. Note how we don't use the default settings for the key generation.
package com.example.android.secure;
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.SecretKeySpec;
public class EncryptionManager {
// we should get a password from the user
String password = "...";
String PBE_ALGORITHM = "PBEWithSHA256And256BitAES-CBC-BC";
// Important not to rely on default here !!!! use CBC instead of ECB
String CIPHER_ALGORITHM = "AES/CBC/PKCS5Padding";
int NUM_OF_ITERATIONS = 1000;
int KEY_SIZE = 256;
// generated on first run
byte[] salt = "abababababababababa bab".getBytes();
byte[] iv = "1234567890abcdef".getBytes();
// This is the value to be encrypted.
String clearText = "...";
byte[] encryptedText;
byte[] decryptedText;
public void exampleCodeNoRealMethod() {
try {
PBEKeySpec pbeKeySpec = new PBEKeySpec(password.toCharArray(), salt, NUM_OF_ITERATIONS, KEY_SIZE);
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(PBE_ALGORITHM);
SecretKey tempKey = keyFactory.generateSecret(pbeKeySpec);
SecretKey secretKey = new SecretKeySpec(tempKey.getEncoded(), "AES");
IvParameterSpec ivSpec = new IvParameterSpec(iv);
Cipher encCipher = Cipher.getInstance(CIPHER_ALGORITHM);
encCipher.init(Cipher.ENCRYPT_MODE, secretKey, ivSpec);
Cipher decCipher = Cipher.getInstance(CIPHER_ALGORITHM);
decCipher.init(Cipher.DECRYPT_MODE, secretKey, ivSpec);
encryptedText = encCipher.doFinal(clearText.getBytes());
decryptedText = decCipher.doFinal(encryptedText);
String sameAsClearText = new String(decryptedText);
} catch (Exception e) {
// TODO handle this exception
}
}
}
Using the Android KeyStore
This is a new feature only available on the latest Android devices. More information can be found on this blog post. I added a snippet from there:
public static SecretKey generateKey(char[] passphraseOrPin, byte[] salt) throws NoSuchAlgorithmException, InvalidKeySpecException {
// Number of PBKDF2 hardening rounds to use. Larger values increase
// computation time. You should select a value that causes computation
// to take >100ms.
final int iterations = 1000;
// Generate a 256-bit key
final int outputKeyLength = 256;
SecretKeyFactory secretKeyFactory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
KeySpec keySpec = new PBEKeySpec(passphraseOrPin, salt, iterations, outputKeyLength);
SecretKey secretKey = secretKeyFactory.generateSecret(keySpec);
return secretKey;
}

Categories

Resources