Reputation: 1760
All I want to do is use a public key to encrypt a token so that it can be decrypted on the other end using the private key.
I used the following command to create a keypair, but now I'm unsure of how to load the public key in my code in order to encrypt the token:
$ ssh-keygen -t rsa -b 4096
What java libraries do I use to load the key and use it to encrypt a String? Along with a code example, I'd also be interested in any reading materials for greater understanding and clarity.
Upvotes: 0
Views: 911
Reputation: 13710
I found a good example in Java (and many other languages) of encrypting a SSO token in the uservoice/developer docs. I pasted the Java code on Pastebin (hope uservoice does not mind!) as it is a little too long to paste here.
I suggest using jose4j if your token is a JWT and you don't actually want to encrypt it, but just sign it!
Tokens don't really need to be encrypted in certain architectures as they only reveal non-sensitive information for the most part (what you can access, when, for how long)... security lies not in making it hard to read the token, but in making it very hard to get access to the token in the first place! Once an attacker gets access to a token, there's not much you can do as the attacker is more interested in using the token (which he/she can do unless there's further protection regarding the access device for example) to impersonate someone than in reading whatever the token contains (which may be nothing, as we'll see).
JWTs can be easily read by anyone as they are just URL-encoded to make transport easy... but they do need to be signed to be trusted as they are often not even saved in the authorization server (they don't need to as only the server can have signed it if the signature is valid)... and protected at the transport layer by only using HTTPS connections to send it, of course.
To load a RSA public/private key in pure Java, see the answer to this question.
To sign and check a JWT's signature, check this page in the jose4j wiki.
If you want your token to stay completely secret, then use an opaque token which doesn't contain any information at all by itself, but points to the actual information the token is supposed to represent, which only the server which generates it can access, so your information is never even exposed directly... opaque tokens are normally just a long UUID.
If you are interested in knowing more about tokens and authorization/authentication, I recommend having a look at the Nordic APIs blog, which contains a lot of articles and links to great open source resources you can use.
Disclaimer: I work for a company that sponsors Nordic APIs.
Upvotes: 2