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.
Related
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.
I need an end to encrypt different strings and related decryptions after user authenticate using fingerprint scanner.
Following this project (https://github.com/StylingAndroid/UserIdentity/tree/Part1) and changed "tryEncrypt" method like below:
private boolean tryEncrypt(Cipher cipher) {
try {
cipher.doFinal(SECRET_BYTES);
String one = "augusto";
String two = "test#gmail.com";
String three = "3333333331";
byte[] oneEnc = cipher.doFinal(one.getBytes());
byte[] twoEnc = cipher.doFinal(one.getBytes());
byte[] threeEnc = cipher.doFinal(one.getBytes());
Log.d("test", "oneEnc: " + Base64.encodeToString(oneEnc,0));
Log.d("test", "twoEnc: " + Base64.encodeToString(twoEnc,0));
Log.d("test", "threeEnc: " + Base64.encodeToString(threeEnc,0));
} catch (Exception e) {
e.printStackTrace();
return false;
}
return true;
}
I'm getting this error:
java.lang.IllegalStateException: IV has already been used. Reusing IV in encryption mode violates security best practices.
What is the correct way on how to do it?
Thanks
*******************UPDATE:*****************************
To help others to get solve this problem I used this library and worked like charm:
https://github.com/Mauin/RxFingerprint
You have a problem because your are using a single instance of the Cipher for multiple encryptions (dofinal). You are using a single vector initialization (IV).
Take a look on an option of how to initialize a cipher.
SecureRandom r = new SecureRandom();
byte[] ivBytes = new byte[16];
r.nextBytes(ivBytes);
cipher.init(Cipher.ENCRYPT_MODE, secretKey, new IvParameterSpec(ivBytes));
As you can see, you need to specify the initialization vector. The initialization vector can not be repeated to guarantee that the encryption works.
In your scenario, you probably gonna need to perform a new initialization.
*Ps: It's also possible to use the Cipher initialization without the IvParameterSpec. In this scenario, the class will generate one for you. However, I believe that you need to perform a initialization per DoFinal to guarantee some randomness.
To help others to get solve this problem I used this library that worked like charm:
https://github.com/Mauin/RxFingerprint
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
I'm currently trying to develop an encryption app for Android using ECDH and BouncyCastle. So far what I've implemented is Public and Private Key generation on the application as per the code below.
My next task is to send the public keys over SMS. I would like to find out what methods can be used to get the job done. Currently I'm trying it out by assigning the generated keys to a string then I'm sending the string out but I'm still unable to get it to work properly.
Any assistance would be greatly appreciated
Thanks and Happy Holidays!
try
{
KeyPairGenerator g = KeyPairGenerator.getInstance("ECDH", "SC");
//Define the Elliptic Curve Field, Points A and B
EllipticCurve curve = new EllipticCurve(new ECFieldFp(Presets.CurveQ),Presets.PointA,Presets.PointB);
//Define the points on the Elliptic Curve
ECParameterSpec ecSpec = new ECParameterSpec(
curve,
ECPointUtil.decodePoint(curve, Hex.decode("020ffa963cdca8816ccc33b8642bedf905c3d358573d3f27fbbd3b3cb9aaaf")), // G
new BigInteger("883423532389192164791648750360308884807550341691627752275345424702807307"), // n
1); // h
//Generate the random point on the Elliptic Curve
g.initialize(ecSpec, new SecureRandom());
//Generate Private Key for User A
KeyPair aKeyPair = g.generateKeyPair();
aKeyAgree = KeyAgreement.getInstance("ECDH", "SC");
aKeyAgree.init(aKeyPair.getPrivate());
//Save Personal Keys
Presets.myPrivateKey = aKeyPair.getPrivate().getEncoded().toString();
Presets.myPublicKey = aKeyPair.getPublic().getEncoded().toString();
I managed to find out what I was doing wrongly.
The output I was getting from
Presets.myPublicKey = aKeyPair.getPublic().getEncoded().toString();
was something along the lines of [#B1ef9157 which could not be sent over SMS like I hoped for.
Java: Syntax and meaning behind "[B#1ef9157"? Binary/Address?
Instead I did this
byte[] pubEnc = aKeyPair.getPublic().getEncoded();
String s = Base64.encodeBytes(pubEnc);
making use of the Base64 encoder from http://iharder.sourceforge.net/current/java/base64/
and now I am able to successfully send the string over sms.
Thanks Craigy!
i'm looking very hard for a possibility to encrypt my sqlite database on Android devices, but I was't able to find a satisfying solution.
I need something like a libary to reference, in order to have a "on the fly" encryption/decryption of my database, while using the normal sqlite functions.
I don't want to encrypt data before storing.
I don't want to encrypt the whole databasefile, in order to decrypt it before using.
I know about the following projects:
SEE
wxSQLite
SQLCipher
SQLiteCrypt
Botan
But I can't find any working example for this stuff.
Btw, I'm absolutly willing to purchase a commercial build, but I have to test ist before spending a few hundred dollars.
Did anyone solve this issue for his own?
Try the SQLCipher port to Android instead of the regular SQLCipher.
litereplica supports encryption using the ChaCha cipher, faster than AES on portable devices.
There are bindings for Android.
To create and open an encrypted database we use an URI like this:
"file:/path/to/file.db?cipher=...&key=..."
If anyone is still looking:
Override SQLiteOpenHelper function as below:
void onConfigure(SQLiteDatabase db){
db.execSQL("PRAGMA key = 'secretkey'");
}
private String encrypt(String password) {
try {
SecretKeySpec keySpec = generateKey(password);
Cipher c = Cipher.getInstance("AES");
c.init(Cipher.ENCRYPT_MODE,keySpec);
byte[] encVal = c.doFinal(password.getBytes());
String encryptedValue = Base64.encodeToString(encVal,Base64.DEFAULT);
return encryptedValue;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
private SecretKeySpec generateKey(String password) throws Exception {
final MessageDigest digest = MessageDigest.getInstance("SHA-256");
byte[] bytes = password.getBytes(StandardCharsets.UTF_8);
digest.update(bytes,0,bytes.length);
byte[] key = digest.digest();
SecretKeySpec secretKeySpec = new SecretKeySpec(key,"AES");
return secretKeySpec;
}
I just used the encrypt function to encrypt the password. Here I used the user's password as a key. Therefore I don't need to keep the key inside the application. When the user wants to log in, simply encrypt the password and try to match with the encrypted password in the database and allow them to log in.