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?
Related
I'm trying to hash data "text" to be transferred from Java Service to C# Service.
I'm using SHA256 as a Hashing algorithm, but despite the values and the salt being the same the result doesn't.
Here is my C# snippet
public string Sign(string textToHash, string salt){
byte[] convertedHash = new byte[salt.Length / 2];
for (int i = 0; i < salt.Length / 2; i++)
convertedHash[i] = (byte)int.Parse(salt.Substring(i * 2, 2), NumberStyles.HexNumber);
HMAC hasher = new HMACSHA256(convertedHash);
string hexHash = "";
using (hasher)
{
byte[] hashValue = hasher.ComputeHash(Encoding.UTF8.GetBytes(textToHash));
foreach (byte b in hashValue)
{
hexHash += b.ToString("X2");
}
}
return hexHash;
}
And, here is the Java snippet
public static String sign(String textToHash, String salt){
byte[] convertedHash = new byte[salt.length() / 2];
for (int i = 0; i < salt.length() / 2; i++)
{
convertedHash[i] = (byte)Integer.parseInt(salt.substring(i * 2, i * 2 + 2),16);
}
String hashedText = null;
try {
MessageDigest md = MessageDigest.getInstance("SHA-256");
md.update(convertedHash);
byte[] bytes = md.digest(textToHash.getBytes(StandardCharsets.UTF_8));
StringBuilder sb = new StringBuilder();
for (byte aByte : bytes) {
sb.append(Integer.toString((aByte & 0xff) + 0x100, 16).substring(1));
}
hashedText = sb.toString();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
return hashedText;
}
In Java, I also tried
convertedHash = salt.getBytes();
But I got different results also.
Tests:
salt = ABCDEFG
text = hashme
Result in C#
70B38047C28FFEDCF7275C428E65310671CADB65F11A5C9A8CFBB3CF52112BA3
Result in Java
a8bc36606aade01591a1d12c8b3c87aca1fe55def79740def03a90b49f2c6b7c
So, any help about why the results aren't the same.
Thanks in advance.
To mimic the Java hashing, I used SHA256Managed rather than HMACSHA256 in C#
public static string Sign(string data, string salt)
{
UTF8Encoding encoder = new UTF8Encoding();
SHA256Managed sha256hasher = new SHA256Managed();
byte[] convertedHash = new byte[salt.Length / 2];
for (int i = 0; i < salt.Length / 2; i++)
convertedHash[i] = (byte)int.Parse(salt.Substring(i * 2, 2), NumberStyles.HexNumber);
byte[] dataBytes = encoder.GetBytes(data);
byte[] bytes = new byte[convertedHash.Length + dataBytes.Length];
Array.Copy(convertedHash, bytes, convertedHash.Length);
Array.Copy(dataBytes, 0, bytes, convertedHash.Length, dataBytes.Length);
byte[] hashedBytes = sha256hasher.ComputeHash(bytes);
return hashedBytes.Aggregate("", (current, t) => current + t.ToString("X2"));
}
HMACSHA256 is not a pure SHA-256.
byte[] input = {0xA,0xB,0xC,0xD};
MessageDigest md = MessageDigest.getInstance("SHA-256");
byte[] digest = md.digest(input);
for(int i=0; i<digest.length; i++) {
System.out.format("%x",digest[i]&0xff);
}
I know how to get the hash with a text string, but I don't get the correct digest for this input. The correct is:
SHA256(0xABCD) = 123d4c7ef2d1600a1b3a0f6addc60a10f05a3495c9409f2ecbf4cc095d000a6b
byte[] input = {(byte)0xAB,(byte)0xCD};
MessageDigest md = MessageDigest.getInstance("SHA-256");
byte[] digest = md.digest(input);
for (int i=0; i < digest.length; i++) {
sb.append(Integer.toString((digest[i] & 0xff) + 0x100, 16).substring(1));
}
System.out.println(sb.toString());
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 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
I'm having a lot of trouble converting the following code to Objective-C, can anyone lend a hand:
public String encodeString(String s) {
try {
// Create MD5 Hash
MessageDigest digest = java.security.MessageDigest.getInstance("MD5");
digest.update(s.getBytes());
byte messageDigest[] = digest.digest();
Base64 b = null;
return b.encodeToString(messageDigest,1);
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
return "";
}
This should work:
#import <CommonCrypto/CommonDigest.h>
- (NSString *) encodeString:(NSString *) s {
const char *cStr = [s UTF8String];
unsigned char result[CC_MD5_DIGEST_LENGTH];
CC_MD5(cStr, strlen(cStr), result);
NSMutableString *result = [NSMutableString stringWithCapacity:CC_MD5_DIGEST_LENGTH * 2];
for(int i = 0; i < CC_MD5_DIGEST_LENGTH; ++i) {
[result appendFormat:#"%02x", result[i]];
}
return [NSString stringWithString:result];
}