由于是在网上找到的一份源代码,在此基础上进行驱动移植。里面的加密算法没有仔细研究也很难看得懂,而且一直让我很迷惑的是,芯片手册里压根没提到用什么加密算法,这源代码的作者是怎么知道使用哪个算法?莫非是芯片厂商提供的?由于现在对算法一点也不了解,源代码中并没有实现双向认证,而且加密模式似乎也不能正常工作。自己也对这加密和认证过程很迷糊,现在可以说停留原地毫无进展。单向认证是可以,但有bug,有时不知如何操作密码验证失败,可是密码是正确的,密码失败就会导致退出认证模式,此时再发送密码就成功了。还有个很不解的问题,既然每个数据区可以单独设定是否需要认证,那当我认证某个需要认证的数据区后,所有的操作都是进入认证模式,包括当我切换到其它数据区后,依然是处于认证模式(因为认证模式下密码是加密的,虽然本地程序是用变量记录是否进入了认证模式,但发现切换后还是必须加密才能成功解锁)。如果是这样,何必单独设置呢?
太多太多疑惑,可是就是没什么人愿意回答。
现贴上加密算法的相关代码,希望有人了解这种算法,当然我只要知道如何正确使用。
// Generate next value
uchar cm_GPAGen(uchar Datain)
{
uchar Din_gpa;
uchar Ri, Si, Ti;
uchar R_sum, S_sum, T_sum;
// Input Character
Din_gpa = Datain^Gpa_byte; //异或运算
Ri = Din_gpa&0x1f; //Ri[4:0] = Din_gpa[4:0]
Si = ((Din_gpa<<3)&0x78)|((Din_gpa>>5)&0x07); //Si[6:0] = {Din_gpa[3:0], Din_gpa[7:5]}
Ti = (Din_gpa>>3)&0x1f; //Ti[4:0] = Din_gpa[7:3];
//R polynomial
R_sum = cm_Mod(RD, cm_RotR(RG), CM_MOD_R);
RG = RF;
RF = RE;
RE = RD;
RD = RC^Ri;
RC = RB;
RB = RA;
RA = R_sum;
//S ploynomial
S_sum = cm_Mod(SF, cm_RotS(SG), CM_MOD_S);
SG = SF;
SF = SE^Si;
SE = SD;
SD = SC;
SC = SB;
SB = SA;
SA = S_sum;
//T polynomial
T_sum = cm_Mod(TE,TC,CM_MOD_T);
TE = TD;
TD = TC;
TC = TB^Ti;
TB = TA;
TA = T_sum;
// Output Stage
Gpa_byte =(Gpa_byte<<4)&0xF0; // shift gpa_byte left by 4
Gpa_byte |= ((((RA^RE)&0x1F)&(~SA))|(((TA^TD)&0x1F)&SA))&0x0F; // concat 4 prev bits and 4 new bits
return Gpa_byte;
}
// Clock some zeros into the state machine
void cm_GPAGenN(uchar Count)
{
while(Count--) cm_GPAGen(0x00);
}
// Clock some zeros into the state machine, then clock in a byte of data
void cm_GPAGenNF(uchar Count, uchar DataIn)
{
cm_GPAGenN(Count); // First ones are allways zeros
cm_GPAGen(DataIn); // Final one is sometimes different
}
// Include 2 bytes of a command into a polynominal
void cm_GPAcmd2(puchar pucInsBuff)
{
cm_GPAGenNF(5, pucInsBuff[2]);
cm_GPAGenNF(5, pucInsBuff[3]);
}
// Include 3 bytes of a command into a polynominal
void cm_GPAcmd3(puchar pucInsBuff)
{
cm_GPAGenNF(5, pucInsBuff[1]);
cm_GPAcmd2(pucInsBuff);
}
// Include the data in the polynominals and decrypt it required
void cm_GPAdecrypt(uchar ucEncrypt, puchar pucBuffer, uchar ucCount)
{
uchar i;
for (i = 0; i < ucCount; ++i) {
if (ucEncrypt) pucBuffer[i] = pucBuffer[i]^Gpa_byte;
cm_GPAGen(pucBuffer[i]);
cm_GPAGenN(5); // 5 clocks with 0x00 data
}
}
// Include the data in the polynominals and encrypt it required
void cm_GPAencrypt(uchar ucEncrypt, puchar pucBuffer, uchar ucCount)
{
uchar i, ucData;
for (i = 0; i<ucCount; i++) {
cm_GPAGenN(5); // 5 0x00s
ucData = pucBuffer[i];
if (ucEncrypt) pucBuffer[i] = pucBuffer[i]^Gpa_byte;
cm_GPAGen(ucData);
}
}
------解决方案--------------------
我也刚开始做这个,刚拿到代码是一头雾水啊,好像和你是同一份代码,还没开始调呢