net.leanix.dropkit.oauth.token.KeyReaderRSA Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of leanix-dropkit Show documentation
Show all versions of leanix-dropkit Show documentation
Base functionality for leanIX dropwizard-based services
package net.leanix.dropkit.oauth.token;
import org.apache.commons.io.IOUtils;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.security.GeneralSecurityException;
import java.security.KeyFactory;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
/**
* Reads RSA keys from file system location, keys must be in DER format. E.g. generate with
* openssl genrsa -out leanix.pem 2048
* openssl pkcs8 -topk8 -inform PEM -outform DER -in leanix.pem -out leanix_private.der -nocrypt
* openssl rsa -in leanix.pem -pubout > leanix.pub
* openssl rsa -in leanix.pem -pubout -outform DER -out leanix_public.der
*/
public class KeyReaderRSA {
public static PrivateKey getPrivateKey(String filename) throws IOException, GeneralSecurityException {
return getPrivateKey(new FileInputStream(new File(filename)));
}
public static PrivateKey getPrivateKey(InputStream stream) throws IOException, GeneralSecurityException {
byte[] keyBytes = IOUtils.toByteArray(stream);
PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(keyBytes);
KeyFactory kf = KeyFactory.getInstance("RSA");
return kf.generatePrivate(spec);
}
public static PublicKey getPublicKey(String filename) throws IOException, GeneralSecurityException {
return getPublicKey(new FileInputStream(new File(filename)));
}
public static PublicKey getPublicKey(InputStream stream) throws IOException, GeneralSecurityException {
byte[] keyBytes = IOUtils.toByteArray(stream);
X509EncodedKeySpec spec = new X509EncodedKeySpec(keyBytes);
KeyFactory kf = KeyFactory.getInstance("RSA");
return kf.generatePublic(spec);
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy