/*param:
pKey:密钥(十六进制)
strPlainAKey:需要加解密的字符串(十六进制)
ciperAKey:返回值
iflag:1解密 0加密*/
void getCiper(char* pKey, char* strPlainAKey, char* ciperAKey, intiflag)
{
unsignedchar binPlainAKey[64] = {0};
hex2binary(binPlainAKey, strPlainAKey, strlen(strPlainAKey));
ASCIIStr2BinCharStrBy3DES(pKey,(unsignedchar*)binPlainAKey,strlen(strPlainAKey)/2, (unsigned char*)ciperAKey, iflag);
}/*param:
pKey:密钥(十六进制)
inBinary:加解密字符串的字节形式
inLen:加解密字符串的长度
binCharString:返回值
iflag:1解密 0加密*/
void ASCIIStr2BinCharStrBy3DES(char* pKey, unsigned char* inBinary, int inLen, unsigned char* binCharString,intiflag)
{
unsignedchar targetIdBin[DESBINARY_LEN] = {0}; //TargetIdLen=8//3DES encription
unsigned charkey[LEN_OF_KEY];
unsignedchar block_key[9];
memset(key,0, LEN_OF_KEY);
hex2binary(key, pKey, strlen(pKey));
DES_key_schedule ks,ks2,ks3;
memset(block_key,0, sizeof(block_key));
memcpy(block_key, key+ 0, 8);
DES_set_key_unchecked((const_DES_cblock*)block_key, &ks);
memcpy(block_key, key+ 8, 8);
DES_set_key_unchecked((const_DES_cblock*)block_key, &ks2);
memcpy(block_key, key+ 0, 8);
DES_set_key_unchecked((const_DES_cblock*)block_key, &ks3);
unsignedchar input[8];
memset(input,0, sizeof(input));
unsignedcharencryptedOutBinary[DESBINARY_LEN];
memset(encryptedOutBinary,0, sizeof(encryptedOutBinary));for(int i=0; i
{
memset(targetIdBin,0, sizeof(targetIdBin));
memcpy((void*)targetIdBin, (const void*)(inBinary+i*8), 8);
DES_ecb3_encrypt((const_DES_cblock*)targetIdBin, (DES_cblock*)encryptedOutBinary, &ks, &ks2, &ks3, iflag);
binary2char((char*)binCharString+i*16, encryptedOutBinary, DESBINARY_LEN);
}
}//
//A public function: convert binary string to character string, the character string‘s length = 2//binary string.//@param charArray: character array. output.//@param binArray: binary array. input.//@param binLen: length of binary array.//void binary2char(char* charArray, const unsigned char* binArray, intbinLen)
{inti;for(i = 0; i < binLen; i++)
{
sprintf(charArray+ 2*i, "%02X", binArray[i]);
}
charArray[2*i] = ‘\0‘;
}//
//A public function: convert hex string to binary string, the hex string‘s length = 2 * binary string.//@param binArray: binary array. output.//@param hexCharArray: character array contains hex string. input.//@param hexLen: length of hex string array. input.//
void hex2binary(unsigned char* binArray, const char* hexCharArray, inthexLen)
{if (hexLen%2 != 0)
{
printf("hex2binary(): length of input parameter hexCharArray should be even number!\n");return;
}inti, j;//convert two hex chars to one byte
char atom[2 + 1] = "\0";for (i = 0, j = 0; i < hexLen/2; i++, j+=2)
{
strncpy(atom, hexCharArray+ j, sizeof(atom) - 1);
atom[sizeof(atom) - 1] = ‘\0‘;
binArray[i]= (unsigned char)strtol(atom, NULL, 16);
}
}