MessageDigest md = null;
try {
md = MessageDigest.getInstance("MD5");
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
String resultPassword = dc.profile.sipUsername + ":" + dc.profile.stunServer + ":" + passwd;
md.update(resultPassword.getBytes());
byte byteData[] = md.digest();
StringBuffer sb = new StringBuffer();
for (int j = 0; j < byteData.length; j++) {
sb.append(Integer.toString((byteData[j] & 0xff) + 0x100, 16).substring(1));
}
I have reached to that point
NSData *data = [resultPassword dataUsingEncoding:NSUTF16LittleEndianStringEncoding allowLossyConversion:NO];
unsigned char digest[CC_MD5_DIGEST_LENGTH];
CC_MD5(data.bytes, data.length, digest);
NSData *hashData = [[NSData alloc] initWithBytes:digest length: sizeof digest];
But don't know am i going on right way.
I need to convert password to md5
Try the following:
#import <CommonCrypto/CommonHMAC.h>
NSString *calcMD5(NSString *aString, NSString *key)
{
const char *cKey = [key cStringUsingEncoding: NSUTF8StringEncoding];
const char *cData = [aString cStringUsingEncoding: NSUTF8StringEncoding];
// Berechnung der MD5-Signatur
unsigned char cHMAC[CC_MD5_DIGEST_LENGTH];
CCHmac(kCCHmacAlgMD5, cKey, strlen(cKey), cData, strlen(cData), cHMAC);
NSData *HMAC = [[NSData alloc] initWithBytes:cHMAC
length:sizeof(cHMAC)];
// Base64 encoded zurückliefern
return [HMAC base64EncodedStringWithOptions:0];
}
Or use the following if there is no key:
How do I create an MD5 Hash of a string in Cocoa?
Sha256 hash function gives a longer hashed string in objective c than Java. Extra Zeros being added in objective C, how can I rationalise the hashing?
Objective C:
-(NSString*) sha256:(NSString *)clear{
const char *s=[clear cStringUsingEncoding:NSASCIIStringEncoding];
NSData *keyData=[NSData dataWithBytes:s length:strlen(s)];
uint8_t digest[CC_SHA256_DIGEST_LENGTH]={0};
CC_SHA256(keyData.bytes, keyData.length, digest);
NSData *out=[NSData dataWithBytes:digest
length:CC_SHA256_DIGEST_LENGTH];
NSString *hash=[out description];
hash = [hash stringByReplacingOccurrencesOfString:#" " withString:#""];
hash = [hash stringByReplacingOccurrencesOfString:#"<" withString:#""];
hash = [hash stringByReplacingOccurrencesOfString:#">" withString:#""];
return hash;
}
Java
public static String generateHashString(String data)
{
try {
MessageDigest md = MessageDigest.getInstance("SHA-256");
byte[] dataInBytes = data.getBytes(StandardCharsets.UTF_8);
md.update(dataInBytes);
byte[] mdbytes = md.digest();
StringBuffer hexString = new StringBuffer();
for (int i=0;i<mdbytes.length;i++) {
hexString.append(Integer.toHexString(0xFF & mdbytes[i]));
}
return hexString.toString();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
return null;
}
Integer.toHexString() on an integer less than 16 will only be one character long, whereas you want the extra '0' character.
You could use String.format():
for (int i = 0; i < mdbytes.length; i++) {
hexString.append(String.format("%02x", 0xFF & mdbytes[i]));
}
Also, you really should be using StringBuilder rather than StringBuffer in this case because only a single thread is involved.
See Java code To convert byte to Hexadecimal for some alternative solutions to hex-encoding a byte array in Java.
I am calculating the MD5 in PHP with following line (see documentation for more info):
md5($password, true); // returns raw output
I am using the following Java code:
byte[] bytesOfMessage = password.getBytes("UTF-8");
MessageDigest md = MessageDigest.getInstance("MD5");
byte[] thedigest = md.digest(bytesOfMessage);
Above code doesn't return the same output as the one returned by the PHP code.
How can I solve it for Android/Java generate exactly the same MD5 with raw output not hash string?
Yes. I had the same problem. I find the right way:
That is my equivalent of PHP's md5(password, true):
final protected static char[] hexArray = "0123456789ABCDEF".toCharArray();
public byte[] md5x16(String text) {
try {
MessageDigest digester = MessageDigest.getInstance("MD5");
digester.update(text.getBytes());
byte[] md5Bytes = digester.digest();
String md5Text = new String(md5Bytes); // if you need in String format
// better use md5Bytes if applying further processing to the generated md5.
// Otherwise it may give undesired results.
return md5Bytes;
}
catch (Exception e) {
e.printStackTrace();
}
return null;
}
and equivalent of PHP's md5(password, false):
public static String md5(String text) {
try {
MessageDigest digester = MessageDigest.getInstance("MD5");
digester.update(text.getBytes());
byte[] md5Bytes = digester.digest();
String md5Text = null;
md5Text = bytesToHex(md5Bytes);
return md5Text;
}
catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
return "";
}
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] = hexArray[v >>> 4];
hexChars[j * 2 + 1] = hexArray[v & 0x0F];
}
return new String(hexChars);
}
And if you need to convert an equivalent of PHP's base64_encode(text), use this one:
public String convertToBase64(byte[] bytes) {
try {
String base64 = Base64.encodeToString(bytes, Base64.DEFAULT);
return base64;
}
catch (Exception e) {
}
return "";
}
I had the same issue, this is my Java program code:
public static String encryptPassword(String password) {
String hash = null;
try {
MessageDigest md = MessageDigest.getInstance("MD5");
md.update(password.getBytes("UTF-8"));
byte[] raw = md.digest();
hash = (new BASE64Encoder()).encode(raw);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return hash;
}
And this is my php code:
<?php
$str = 'encodeIt';
$toutf8 = utf8_encode($str);
$var = md5($str,true);
echo base64_encode($var);
?>
They return always the same hash.
I have to decrypt a string in Objective C. The encryption scheme is DES/ECB/NoPadding and I am providing this Java code with correct output with following input
data = 741DCDDF1C216EEF and key = D9C44F6D2589255E and output should be 34160D6EADAD6D86
public static String decrypt3DES(String Key, String data) throws Exception
{
Cipher cipher = null;
byte[] text = null;
byte[] desKey = null;
Key keySpec = null;
try {
if (Key.length() <= 16) {
cipher = Cipher.getInstance("DES/ECB/NoPadding");
desKey = byteConvertor(Key);
keySpec = new SecretKeySpec(desKey, "DES");
} else if (Key.length() >= 32) {
cipher = Cipher.getInstance("DESede/ECB/NoPadding");
desKey = byteConvertor(Key);
keySpec = new SecretKeySpec(desKey, "DESede");
}
cipher.init(Cipher.DECRYPT_MODE, keySpec);
text = cipher.doFinal(byteConvertor(data));
} 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 alpha2Hex(byteArr2String(text));
}
Objective C code :
NSString *token = #"741DCDDF1C216EEF";
NSString *key = #"D9C44F6D2589255E";
const void *vplainText;
size_t plainTextBufferSize;
NSData *EncryptData = [[NSData alloc] initWithBase64EncodedString:token options:0];
plainTextBufferSize = [EncryptData length]+1;
vplainText = [EncryptData bytes];
//plainTextBufferSize = [token length];
//vplainText = (const void *)[token UTF8String];
CCCryptorStatus ccStatus;
uint8_t *bufferPtr = NULL;
size_t bufferPtrSize = 0;
size_t movedBytes;
bufferPtrSize = (plainTextBufferSize + kCCBlockSize3DES) & ~(kCCBlockSize3DES - 1);
bufferPtr = malloc( bufferPtrSize * sizeof(uint8_t));
memset((void *)bufferPtr, 0x0, bufferPtrSize);
NSString *initVec = #"init Vec";
const void *vkey = (const void *)[key UTF8String];
const void *vinitVec;
vinitVec = (const void *) [initVec UTF8String];
//uint8_t initVect[8];
//bzero(initVect, 8);
ccStatus = CCCrypt(kCCDecrypt,
kCCAlgorithmDES,
kCCOptionECBMode|0x0000,
vkey, //"123456789012345678901234", //key
kCCKeySizeDES,
NULL,// vinitVec, //"init Vec", //iv,
vplainText, //"Your Name", //plainText,
plainTextBufferSize,
(void *)bufferPtr,
bufferPtrSize,
&movedBytes);
NSData *myData = [NSData dataWithBytes:(const void *)bufferPtr length:(NSUInteger)movedBytes];
NSString *decodedString = [[NSString alloc] initWithData:myData encoding:NSUTF8StringEncoding];
NSLog(#"dis is data %#",decodedString);
i am getting correct output in java and not in objective c.please provide solution for objective c code
How can I hash some String with SHA-256 in Java?
SHA-256 isn't an "encoding" - it's a one-way hash.
You'd basically convert the string into bytes (e.g. using text.getBytes(StandardCharsets.UTF_8)) and then hash the bytes. Note that the result of the hash would also be arbitrary binary data, and if you want to represent that in a string, you should use base64 or hex... don't try to use the String(byte[], String) constructor.
e.g.
MessageDigest digest = MessageDigest.getInstance("SHA-256");
byte[] hash = digest.digest(text.getBytes(StandardCharsets.UTF_8));
I think that the easiest solution is to use Apache Common Codec:
String sha256hex = org.apache.commons.codec.digest.DigestUtils.sha256Hex(stringText);
Another alternative is Guava which has an easy-to-use suite of Hashing utilities. For example, to hash a string using SHA256 as a hex-string you would simply do:
final String hashed = Hashing.sha256()
.hashString("your input", StandardCharsets.UTF_8)
.toString();
Full example hash to string as another string.
public static String sha256(final String base) {
try{
final MessageDigest digest = MessageDigest.getInstance("SHA-256");
final byte[] hash = digest.digest(base.getBytes("UTF-8"));
final StringBuilder hexString = new StringBuilder();
for (int i = 0; i < hash.length; i++) {
final String hex = Integer.toHexString(0xff & hash[i]);
if(hex.length() == 1)
hexString.append('0');
hexString.append(hex);
}
return hexString.toString();
} catch(Exception ex){
throw new RuntimeException(ex);
}
}
If you are using Java 8 you can encode the byte[] by doing
MessageDigest digest = MessageDigest.getInstance("SHA-256");
byte[] hash = digest.digest(text.getBytes(StandardCharsets.UTF_8));
String encoded = Base64.getEncoder().encodeToString(hash);
import java.security.MessageDigest;
public class CodeSnippets {
public static String getSha256(String value) {
try{
MessageDigest md = MessageDigest.getInstance("SHA-256");
md.update(value.getBytes());
return bytesToHex(md.digest());
} catch(Exception ex){
throw new RuntimeException(ex);
}
}
private static String bytesToHex(byte[] bytes) {
StringBuffer result = new StringBuffer();
for (byte b : bytes) result.append(Integer.toString((b & 0xff) + 0x100, 16).substring(1));
return result.toString();
}
}
String hashWith256(String textToHash) {
MessageDigest digest = MessageDigest.getInstance("SHA-256");
byte[] byteOfTextToHash = textToHash.getBytes(StandardCharsets.UTF_8);
byte[] hashedByetArray = digest.digest(byteOfTextToHash);
String encoded = Base64.getEncoder().encodeToString(hashedByetArray);
return encoded;
}
I traced the Apache code through DigestUtils and sha256 seems to default back to java.security.MessageDigest for calculation. Apache does not implement an independent sha256 solution. I was looking for an independent implementation to compare against the java.security library. FYI only.
In Java 8
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Scanner;
import javax.xml.bind.DatatypeConverter;
Scanner scanner = new Scanner(System.in);
String password = scanner.nextLine();
scanner.close();
MessageDigest digest = null;
try {
digest = MessageDigest.getInstance("SHA-256");
} catch (NoSuchAlgorithmException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
byte[] hash = digest.digest(password.getBytes(StandardCharsets.UTF_8));
String encoded = DatatypeConverter.printHexBinary(hash);
System.out.println(encoded.toLowerCase());
This was my approach using Kotlin:
private fun getHashFromEmailString(email : String) : String{
val charset = Charsets.UTF_8
val byteArray = email.toByteArray(charset)
val digest = MessageDigest.getInstance("SHA-256")
val hash = digest.digest(byteArray)
return hash.fold("", { str, it -> str + "%02x".format(it)})
}
This is what i have been used for hashing:
String pass = "password";
MessageDigest messageDigest = MessageDigest.getInstance("SHA-256");
byte hashBytes[] = messageDigest.digest(pass.getBytes(StandardCharsets.UTF_8));
BigInteger noHash = new BigInteger(1, hashBytes);
String hashStr = noHash.toString(16);
Output: 5e884898da28047151d0e56f8dc6292773603d0d6aabbdd62a11ef721d1542d8
Here is a slightly more performant way to turn the digest into a hex string:
private static final char[] hexArray = "0123456789abcdef".toCharArray();
public static String getSHA256(String data) {
StringBuilder sb = new StringBuilder();
try {
MessageDigest md = MessageDigest.getInstance("SHA-256");
md.update(data.getBytes());
byte[] byteData = md.digest();
sb.append(bytesToHex(byteData);
} catch(Exception e) {
e.printStackTrace();
}
return sb.toString();
}
private 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] = hexArray[v >>> 4];
hexChars[j * 2 + 1] = hexArray[v & 0x0F];
}
return String.valueOf(hexChars);
}
Does anyone know of a faster way in Java?
This method return a left padded String with zero:
Java 10 and after:
public static String sha256(String text) {
try {
var messageDigest = MessageDigest.getInstance("SHA-256");
var hash = messageDigest.digest(text.getBytes(StandardCharsets.UTF_8));
return String.format("%064x", new BigInteger(1, hash));
}
catch (NoSuchAlgorithmException e) {
e.printStackTrace();
return null;
}
}
Java 8:
public static String sha256(String text) {
try {
MessageDigest messageDigest = MessageDigest.getInstance("SHA-256");
byte[] hash = messageDigest.digest(text.getBytes(StandardCharsets.UTF_8));
return String.format("%064x", new BigInteger(1, hash));
}
catch (NoSuchAlgorithmException e) {
e.printStackTrace();
return null;
}
}
BTW, you can use "%064X" for an uppercase result.
Example:
System.out.println(sha256("hello world 1"));
063dbf1d36387944a5f0ace625b4d3ee36b2daefd8bdaee5ede723637efb1cf4
Comparison to Linux cmd:
$ echo -n 'hello world 1' | sha256sum
063dbf1d36387944a5f0ace625b4d3ee36b2daefd8bdaee5ede723637efb1cf4 -
You can use MessageDigest in the following way:
public static String getSHA256(String data){
StringBuffer sb = new StringBuffer();
try{
MessageDigest md = MessageDigest.getInstance("SHA-256");
md.update(data.getBytes());
byte byteData[] = md.digest();
for (int i = 0; i < byteData.length; i++) {
sb.append(Integer.toString((byteData[i] & 0xff) + 0x100, 16).substring(1));
}
} catch(Exception e){
e.printStackTrace();
}
return sb.toString();
}
Here's a method that shows how to hash a String with the sha-256
algorithm and encode the result in hex format. This is an often used format to hash and store passwords in a database:
public static String sha256(final String data) {
try {
final byte[] hash = MessageDigest.getInstance("SHA-256").digest(data.getBytes(StandardCharsets.UTF_8));
final StringBuilder hashStr = new StringBuilder(hash.length);
for (byte hashByte : hash)
hashStr.append(Integer.toHexString(255 & hashByte));
return hashStr.toString();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
return null;
}
}
public static String sha256(String s) {
try {
return DatatypeConverter.printHexBinary(MessageDigest.getInstance("SHA-256").digest(s.getBytes(StandardCharsets.UTF_8))).toLowerCase();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
return null;
}
In Java, MessageDigest class is used to calculate cryptographic hashing value. This class provides cryptographic hash function ( MD5, SHA-1 and SHA-256) to find hash value of text.
Code example for using SHA-256 algorithm.
public void printHash(String str) throws NoSuchAlgorithmException {
MessageDigest md=MessageDigest.getInstance("SHA-256");
byte[] sha256=md.digest(str.getBytes(StandardCharsets.UTF_8));
for(byte b : sha256){
System.out.printf("%02x",b);
}
}
private static String getMessageDigest(String message, String algorithm) {
MessageDigest digest;
try {
digest = MessageDigest.getInstance(algorithm);
byte data[] = digest.digest(message.getBytes("UTF-8"));
return convertByteArrayToHexString(data);
} catch (NoSuchAlgorithmException | UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
You can call above method with different algorithms like below.
getMessageDigest(message, "MD5");
getMessageDigest(message, "SHA-256");
getMessageDigest(message, "SHA-1");
You can refer this link for complete application.