I am trying to convert a user fed password into a md5 hash. The following code smippet was taken from a weblog. But it is showing error in eclipse (android development):
MessageDigest cannot be resolved.
public class MainActivity extends Activity {
private String md5(String in) {
MessageDigest digest;
try {
digest = MessageDisgest.getInstance("MD5");
digest.reset();
digest.update(in.getBytes());
byte[] a = digest.digest();
int len = a.length;
StringBuilder sb = new StringBuilder(len << 1);
for(int i=0;i<len;i++) {
sb.append(Character.forDigit((a[i] & 0xf0) >> 4, 16));
sb.append(Character.forDigit(a[i] & 0x0f, 16));
}
return sb.toString();
} catch (NoSuchAlgorithmException e) { e.printStackTrace();}
return null;
}
I am not able to find any error. What could be wrong?
Try to change MessageDisgest to MessageDigest
Related
Im trying to implement AES in an Android application. The server is a PHP server.
This is the AES code :
public class AES{
private String SecretKey = "89432hjfsd891787";
private String iv = "fedcba9876543210";
private IvParameterSpec ivspec;
private SecretKeySpec keyspec;
private Cipher cipher;
public AES()
{
ivspec = new IvParameterSpec(iv.getBytes());
keyspec = new SecretKeySpec(SecretKey.getBytes(), "AES");
try {
cipher = Cipher.getInstance("AES/CBC/NoPadding");
} catch (NoSuchAlgorithmException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchPaddingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public byte[] encrypt(String text) throws Exception
{
if(text == null || text.length() == 0)
throw new Exception("Empty string");
byte[] encrypted = null;
try {
cipher.init(Cipher.ENCRYPT_MODE, keyspec, ivspec);
encrypted = cipher.doFinal(padString(text).getBytes());
} catch (Exception e)
{
throw new Exception("[encrypt] " + e.getMessage());
}
return encrypted;
}
public byte[] decrypt(String code) throws Exception
{
if(code == null || code.length() == 0)
throw new Exception("Empty string");
byte[] decrypted = null;
try {
cipher.init(Cipher.DECRYPT_MODE, keyspec, ivspec);
decrypted = cipher.doFinal(hexToBytes(code));
} catch (Exception e)
{
throw new Exception("[decrypt] " + e.getMessage());
}
return decrypted;
}
public static String bytesToHex(byte[] data)
{
if (data==null)
{
return null;
}
int len = data.length;
String str = "";
for (int i=0; i<len; i++) {
if ((data[i]&0xFF)<16)
str = str + "0" + java.lang.Integer.toHexString(data[i]&0xFF);
else
str = str + java.lang.Integer.toHexString(data[i]&0xFF);
}
return str;
}
public static byte[] hexToBytes(String str) {
if (str==null) {
return null;
} else if (str.length() < 2) {
return null;
} else {
int len = str.length() / 2;
byte[] buffer = new byte[len];
for (int i=0; i<len; i++) {
buffer[i] = (byte) Integer.parseInt(str.substring(i*2,i*2+2),16);
}
return buffer;
}
}
private static String padString(String source)
{
char paddingChar = ' ';
int size = 16;
int x = source.length() % size;
int padLength = size - x;
for (int i = 0; i < padLength; i++) {
source += paddingChar;
}
return source;
}
}
I get an error while decrypting the incoming string : Cipher functions:EVP_DecryptFinal_ex:DATA_NOT_MULTIPLE_OF_BLOCK_LENGTH
How do i go about this?
Manually padding the String representation of the plaintext with spaces is not a good padding mechanism. Instead, you should use AES/CBC/PKCS5Padding which will handle the padding as prescribed in PKCS #5/#7.
You should also:
generate a unique IV per encryption operation rather than re-using the same value for all messages
Use an authenticated mode of operation (GCM, HMAC/SHA-256 MAC over cipher text, etc.)
Store the key in hexadecimal representation of the raw bytes rather than an ASCII/UTF-8 String encoding (not specified in your code)
Encode the cipher text in Base64 or Hex before serializing/transmitting. Encoding errors can contribute to padding exceptions during decryption.
I need provide hashing password with sha1 and Base64 like next:
base64(sha1(password))
here is what i tried for:
private static String convertToHex(byte[] data) {
StringBuffer buf = new StringBuffer();
for (int i = 0; i < data.length; i++) {
int halfbyte = (data[i] >>> 4) & 0x0F;
int two_halfs = 0;
do {
if ((0 <= halfbyte) && (halfbyte <= 9)) {
buf.append((char) ('0' + halfbyte));
}
else {
buf.append((char) ('a' + (halfbyte - 10)));
}
halfbyte = data[i] & 0x0F;
} while(two_halfs++ < 1);
}
return buf.toString();
}
public static String SHA1(String password) throws NoSuchAlgorithmException, UnsupportedEncodingException {
MessageDigest md = MessageDigest.getInstance("SHA-1");
md.update(password.getBytes("iso-8859-1"), 0, password.length());
byte[] sha1hash = md.digest();
return convertToHex(sha1hash);
}
and than :
String encodedPass = Base64.encodeToString(password.getBytes(), Base64.DEFAULT);
but this doesn't work correctly...
Maybe there some mistake or some much easier way to do it?
the problem was next:
convertToHex(sha1hash) - return string, but for correct work of Base64 I was needed to put byte [] here:
Base64.encodeToString(byte[], Base64.DEFAULT);
so solution is pretty simple:
public static String encodePassword(String password) throws NoSuchAlgorithmException, UnsupportedEncodingException {
String result;
MessageDigest md = MessageDigest.getInstance("SHA-1");
md.update(password.getBytes("iso-8859-1"), 0, password.length());
byte[] sha1hash = md.digest();
result = Base64.encodeToString(sha1hash, Base64.DEFAULT);
result = result.substring(0, result.length()-1);
return result;
}
On Android, I get the following error when I try to md5 a string:
"Performing stop of activity that is not resumed"
I need to attach the md5 to a URL.
Please help
//md5 code
MessageDigest digest;
try {
digest = MessageDigest.getInstance("MD5");
digest.reset();
digest.update(text.getBytes());
byte[] a = digest.digest();
int len = a.length;
StringBuilder sb = new StringBuilder(len << 1);
for (int i = 0; i < len; i++) {
sb.append(Character.forDigit((a[i] & 0xf0) >> 4, 16));
sb.append(Character.forDigit(a[i] & 0x0f, 16));
}
return sb.toString();
} catch (NoSuchAlgorithmException e) {
// e.printStackTrace();
}
//request code
encryptedTaskId = MDConversion.MD5(taskId);
Log.v("inside doInBackground :: ", "inside doInBackground :: ");
totalUrl = baseUrl + "&access_token=" + accessToken + "&id=" + encryptedTaskId;
Log.v("fetch users to forward task url :: ", "url :: "+totalUrl);
HttpGet get = new HttpGet(totalUrl);
HttpClient client = new DefaultHttpClient();
HttpResponse response;
response = client.execute(get);
Try to use this static function:
public static final String md5(final String toEncrypt) {
try {
final MessageDigest digest = MessageDigest.getInstance("md5");
digest.update(toEncrypt.getBytes());
final byte[] bytes = digest.digest();
final StringBuilder sb = new StringBuilder();
for (int i = 0; i < bytes.length; i++) {
sb.append(String.format("%02X", bytes[i]));
}
return sb.toString().toLowerCase();
} catch (Exception exc) {
return ""; // Impossibru!
}
}
I'm sorry but I need help for building an Android app that will have a function to generate MD5 hash from a file and a textfile. Can you help me, I don't very understand on Android development, but my teacher keep pushing me (sorry about that).
Thank you so much for your help.
Hari (Indonesia)
MD5 Hash function:
public static final String md5(final String s)
{
try
{
MessageDigest digest = java.security.MessageDigest.getInstance("MD5");
digest.update(s.getBytes());
byte messageDigest[] = digest.digest();
StringBuffer hexString = new StringBuffer();
for (int i = 0; i < messageDigest.length; i++)
{
String h = Integer.toHexString(0xFF & messageDigest[i]);
while (h.length() < 2)
h = "0" + h;
hexString.append(h);
}
return hexString.toString();
}
catch (NoSuchAlgorithmException e)
{
e.printStackTrace();
}
return "";
}
im using this code to encrypt my password......
private static final String md5(final String password) {
try {
MessageDigest digest = java.security.MessageDigest
.getInstance("MD5");
digest.update(password.getBytes());
byte messageDigest[] = digest.digest();
StringBuffer hexString = new StringBuffer();
for (int i = 0; i < messageDigest.length; i++) {
String h = Integer.toHexString(0xFF & messageDigest[i]);
while (h.length() < 2)
h = "0" + h;
hexString.append(h);
}
return hexString.toString();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
return "";
}
how can i add a (Secretkey) so i can send the value to a .net
What about using AES encryption?
You can find examples yow to use it at What are best practices for using AES encryption in Android?