I am trying to encrypt and decrypt a string of data using 3DES and it is working fine. However I want that the size of the data after encryption to be limited to length of 16 bits.
This is the code I am referring from https://gist.github.com/riversun/6e15306cd6e3b1b37687a0e5cec1cef1 :
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
public class DesedeCrypter {
private static final String CRYPT_ALGORITHM = "DESede";
private static final String PADDING = "DESede/CBC/NoPadding";
private static final String CHAR_ENCODING = "UTF-8";
private static final byte[] MY_KEY = "5oquil2oo2vb63e8ionujny6".getBytes();//24-byte
private static final byte[] MY_IV = "3oco1v52".getBytes();//8-byte
public static void main(String[] args) {
String srcText = "M3A1B2C3D4HHG393";
final DesedeCrypter crypter = new DesedeCrypter();
String encryptedText = crypter.encrypt(srcText);
System.out.println("sourceText=" + srcText + " -> encryptedText=" + encryptedText + "\n");
System.out.println("encrypted-text=" + encryptedText + " -> decrypted-text(source text)="
+ crypter.decrypt(encryptedText));
}
public String encrypt(String text) {
String retVal = null;
try {
final SecretKeySpec secretKeySpec = new SecretKeySpec(MY_KEY, CRYPT_ALGORITHM);
final IvParameterSpec iv = new IvParameterSpec(MY_IV);
final Cipher cipher = Cipher.getInstance(PADDING);
cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec, iv);
final byte[] encrypted = cipher.doFinal(text.getBytes(CHAR_ENCODING));
retVal = new String(encodeHex(encrypted));
} catch (Exception e) {
e.printStackTrace();
}
return retVal;
}
public String decrypt(String text) {
String retVal = null;
try {
final SecretKeySpec secretKeySpec = new SecretKeySpec(MY_KEY, CRYPT_ALGORITHM);
final IvParameterSpec iv = new IvParameterSpec(MY_IV);
final Cipher cipher = Cipher.getInstance(PADDING);
cipher.init(Cipher.DECRYPT_MODE, secretKeySpec, iv);
final byte[] decrypted = cipher.doFinal(decodeHex(text.toCharArray()));
retVal = new String(decrypted, CHAR_ENCODING);
} catch (Exception e) {
e.printStackTrace();
}
return retVal;
}
private byte[] decodeHex(char[] data) throws Exception {
int len = data.length;
if ((len & 0x01) != 0) {
throw new Exception("Odd number of characters.");
}
byte[] out = new byte[len >> 1];
// two characters form the hex value.
for (int i = 0, j = 0; j < len; i++) {
int f = toDigit(data[j], j) << 4;
j++;
f = f | toDigit(data[j], j);
j++;
out[i] = (byte) (f & 0xFF);
}
return out;
}
private int toDigit(char ch, int index) throws Exception {
int digit = Character.digit(ch, 16);
if (digit == -1) {
throw new Exception("Illegal hexadecimal character " + ch + " at index " + index);
}
return digit;
}
private char[] encodeHex(byte[] data) {
final char[] DIGITS = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
int l = data.length;
char[] out = new char[l << 1];
// two characters form the hex value.
for (int i = 0, j = 0; i < l; i++) {
out[j++] = DIGITS[(0xF0 & data[i]) >>> 4];
out[j++] = DIGITS[0x0F & data[i]];
}
return out;
}
}
Currently this is the output I am getting:
sourceText=M3A1B2C3D4HHG393 -> encryptedText=afc1d48ea5cc703253cbc1a88a198103
encrypted-text=afc1d48ea5cc703253cbc1a88a198103 -> decrypted-text(source text)=M3A1B2C3D4HHG393
Is there any way that the size of the encryptedText be limited to 16 as I want to add the encrypted text back into a message which has 16 digits space for encrypted text.
Please suggest some way or any other change that is required to achieve this. Thanks !
For one, I highly recommend not supporting (3)DES anymore, as it's officially unsecure in favour of AES/ChaCha, which I must say before answering this question.
3DES has a block size of 64 bits (or 8 bytes). With that also comes that encryption ≠ compression. So if you want to encrypt 16 bytes, provide 16 bytes of input, unless:
You apply a padding scheme (which it appears you're not doing)(taken from the DESede/CBC/NoPadding
You apply a (random) initialisation vector (which it appears you're doing)
The latter one should, but I'm not to sure of Android's implementation, create a 64 bits (8 byte) iv, as the iv should be as big as the block size of the cipher (again, 64 bits for 3DES).
So if you want 16 bytes of output, you can, and should, only provide 8 bytes to encrypt. Now, if 8 bytes is not enough, you might choose to drop the iv from being in the ciphertext, which you could do if you use a fixed iv (such as an all zero iv) with random keys, as reusing the same key with iv is not secure.
Now if you do take security in consideration, keep in mind that AES has a block size of 16 bytes. AES and ChaCha come with the same constraints regarding the iv.
Then you might also might want to consider changing the message (protocol) instead, so it can take more than 16 bytes of data or use those 16 bytes in such a way that it indicates that there is more data to handle, as like an attachment to an e-mail.
Related
I wrote this simple Java program which encrypt a string and output the hex value of the iv, salt, derived key and cipher text.
public class tmp{
static Cipher encryptionCipher;
static String RANDOM_ALGORITHM = "SHA1PRNG";
static String PBE_ALGORITHM = "PBEWithSHA256And256BitAES-CBC-BC";
static String CIPHER_ALGORITHM = "AES/CBC/PKCS7Padding";
static String SECRET_KEY_ALGORITHM = "AES";
static int PBE_ITERATION_COUNT = 2048;
static String PROVIDER = "BC";
public static byte[] generateIv() {
try{
SecureRandom random;
random = SecureRandom.getInstance(RANDOM_ALGORITHM);
byte[] iv = new byte[16];
random.nextBytes(iv);
return iv;
} catch(Exception e){
return null; // Always must return something
}
}
public static byte[] generateSalt() {
try {SecureRandom random;
random = SecureRandom.getInstance(RANDOM_ALGORITHM);
byte[] salt = new byte[32];
random.nextBytes(salt);
return salt;
} catch(Exception e){
return null; // Always must return something
}
}
public static SecretKey getSecretKey(String password, byte[] salt){
try {
PBEKeySpec pbeKeySpec = new PBEKeySpec(password.toCharArray(), salt, PBE_ITERATION_COUNT, 256);
SecretKeyFactory factory = SecretKeyFactory.getInstance(PBE_ALGORITHM, PROVIDER);
SecretKey tmp = factory.generateSecret(pbeKeySpec);
return new SecretKeySpec(tmp.getEncoded(), SECRET_KEY_ALGORITHM);
} catch(Exception e){
System.out.println(e); // Always must return something
return null;
}
}
public static String encrypt(String plaintext, Key key, byte[] iv) {
try {
AlgorithmParameterSpec ivParamSpec = new IvParameterSpec(iv);
encryptionCipher = Cipher.getInstance(CIPHER_ALGORITHM, PROVIDER);
encryptionCipher.init(Cipher.ENCRYPT_MODE, key, ivParamSpec);
byte[] ciphertext = encryptionCipher.doFinal(plaintext.getBytes("UTF-8"));
String cipherHexString = DatatypeConverter.printHexBinary(ciphertext);
return cipherHexString;
}
catch (Exception e) {
System.out.println(e);
return null;
}
}
public static void main (String[] Args){
SecretKey key;
//sha512(ciao)
String encami = "This is a test pharse. Thanks!!";
String password = "a0c299b71a9e59d5ebb07917e70601a3570aa103e99a7bb65a58e780ec9077b1902d1dedb31b1457beda595fe4d71d779b6ca9cad476266cc07590e31d84b206";
byte[] iv = new byte[16];
byte[] salt = new byte[32];
iv = generateIv();
salt = generateSalt();
String ll = DatatypeConverter.printHexBinary(iv);
String lp = DatatypeConverter.printHexBinary(salt);
System.out.println(ll);
System.out.println(lp);
key = getSecretKey(password, salt);
byte tt[] = new byte[32];
tt = key.getEncoded();
String lo = DatatypeConverter.printHexBinary(tt);
System.out.println(lo);
String outenc = encrypt(encami, key, iv);
System.out.println(outenc);
}
}
In the following C program iv and salt are initialized with the values given by the above Java program. No padding needed since the length of the text is 32 bytes.
#include <stdio.h>
#include <gcrypt.h>
#include <stdlib.h>
#include <string.h>
int
main (void)
{
int i;
char *encami = "This is a test pharse. Thanks!!";
char *pwd = "a0c299b71a9e59d5ebb07917e70601a3570aa103e99a7bb65a58e780ec9077b1902d1dedb31b1457beda595fe4d71d779b6ca9cad476266cc07590e31d84b206";
unsigned char iv[] = {};
unsigned char salt[] = {};
int algo = gcry_cipher_map_name("aes256");
unsigned char *devkey = NULL;
unsigned char *enc_buf = NULL;
enc_buf = gcry_malloc(32);
devkey = gcry_malloc_secure (32);
gcry_cipher_hd_t hd;
gcry_cipher_open(&hd, algo, GCRY_CIPHER_MODE_CBC, 0);
gcry_kdf_derive (pwd, strlen(pwd)+1, GCRY_KDF_PBKDF2, GCRY_MD_SHA256, salt, 32, 2048, 32, devkey);
for (i=0; i<32; i++)
printf ("%02x", devkey[i]);
printf("\n");
gcry_cipher_setkey(hd, devkey, 32);
gcry_cipher_setiv(hd, iv, 16);
gcry_cipher_encrypt(hd, enc_buf, strlen(encami)+1, encami, strlen(encami)+1);
for (i=0; i<32; i++)
printf("%02x", enc_buf[i]);
printf("\n");
gcry_cipher_close(hd);
gcry_free(enc_buf);
gcry_free (devkey);
return 0;
}
My problem is that the derived key is not the same in those two programs. Why?
Is the bouncy castle deriving function not working in the same way as gcry_kdf_derive?
Thanks!
I've now looked into the PBEWithSHA256And256BitAES-CBC-BC algorithm in the BC provider, and found that it is not compatible with GCRY_KDF_PBKDF2. The gcrypt algorithm is PKCS#5 2.0 Scheme 2, whereas the BC one is actually implementing PKCS#12.
Actually, I've so far not found a named algorithm in the provider that matches the gcrypt one, however I was able to use the BC API directly to get matching results b/w them, as follows.
Bouncy Castle:
byte[] salt = new byte[8];
Arrays.fill(salt, (byte)1);
PBEParametersGenerator pGen = new PKCS5S2ParametersGenerator(new SHA256Digest());
pGen.init(Strings.toByteArray("password"), salt, 2048);
KeyParameter key = (KeyParameter)pGen.generateDerivedParameters(256);
System.out.println(Hex.toHexString(key.getKey()));
gcrypt:
unsigned char salt[8];
memset(salt, 1, 8);
unsigned char key[32];
gcry_kdf_derive("password", 8, GCRY_KDF_PBKDF2, GCRY_MD_SHA256, salt, 8, 2048, 32, key);
for (int i = 0; i < 32; ++i)
printf("%02x", key[i]);
printf("\n");
which both output:
4182537a153b1f0da1ccb57971787a42537e38dbf2b4aa3692baebb106fc02e8
You appear to be including a terminating NULL character in your count of 32 bytes (encami), which explains the differing outputs. The java version sees a 31-character input and provides a single PKCS#7-padded output block (PKCS#7 will pad the input with a single '1' byte). The C version is passed 32 bytes, including the final '0' byte. So the inputs are different.
I recommend you stop treating the NULL terminator as part of the input; instead apply PKCS#7 padding, as the Java version is doing. I'm not familiar with gcrypt, so I don't know what the typical method is for doing this, but PKCS#7 padding is a quite simple concept in any case.
I tried using salt to decrypt a AES encrypted message but it always returns null value. Can anyone look at it where am i doing wrong?
public static String decryptMessage(String encryptedMessage, String salt) {
String decryptedMessage = null;
String valueToDecrypt = encryptedMessage;
try {
Key key = generateKey();
Cipher c = Cipher.getInstance(ALGORITHM);
c.init(Cipher.DECRYPT_MODE, key);
for (int i = 0; i < ITERATIONS; i++) {
byte[] decodedValue = Base64.decodeBase64(valueToDecrypt);
byte[] decVal = c.doFinal(decodedValue);
decryptedMessage = new String(decVal).substring(salt.length());
valueToDecrypt = decryptedMessage;
}
} catch (Exception e) {
e.printStackTrace();
}
return decryptedMessage;
}
**EDIT:**
Here is corresponding encryption method which i assume, works.
private static final String ALGORITHM = "AES";
private static final int ITERATIONS = 5;
private static final byte[] keyValue = new byte[] { '1', '2', '3', '4',
'5', '6', '7', '8', '9', '0', '1', '2', '3', '4', '5', '6' };
public static String encryptMessage(String message, String salt) {
String encMessage = null;
byte[] encVal = null;
String messageWithSalt = null;
try {
Key key = generateKey();
Cipher c = Cipher.getInstance(ALGORITHM);
c.init(Cipher.ENCRYPT_MODE, key);
for (int i = 0; i < ITERATIONS; i++) {
messageWithSalt = salt + encMessage;
encVal = c.doFinal(messageWithSalt.getBytes());
byte[] encryptedValue = new Base64().encode(encVal);
encMessage = new String(encryptedValue);
}
} catch (Exception e) {
e.printStackTrace();
}
return encMessage;
}
PS: ITERATION is NOT 0;
I think your method might be chronically broken or misnamed. You are generating a key each time you decrypt, whereas you should have a pre-existing key that matches the one used for encryption.
You also pass in a "salt" value - note: this is a term normally reserved for hashing - which you then completely ignore, except to use the size as a truncation length on your result.
Certainly what I see above is not decrypting anything in a sensible fashion. If you can describe exactly what you wanted to achieve, we can possibly correct the code or point you at the peer-reviewed method for performing that task (which may already be implemented in the standard libs).
Well, i found the error. It was in the encryption method. encMessage was null before the encryption process begins. String encMessage = message did the trick. So the encryption method is:
public static String encryptMessage(String message, String salt) {
String encMessage = message;
byte[] encVal = null;
String messageWithSalt = null;
try {
Key key = generateKey();
Cipher c = Cipher.getInstance(ALGORITHM);
c.init(Cipher.ENCRYPT_MODE, key);
for (int i = 0; i < ITERATIONS; i++) {
messageWithSalt = salt + encMessage;
encVal = c.doFinal(messageWithSalt.getBytes());
byte[] encryptedValue = new Base64().encode(encVal);
encMessage = new String(encryptedValue);
}
} catch (Exception e) {
e.printStackTrace();
}
return encMessage;
}
I'm following this tutorial to use 3DES encryption, and i needed to make some changes in cipher settings, so here's my code:
public class TripleDES {
public static int MAX_KEY_LENGTH = DESedeKeySpec.DES_EDE_KEY_LEN;
private static String ENCRYPTION_KEY_TYPE = "DESede";
private static String ENCRYPTION_ALGORITHM = "DESede/ECB/PKCS7Padding";
private final SecretKeySpec keySpec;
private final static String LOG = "TripleDES";
public TripleDES(String passphrase) {
byte[] key;
try {
// get bytes representation of the password
key = passphrase.getBytes("UTF8");
} catch (UnsupportedEncodingException e) {
throw new IllegalArgumentException(e);
}
key = padKeyToLength(key, MAX_KEY_LENGTH);
key = addParity(key);
keySpec = new SecretKeySpec(key, ENCRYPTION_KEY_TYPE);
}
// !!! - see post below
private byte[] padKeyToLength(byte[] key, int len) {
byte[] newKey = new byte[len];
System.arraycopy(key, 0, newKey, 0, Math.min(key.length, len));
return newKey;
}
// standard stuff
public byte[] encrypt(String message) throws GeneralSecurityException, UnsupportedEncodingException {
byte[] unencrypted = message.getBytes("UTF8");
return doCipher(unencrypted, Cipher.ENCRYPT_MODE);
}
public byte[] decrypt(byte[] encrypted) throws GeneralSecurityException {
return doCipher(encrypted, Cipher.DECRYPT_MODE);
}
private byte[] doCipher(byte[] original, int mode)
throws GeneralSecurityException {
Cipher cipher = Cipher.getInstance(ENCRYPTION_ALGORITHM);
// IV = 0 is yet another issue, we'll ignore it here
// IvParameterSpec iv = new IvParameterSpec(new byte[] { 0, 0, 0, 0, 0, 0, 0, 0 });
cipher.init(mode, keySpec); //, iv);
return cipher.doFinal(original);
}
// Takes a 7-byte quantity and returns a valid 8-byte DES key.
// The input and output bytes are big-endian, where the most significant
// byte is in element 0.
public static byte[] addParity(byte[] in) {
byte[] result = new byte[8];
// Keeps track of the bit position in the result
int resultIx = 1;
// Used to keep track of the number of 1 bits in each 7-bit chunk
int bitCount = 0;
// Process each of the 56 bits
for (int i = 0; i < 56; i++) {
// Get the bit at bit position i
boolean bit = (in[6 - i / 8] & (1 << (i % 8))) > 0;
// If set, set the corresponding bit in the result
if (bit) {
result[7 - resultIx / 8] |= (1 << (resultIx % 8)) & 0xFF;
bitCount++;
}
// Set the parity bit after every 7 bits
if ((i + 1) % 7 == 0) {
if (bitCount % 2 == 0) {
// Set low-order bit (parity bit) if bit count is even
result[7 - resultIx / 8] |= 1;
}
resultIx++;
bitCount = 0;
}
resultIx++;
}
Log.d(LOG, "result: " + result);
return result;
}
}
But i'm getting InvalidKeyException on this line:
cipher.init(mode, keySpec);
LogCat:
W/System.err(758): java.security.InvalidKeyException: src.length=8 srcPos=8 dst.length=8 dstPos=0 length=8
W/System.err(758): at org.bouncycastle.jce.provider.JCEBlockCipher.engineInit(JCEBlockCipher.java:584)
W/System.err(758): at org.bouncycastle.jce.provider.JCEBlockCipher.engineInit(JCEBlockCipher.java:631)
W/System.err(758): at javax.crypto.Cipher.init(Cipher.java:511)
W/System.err(758): at javax.crypto.Cipher.init(Cipher.java:471)
I'm new on encrytion so i probably overlook something but i cannot find what it is. Any help is appreciated...
Triple DES requires a 24 byte key, not an 8 byte one.
I've found solution by changing these lines:
try {
// get bytes representation of the password
key = passphrase.getBytes("UTF8");
} catch (UnsupportedEncodingException e) {
throw new IllegalArgumentException(e);
}
key = padKeyToLength(key, MAX_KEY_LENGTH);
key = addParity(key);
keySpec = new SecretKeySpec(key, ENCRYPTION_KEY_TYPE);
into these:
Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
byte[] keyBytes = GetKeyAsBytes(key);
keySpec = new SecretKeySpec(keyBytes, "DESede");
while GetKeyAsBytes method is this:
public byte[] GetKeyAsBytes(String key) {
byte[] keyBytes = new byte[24]; // a Triple DES key is a byte[24] array
for (int i = 0; i < key.length() && i < keyBytes.length; i++)
keyBytes[i] = (byte) key.charAt(i);
return keyBytes;
}
I'm trying to take in a long string and encrypt it using the following code:
import java.security.*;
import javax.crypto.*;
import javax.crypto.spec.*;
import java.io.*;
public class AESEncrypt {
/**
* Turns array of bytes into string
*
* #param buf
* Array of bytes to convert to hex string
* #return Generated hex string
*/
public static String asHex(byte buf[]) {
StringBuffer strbuf = new StringBuffer(buf.length * 2);
int i;
for (i = 0; i < buf.length; i++) {
if (((int) buf[i] & 0xff) < 0x10)
strbuf.append("0");
strbuf.append(Long.toString((int) buf[i] & 0xff, 16));
}
return strbuf.toString();
}
public static byte[] hexStringToByteArray(String s) {
int len = s.length();
byte[] data = new byte[len / 2];
for (int i = 0; i < len; i += 2) {
data[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4) + Character
.digit(s.charAt(i + 1), 16));
}
return data;
}
public static void main(String[] args) throws Exception {
String message = "Test text!";
// Get the KeyGenerator
KeyGenerator kgen = KeyGenerator.getInstance("AES");
kgen.init(128); // 192 and 256 bits may not be available
// Generate the secret key specs.
SecretKey skey = kgen.generateKey();
byte[] raw = skey.getEncoded();
SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
System.out.println("Key: " + asHex(raw));
// Instantiate the cipher
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
byte[] encrypted = cipher.doFinal((args.length == 0 ? message : args[0]).getBytes());
System.out.println("encrypted string: " + asHex(encrypted));
}
}
However, I would like to encrypt word by word and print out the encrypted text as such:
Original string -> Test text!
Encrypted string -> 29f84h2f 23f9f92jf3
I couldn't find any examples online that could help me out. Is there anyway I can achieve this?
AES is a block cypher, and it uses 16 byte blocks. It does not work in words, but in fixed blocks. If you want to split up your text into varying size words then you will likely get closer to what you want by using either a stream cypher, such as RC4, or alternatively AES in CTR mode, which effectively turns AES into a stream cypher. Stream cyphers do not work in blocks, but in bytes. You can take 3 bytes off the stream for a 3 letter word, or nine bytes off the stream for a 9 letter word.
You will need to work out what to do with spaces, punctuation etc between words. You will also need to think about how often you re-key the cypher. Do you want to re-key for every individual word, or do you just re-key at the start of each string? As with any stream cypher, never ever use the same key twice.
Try as below example; Actually, It just need to used StringTokenizer. Firstly you have to token your target string. After that, encrypt the token string.
import java.util.StringTokenizer;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
public class AES {
public static String asHex(byte[] buf) {
StringBuffer strbuf = new StringBuffer(buf.length * 2);
int i;
for (i = 0; i < buf.length; i++) {
if (((int)buf[i] & 0xff) < 0x10)
strbuf.append("0");
strbuf.append(Long.toString((int)buf[i] & 0xff, 16));
}
return strbuf.toString();
}
public static void main(String[] args) throws Exception {
KeyGenerator kgen = KeyGenerator.getInstance("AES");
kgen.init(128); // 192 and 256 bits may not be available
// Generate the secret key specs.
SecretKey skey = kgen.generateKey();
byte[] raw = skey.getEncoded();
SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
String target = "This is just an example";
StringTokenizer token = new StringTokenizer(target);
while(token.hasMoreTokens()) {
String temp = token.nextToken();
byte[] encrypted = cipher.doFinal((args.length == 0 ? temp : args[0]).getBytes());
System.out.println(asHex(encrypted) + " ");
}
}
}
Output :
d40186eab04d10e299801e7ad9046c06 6a71265c768a3b6e1f1a8f891d621c1d 735e3f54c8ad7242466e3517e8dd1659 5216643345db0f0c12f65c66c5363be3 b823355d5bb31bf092df98e18fa8001c
I have been working on this for hours, but I can't get it to work.
Basically I am developing a REST client in Java for a REST server in PHP. Both the client and the server have to compute the md5 of a string and the server will compare them for authentication (kinda).
On the server, the PHP code is:
md5("getTokenapi_keybf8ddfs845jhre980543jhsjfro93fd8capi_ver1tokeniud9ER£jdfff");
that generates:
4d7b2e42c3dfd11de3e77b9fe2211b87
Nice!
Here is the code for the client:
import java.security.*;
....
String s = "getTokenapi_keybf8ddfs845jhre980543jhsjfro93fd8capi_ver1tokeniud9ER£jdfff";
byte[] bytesOfMessage = s.getBytes("UTF-8");
MessageDigest md = MessageDigest.getInstance("MD5");
byte[] thedigest = md.digest(bytesOfMessage);
System.out.println("String2: " + thedigest);
System.out.println("String3: " + new String(thedigest));
That generates:
String2: [B#42e816
String3: M{.B�����{��!�
How can I get Java to compute the md5 sum the same way PHP does, please?
Thanks,
Dan
Give this a try:
public static String md5(String input) throws NoSuchAlgorithmException {
String result = input;
if(input != null) {
MessageDigest md = MessageDigest.getInstance("MD5"); //or "SHA-1"
md.update(input.getBytes());
BigInteger hash = new BigInteger(1, md.digest());
result = hash.toString(16);
while(result.length() < 32) { //40 for SHA-1
result = "0" + result;
}
}
return result;
}
code from http://web.archive.org/web/20140209230440/http://www.sergiy.ca/how-to-make-java-md5-and-sha-1-hashes-compatible-with-php-or-mysql/
Found myself:
import java.math.BigInteger;
..
public static String md5(String input) throws NoSuchAlgorithmException {
String result = input;
if(input != null) {
MessageDigest md = MessageDigest.getInstance("MD5"); //or "SHA-1"
md.update(input.getBytes());
BigInteger hash = new BigInteger(1, md.digest());
result = hash.toString(16);
if ((result.length() % 2) != 0) {
result = "0" + result;
}
}
return result;
}
Source: http://www.sergiy.ca/how-to-make-java-md5-and-sha-1-hashes-compatible-with-php-or-mysql/
You are outputting the raw md5 output, which is just a bunch of bytes. You would get the same result in php if you said md5("some string", true).
You need to convert the bytes to ascii characters instead.
You need to convert the result into the HEX representation. This is how it is done in Fast MD5 library:
private static final char[] HEX_CHARS = { '0', '1', '2', '3', '4', '5',
'6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f', };
/**
* Turns array of bytes into string representing each byte as unsigned hex
* number.
*
* #param hash
* Array of bytes to convert to hex-string
* #return Generated hex string
*/
public static String asHex(byte hash[]) {
char buf[] = new char[hash.length * 2];
for (int i = 0, x = 0; i < hash.length; i++) {
buf[x++] = HEX_CHARS[(hash[i] >>> 4) & 0xf];
buf[x++] = HEX_CHARS[hash[i] & 0xf];
}
return new String(buf);
}
So you will need to call System.out.println("String3: " + asHex(thedigest));
if you use spring security framework , just do :
import org.springframework.security.authentication.encoding.*
new Md5PasswordEncoder().encodePassword("myWord",null)
The same result as PHP::md5(). I confirm
See more examples