question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Using private/public key example

See original GitHub issue

Hi, can you please provide an example of how to sign/verify using an existing private/public key pair?

I got it working in node with node-jsonwebtoken, like this:

var key = fs.readFileSync('private.key');
var pem = fs.readFileSync('public.pem');

var header = {...};
var payload = {...};

header.algorithm = "RS256";
var message = jsonwebtoken.sign(payload, key, header);
var decoded = jsonwebtoken.verify(message, pem, {algorithm: "RS256"});

And it works just fine.

I would like to do the same in Java.

Issue Analytics

  • State:open
  • Created 7 years ago
  • Reactions:14
  • Comments:14 (3 by maintainers)

github_iconTop GitHub Comments

23reactions
csmithmtbcommented, Jun 21, 2016

Here’s what I did during testing using a key pair with the library: Create a RSA keypair in a java keystore: keytool -alias jwtkey -keyalg RSA -dname "CN=Server,OU=Unit,O=Organization,L=City,S=State,C=US" -keypass keypassword -keystore server.jks -storepass jkspassword Java code:

public void test() throws Exception {
        ClassPathResource resource = new ClassPathResource("keystore.jks");
        KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType());
        keystore.load(resource.getInputStream(), "jkspassword".toCharArray());

        Key key = keystore.getKey("jwtkey", "keypassword".toCharArray());
        Certificate cert = keystore.getCertificate("jwtkey");
        PublicKey publicKey = cert.getPublicKey();
        Map<String, Object> claims = new HashMap<>();
                claims.put("user", "cope");
        Calendar expires = Calendar.getInstance();
        expires.roll(Calendar.HOUR, 2);
        String s = Jwts.builder()
                .setClaims(claims)
                .setIssuedAt(new Date())
                .setExpiration(expires.getTime())
                .signWith(SignatureAlgorithm.RS256, key)
                .compact();
        System.out.println(s);
        Jwts.parser().setSigningKey(publicKey).require("user", "cope").parse(s);

If you need to get the public key, you can do the following:

keytool -export -keystore server.jks -alias jwtkey -file jwtkey.cer
openssl x509 -inform der -in jwtkey.cer -pubkey -not

The openssl command will output the public key.

Hope this helps.

7reactions
ChristopherSchultzcommented, May 4, 2021

Using an external library (bouncycastle) or another class is not really necessary at all to read a PEM file. It’s like 2 lines of Java code:

import java.security.cert.Certificate;
import java.security.cert.CertificateFactory;
...
// First, get your PEM-encoded DER certificate into a String, like this:
String certChart = "-----BEGIN CERTIFICATE-----\n.....";

// Now parse it using CertificateFactory:
CertificateFactory cf = CertificateFactory.getInstance("X.509");
Certificate cert = cf.generateCertificate(new java.io.ByteArrayInputStream(certChars.getBytes(StandardCharsets.US_ASCII)));

// Now verify:
Jwts.parserBuilder()
    .setSigningKey(cert.getPublicKey())
   ...
Read more comments on GitHub >

github_iconTop Results From Across the Web

Understand Private Key and Public Key with an Example
Example : A encrypts sensitive information using B's public key and sends it across. B can only access that information and decrypt it...
Read more >
Cryptography/A Basic Public Key Example - Wikibooks
The private key pair is used to decrypt messages, and this key will only work if the public key of the same site...
Read more >
What would be the examples of a public key and a private key?
An example of a public key would be “Prime Minister #ScoMO” , followed by the private key “I know what happened at #EngadineMaccas...
Read more >
How to Create a Public/Private Key Pair
In the example, the path is /home/johndoe/.ssh/id_rsa.pub . At this point, you have created a public/private key pair. Copy the public key and...
Read more >
Public-key cryptography - Wikipedia
For example, a journalist can publish the public key of an encryption key pair on a web site so that sources can send...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found