2012-03-23 2 views
2

Ceci est le code PHP que j'ai.
Besoin de Java équivalent pour le décryptage 3DES du code PHP

function decrypt($s_input, $s_key, $s_iv) { 
    $s_decrypted = pack("H*" , $s_input); // Hex to binary 
    $s_decrypted = mcrypt_decrypt (MCRYPT_3DES, $s_key, $s_decrypted, MCRYPT_MODE_CBC, $s_iv); // 3des decryption 
    return $s_decrypted; 
} 
echo encrypt('c37551bb77f741d0bcdc16497b4f97b1','123456781234567812345678','12345678'); 

ce qu'il fait essentiellement est de décrypter une chaîne cryptée 3DES (d'abord il convertit la chaîne hexadécimale en binaire en utilisant la fonction pack et fait alors le décryptage réel).

Ceci fonctionne parfaitement en PHP-4 et imprime le message "Hello World". Cependant, si j'exécute le code java équivalent (jdk 1.6), il affiche la sortie ordure comme - ¬ªmjV = 7xl_ÓÄ ^> * ?.

Quelqu'un peut-il aider à résoudre ce problème? Pourquoi Java ne décrypte pas correctement la chaîne hexadécimale.

private static String decrypt(String inputStr, String keyStr, String ivStr) throws Exception { 

    IvParameterSpec iv = new IvParameterSpec(ivStr.getBytes()); 
    SecretKeySpec key = new SecretKeySpec(keyStr.getBytes(), "DESede"); 
    inputStr = hexToString(inputStr, 2); 

    Cipher cipher = Cipher.getInstance("DESede/CBC/NoPadding"); 
    cipher.init(Cipher.DECRYPT_MODE, key, iv); 
    byte[] decrypted = cipher.doFinal(inputStr.getBytes()); 

    return new String(decrypted); 
} 

private static String hexToString(String input, int groupLength) { 
    StringBuilder sb = new StringBuilder(input.length()/groupLength); 
    for (int i = 0; i < input.length() - groupLength + 1; i += groupLength) { 
     String hex = input.substring(i, i + groupLength); 
     sb.append((char) Integer.parseInt(hex, 16)); 
    } 
    return sb.toString(); 
} 

public static void main(String[] args) throws Exception { 
    String decryptSignature = decrypt("c37551bb77f741d0bcdc16497b4f97b1", "123456781234567812345678", "12345678"); 
    System.out.println(decryptSignature); 
} 

Répondre

0

Il y a plusieurs choses à vérifier. Vous pourriez trouver Encryption using AES-128 in Java pour être d'une certaine aide. Il pourrait y avoir des problèmes avec les différences entre la façon dont vous manipulez les clés dans le code PHP et Java. Appeler getBytes() sur un String en Java sans un encodage est presque toujours une mauvaise idée. De plus, le rembourrage utilisé pourrait être un problème. De ce que j'ai vu des pads PHP avec null caractères par défaut, ce qui ne correspond pas à NoPadding en Java. Enfin, la méthode hexToString doit renvoyer un byte[] au lieu d'un String. Ajouter le résultat de l'appel Integer.parseInt(hex, 16) dans un tableau:

byte[] results = new byte[input.length()/groupLength]; 
... 
    //inside the loop 
    results[i/groupLength] = (byte) Integer.parseInt(hex, 16); 
... 
return results; 
+0

merci. code que vous avez donné, résolu le problème !! – user1289117

Questions connexes