Traduction decryption d'un string en Java -> Microsoft Crypto API
Bonjour à tous, j'ai essayé de traduire ce code C++ en java puis ça ne fonctionne pas. Est-ce que quelqu'un peut m'aide?
C++
Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
|
std::string &sCryptKeySeed; // My encryption/decryption password
HCRYPTPROV hCryptProv = NULL;
HCRYPTHASH hHash = NULL;
HCRYPTKEY hCryptKey = NULL;
DWORD iLen = iSize;
char *pData = NULL;
if(CryptAcquireContext(&hCryptProv, NULL, NULL, PROV_RSA_FULL, CRYPT_MACHINE_KEYSET))
{
if(CryptCreateHash(hCryptProv, CALG_SHA1, 0, 0, &hHash))
{
if(CryptHashData(hHash, (BYTE *)sCryptKeySeed.c_str(), sCryptKeySeed.length(), 0))
{
if(CryptDeriveKey(hCryptProv, CALG_RC2, hHash, 0, &hCryptKey))
{
if(CryptDecrypt(hCryptKey, NULL, TRUE, 0, (BYTE *)pData, &iLen))
{
sValue.assign(pData);
}
}
}
CryptDestroyHash(hHash);
hHash = NULL;
}
CryptReleaseContext(hCryptProv, 0);
hCryptProv = NULL;
} |
Ce que j'ai essayé et rien ne fonctionne...
Java
Code:
1 2 3 4 5 6 7 8 9
|
byte[] password = sCryptKeySeed.getBytes("UTF-8");
byte iv[] = {1,2,3,4,5,6,7,8};
MessageDigest digest = MessageDigest.getInstance("SHA-1");
byte[] hash = digest.digest(password);
Cipher rc2 = Cipher.getInstance("RC2");
rc2.init(Cipher.DECRYPT_MODE, new SecretKeySpec(hash, "RC2"), new RC2ParameterSpec(128,iv));
String decryptedValue = new String(rc2.doFinal(value.getBytes()), "UTF-8"); |
Merci beaucoup
Solution :
Si ça intéresse quelqu'un la bonne façon de traduire ce code en C++ est :
Code:
1 2 3 4 5 6 7 8 9 10 11 12 13
|
MessageDigest digest = MessageDigest.getInstance("SHA-1");
byte[] hash = digest.digest(sCryptKeySeed.getBytes());
hash = Arrays.copyOfRange(hash, 0, 16);
SecretKeySpec rc2keySPec = new SecretKeySpec(hash,"RC2");
RC2ParameterSpec param = new RC2ParameterSpec(128, new byte[8]);
Cipher rc2 = Cipher.getInstance("RC2/CBC/PKCS5Padding");
rc2.init(Cipher.DECRYPT_MODE, rc2keySPec, param);
String decryptedValue = new String(rc2.doFinal(value.getBytes())); |
Dernière question :
Si j'inclue des "-" ou des "_" dans le sCryptKeySeed comme ceci :
Code:
sCryptKeySeed = "SDFSD2-DF45-ASD5-BLA_BLA"
La decryption génère des caractère étranges comme ceci :
Code:
4D7B2B4F7F14C544AD28C802tÅv¾)¨¸*E557912062013
Ce qui est supposé de sortir :
Code:
4D7B2B4F7F14C544AD28C80227849D54E5579127062013
Est-ce que quelqu'un aurait une idée pourquoi il sort ceci?