encryptionencodingcryptographynodes

how to convert output of a cipher text to numeric digits?


how do we convert the output of say a rsa algorithm, i.e, cipher text to numbers.

cipher text :nq0V69S5fIactNrm0BvG3gI9u2uIU9VjPHVDiy45/XKjKI7UAypjptmyI0OZQXWsEEvfaEPCJrGbPyPKpz7JSQ==

to convert the above cipher text to say 20 digit number


Solution

  • That number is certainly larger than 20 digits, as squamish already has shown in the comments.

    The RSA algorithm is of course producing a number itself as the main operation is modular exponentiation (i.e. ct = m'^e where m' is the padded message).

    However, the RSA PKCS#1 specification requires to perform an operation called Integer to Octet String Primitive, or I2OSP for short. This converts the integer to an unsigned, fixed size, big endian encoding. An octet string is the same thing as a byte array. The size is the same as the modulus / key size when encoded in a minimum of bytes.

    Your byte array is base 64 encoded, so you first need to decode it and then convert it to the integer. In Java, which uses BigEndian encoding by default, it's just a question of doing new BigInteger(1, Base64.decode(encodedCiphertext)), where the 1 makes sure it is interpreted as a positive number (the value of the sign bit).


    Neat little trick: to calculate the number of decimal digits, just divide the number of bits by 10 and then multiply by 3 (and a bit). So 512 bits gives you about 154 decimal digits maximum. Which just doesn't fit a 20 digit number.


    To create a number over the result you first need to concentrate the randomness of the binary result and then extract a number from it.

    This can be performed by:

    1. calculating a secure hash over the result;
    2. interpreting the secure hash as a large, positive number;
    3. reducing the number to a number modulus the maximum value, plus one.

    To make sure that the binary result is relatively well distributed it would be a good idea to make sure that the number resulting from the hash is rather larger than the maximum value.