银行系统的密钥有三种,主密钥/pinkey/Mackey,其中pinkey是用来加密密码的,而mackey是用来校验报文是否有错码,主密钥是用来加密pinkey和mackey的.
其中主密钥加密pinkey和mackey是是用3des来加解密的
代码如下:
/* param: pKey:密钥(十六进制) strPlainAKey:需要加解密的字符串(十六进制) ciperAKey:返回值 iflag:1解密 0加密 */ void getCiper(char* pKey, char* strPlainAKey, char* ciperAKey, int iflag) { unsigned char binPlainAKey[64] = {0}; hex2binary(binPlainAKey, strPlainAKey, strlen(strPlainAKey)); ASCIIStr2BinCharStrBy3DES(pKey,(unsigned char*)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,int iflag) { unsigned char targetIdBin[DESBINARY_LEN] = {0}; //TargetIdLen=8 // 3DES encription unsigned char key[LEN_OF_KEY]; unsigned char 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); unsigned char input[8]; memset(input, 0, sizeof(input)); unsigned char encryptedOutBinary[DESBINARY_LEN]; memset(encryptedOutBinary, 0, sizeof(encryptedOutBinary)); for(int i=0; i<inLen/8; 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, int binLen) { int i; for(i = 0; i < binLen; i++) { sprintf(charArray + 2*i, "%02X", binArray[i]); } charArray[2*i] = '