// ==========================================================================
// pass.c
// (c) 2020, Aurel Dumitru
//
// Description:
// =========================================================================

#include "pass.h"

void Pass_S1(uint32_t* RootKeyPtr)
{
	uint8_t* RootKey = (uint8_t*)RootKeyPtr;
	uint8_t Seed = 0x2D;
	Seed ^= 0xFF;
    RootKey[0] = Seed;
    Seed -= 0x28;
    RootKey[1] = Seed;
    RootKey[2] = (uint8_t)(((double)Seed)*0.5361);
    RootKey[3] = (uint8_t)(((double)((uint32_t)RootKey[2] + (uint32_t)RootKey[1] + (uint32_t)RootKey[0]))/3.1181);
}


void Pass_S2(uint32_t* RootKeyPtr)
{
	RootKeyPtr[1] = RootKeyPtr[0] ^ 0x1C6794CD;
	RootKeyPtr[2] = RootKeyPtr[1] ^ 0xAA01CC48;
}


void Pass_Gen(char* DevString, uint8_t* Dest, uint8_t* Src, uint32_t Length)
{
	uint32_t RootKey[3];
	uint32_t UcId[3];
    Pass_S1(RootKey);
    Pass_S2(RootKey);

	uint32_t Sum=0, I=0;
    do
    	Sum += (uint8_t)DevString[I++] ^ 0xFF;
    while (DevString[I]);
    while ((Sum&1) == 0)
        Sum >>= 1;

    UcId[0] = HAL_GetUIDw2();
    UcId[1] = HAL_GetUIDw1();
    UcId[2] = HAL_GetUIDw0();

    uint8_t* RootKeyPtr = (uint8_t*)RootKey;

    if (Src == NULL)
        for (I=0; I<8; I++)
        	Dest[I] = RootKeyPtr[(Sum+I)%12]^(*((uint8_t*)UcId+11-I));
    else
        for (I=0; I<Length; I++)
        	Dest[I] = RootKeyPtr[(Sum+I+3)%12]^(*((uint8_t*)UcId+((I+5)%12)))^Src[I];
}
