Monday, October 21, 2013

How to convert strings to big integers and vice versa

This is a very simple post on something I found useful in recently.

When creating cryptographic elements, we might need to convert Strings to BigIntegers and vice versa.

A good example is: when you want to hide a secret value using a commitment scheme such as pedersen commitment (I avoid explaining the pedersen commitment here and will leave it for a future post).

Following code demonstrate how you achieve the $subject in java:
import java.math.BigInteger;

public class Test {
    public static void main(String[] args) throws UnsupportedEncodingException {
        String identifier = "secretPW";
        //convert string to big integer
        BigInteger identifierBI = new BigInteger(identifier.getBytes("us-ascii"));
        System.out.println("Identifier: " + identifier + " converted to Big Integer: " + identifierBI);

        //convert the big integer back to identifier and verify
        String verifyIdentifier = new String(identifierBI.toByteArray());
        System.out.println("Big Integer converted back to string val: " + verifyIdentifier);

Note: as in line 8 above, it is good to mention the encoding when converting the string to bytes so that your code will run in the same way even when deployed in different platforms.

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.