C ++ / CLI函数
我正在使用C ++ / CLI生成哈希密钥,并通过网络将数据和哈希密钥发送到其他用Java编码的应用程序。
但是Java应用程序会生成另一个HashKey。
是由于不同服务器上的应用程序不同而导致哈希键不同吗?
任何想法我要去哪里错了?
预先感谢。
char* EncodeData(char* ap_key, char* ap_sourceData)
{
char* lp_data_to_send = NULL;
int key_len = strlen(ap_key);
String^ lv_data = gcnew String(ap_sourceData);//Getting Data in System String
array<Byte>^ lv_main_data = Encoding::UTF8->GetBytes(lv_data);//Encoding to UTF-8
array<Byte>^key = gcnew array< Byte >(key_len + 2);
Marshal::Copy((IntPtr)ap_key, key, 0, key_len); //Copy key in System Array Byte
// Initialize the keyed hash object.
HMACSHA256^ myhmacsha256 = gcnew HMACSHA256(key);
// Compute the hash of the input file.
array<Byte>^hashValue = myhmacsha256->ComputeHash(lv_main_data);
String^ lv_hex_convert = BitConverter::ToString(hashValue)->Replace("-",""); //Converted to Hexadecimal and replacing '-' with ""
Console::WriteLine(lv_hex_convert);//Converted Hexadecimal Hashkey
//Converting to Char*
lp_data_to_send = (char*)(void*)System::Runtime::InteropServices::Marshal::StringToHGlobalAnsi(lv_hex_convert);//Converting again to char* to be send to Calling Function
myhmacsha256->Clear(); //myhmacsha256 clear Instance
return lp_data_to_send;//Return Char*
}
int main()
{
//Secret Key shared by C++/CLi application and Java Application
String ^ lv_key_g = " My Secret Key";
char lv_sourceData[] = { "My data" };
char lv_destinationData[512] = { "" };
char* lp_ret = NULL;
array<Byte>^secretkey = gcnew array<Byte>(65); //Declaring Array
//Converting to UTF-8
secretkey = Encoding::UTF8->GetBytes(lv_key_g);
/*Converting to char* */
pin_ptr<System::Byte> p = &secretkey[0];
unsigned char* pby = p;
//Converting to Char* to send
char* lp_key = reinterpret_cast<char*>(pby);//Converting data to char*
/*End converting to Byte Array*/
lp_ret = EncodeData(lp_key, lv_sourceData);//calling Function
}
JAVA功能
String key = "My Key"; //Hash Key Shared by Both Application
String hashKey = "My Data"; //Data Shared by both Application
Mac sha256_HMAC = null;
try {
//Creating Instance
sha256_HMAC = Mac.getInstance("HmacSHA256");
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
SecretKeySpec secret_key = null;
try {
secret_key = new SecretKeySpec(key.getBytes("UTF-8"), "HmacSHA256");//UTF-8 Secret Key
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
try {
sha256_HMAC.init(secret_key); //Init Secret Key
} catch (InvalidKeyException e) {
e.printStackTrace();
}
final byte[] mac_data = sha256_HMAC.doFinal(hashKey.getBytes()); //Get Data in Bytes
String result = "";
for (final byte element : mac_data){
//Using Radix 16 to convert to String
result += Integer.toString((element & 0xff) + 0x100, 16).substring(1); //Converting to Hexadecimal
}
System.out.print(result);//Hashkey Print
答案 0 :(得分:0)
return lp_data_to_send;//Return Char*
将返回一个悬空指针,您可能应该返回一个引用计数的字符串lv_hex_convert
。另一个可疑的事情是密钥比要求的要长2个字节。