Interesting puzzle
The solution is to write the problem as a matrix vector multiplication and invert the matrix using integer modulo arithmetic. The key is then given by multiplying with the inverse matrix with modulo.
For the first problem of key length 5 and modulo 31 the inverse matrix is
{
{25, 25, 25, 25, 25},
{25, 28, 14, 7, 19},
{25, 14, 19, 28, 7},
{25, 7, 28, 19, 14},
{25, 19, 7, 14, 28}
}
For the problem of key length 7 and modulo 127 the inverse is:
{
{109, 109, 109, 109, 109, 109, 109},
{109, 118, 59, 93, 110, 55, 91},
{109, 59, 110, 91, 118, 93, 55},
{109, 93, 91, 59, 55, 118, 110},
{109, 110, 118, 55, 59, 91, 93},
{109, 55, 93, 118, 91, 110, 59},
{109, 91, 55, 110, 93, 59, 118}
}
i<3Code