Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Return Token with Private/Public keys  RSS feed

Shariq Roomi
Ranch Hand
Posts: 31
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I am writing a login method that will authencticate user and return token for web services. Next time user will send us token and we will validate the token but requirement is that we donot want to keep any state of token at server.What does it mean that when we receive token, we should be able to determine it is a valid token or not.(This implied token can't be forged by any user).

I have written a function using KeyPairGenerator, please have a look and let me know if you see any security issue.

Design is

token generateToken(userid) {
hash = hash(userid) ------------------- ONE
Signature = Encrypt (Private key , hash) --------------- TWO
return hash + " " + Signature

bool isValid(token) {
separate part 1 and part 2 of toekn (delimeter is space)
Signature = Encrypt (Public key , part1)
if signature == part2
token is valid
token is invalid

Code is

PublicKey privateKey ;
PrivateKey publicKey ;
KeyPairGenerator keyGen;
SecureRandom random ;
KeyPair keypair;

public String generateToken() throws Exception{

keyGen = KeyPairGenerator.getInstance("DSA");
random = SecureRandom.getInstance("SHA1PRNG", "SUN");
keyGen.initialize(512 , random);
keypair = keyGen.genKeyPair();
privateKey = keypair.getPrivate();
publicKey = keypair.getPublic();

String token = userName;
byte[] part1 = getHash(1000, token , generateSalt());

/* Create a Signature object and initialize it with the private key */
Signature dsa = Signature.getInstance("SHA1withDSA", "SUN");

/* Update and sign the data */
dsa.update(part1, 0 , part1.length) ;

/* Generate a signature for it */
byte[] realSig = dsa.sign();

String tokenToReturn = byteToBase64(part1) + " " + byteToBase64(realSig) ;

return tokenToReturn;


public void verifyToken(String token) throws Exception{

int space = token.indexOf(" ");
String part1 = token.substring(0 , space);
String part2 = token.substring(space+1);

/* create a Signature object and initialize it with the public key */
Signature sig = Signature.getInstance("SHA1withDSA", "SUN");

byte[] bPart1 = base64ToByte(part1);
byte[] bPart2 = base64ToByte(part2);

/* Update and sign the data */
sig.update(bPart1, 0 , bPart1.length) ;

if ( sig.verify(bPart2) )
System.out.println("signature verifies: " );
System.out.println("signature does not verifies: " );

Does this code look right ??? Please let me know if you see any pitfalls or know better way to create token
Don't get me started about those stupid light bulbs.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!