JWT implementation in Java using .pem file - java

Would like to know if JWT implementation (generating token) in Java is only possible only via .jks file in keystore of we can do it using a .pem (certificate and key) file as well ?
I would like to store the .jks file in a secured location offered by the PaaS provider on which my application is running and this service does not allow a physical file to be stored but rather the encoded format of the binary contents can be stored in key value pair which we have to refer by decoding. However when i do so , I get a Invalid keystore error.Hence i would like to know if .jks is a mandate for JWT token generation ?

As per your requirement, you don't want to use the Keystore & instead of that you directly wants to read the private & public keys (or public certificate), you can easily achieve it by the following. I've added the apache codec library dependency import org.apache.commons.codec.binary.Base64; for the Base64 decoding purpose.
public static RSAPrivateKey readPrivateKey(File file) throws Exception {
String key = new String(Files.readAllBytes(file.toPath()), Charset.defaultCharset());
String privateKeyPEM = key.replace("-----BEGIN PRIVATE KEY-----", "")
.replaceAll(System.lineSeparator(), "").replace("-----END PRIVATE KEY-----", "");
byte[] encoded = Base64.decodeBase64(privateKeyPEM);
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(encoded);
return (RSAPrivateKey) keyFactory.generatePrivate(keySpec);
}
// to call above code
// private.key in PEM format
File file = new File("private.key");
PrivateKey key = readPrivateKey(file);
Similar things can be done for reading the public key and public certificate as per the requirement.

Related

The signing key's algorithm 'SHA256withECDSA' does not equal a valid HmacSHA* algorithm name and cannot be used with HS512

Now I am using this code to generate an JWT token(I am using jjwt lib), this is my mini example of code:
package com.dolphin.soa.post;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
/**
* #author dolphin
*/
public class MiniExample {
public static void main(String[] args) {
Map<String,Object> jwtHeader = new HashMap<>();
jwtHeader.put("alg","ES256");
jwtHeader.put("kid","YDKL424AF9");
jwtHeader.put("typ","JWT");
Map<String,Object> appleJwtPayload = new HashMap<>();
appleJwtPayload.put("iss","5fb8e836-27d7-4390-8f40-008acd64a29d");
appleJwtPayload.put("iat",System.currentTimeMillis() / 1000L);
appleJwtPayload.put("exp",System.currentTimeMillis() / 1000L + 60 * 15);
appleJwtPayload.put("aud","appstoreconnect-v1");
appleJwtPayload.put("nonce",UUID.randomUUID().toString());
appleJwtPayload.put("bid","com.earth.dolphin");
String appleKey = "-----BEGIN EC PRIVATE KEY-----\n" +
"MHcCAQEEIDxLR4/hZpkIor0r2OlxhG2cVPOjD63jUPFaiRzGomvgoAoGCCqGSM49\n" +
"AwEHoUQDQgAE4B1UkwnabK3TqzeIakdWD3EVdA+IQUlsQFGP/fkLjrbyDxtADpi0\n" +
"JuGLvtKnw/vGEkyAnXethxpebzDCcfdWGQ==\n" +
"-----END EC PRIVATE KEY-----";
SecretKey secretKey = new SecretKeySpec(appleKey.getBytes(), SignatureAlgorithm.ES256.getJcaName());
String accessToken = Jwts.builder()
.setClaims(appleJwtPayload)
.setHeader(jwtHeader)
.signWith(secretKey)
.compact();
System.out.println("Access Token:" + accessToken);
}
}
but when I run this code in the server side, shows this error:
Connected to the target VM, address: '127.0.0.1:57457', transport: 'socket'
Exception in thread "main" io.jsonwebtoken.security.InvalidKeyException: The signing key's algorithm 'SHA256withECDSA' does not equal a valid HmacSHA* algorithm name and cannot be used with HS512.
at io.jsonwebtoken.SignatureAlgorithm.assertValid(SignatureAlgorithm.java:373)
at io.jsonwebtoken.SignatureAlgorithm.assertValidSigningKey(SignatureAlgorithm.java:315)
at io.jsonwebtoken.impl.DefaultJwtBuilder.signWith(DefaultJwtBuilder.java:122)
at io.jsonwebtoken.impl.DefaultJwtBuilder.signWith(DefaultJwtBuilder.java:115)
at com.dolphin.soa.post.MiniExample.main(MiniExample.java:39)
Disconnected from the target VM, address: '127.0.0.1:57457', transport: 'socket'
Process finished with exit code 1
where is going wrong and what should I do to make it work? I have tried to convert the apple p8 file to generate the private key?
openssl ec -in AuthKey_Y24AF9.p8 -out au_private.p8
still not fix this problem. I have struggled in the problem for a while and searching from internet but still no clue.
TLDR: private key and secret key are different
There are two radically different kinds of digital cryptography used in the last half-century: traditional or symmetric, also called conventional, and public-key or asymmetric. In Java crypto, and thus in jjwt, the SecretKey[Spec] classes and their subclasses are used only for symmetric algorithms, including HMAC, and the PrivateKey[Spec] classes and their subclasses are used only for asymmetric algorithms, including ECDSA. See https://github.com/jwtk/jjwt#signing-key -- you must use a SecretKey of suitable size for HSnnn but a PrivateKey of both the correct algorithm (RSA or EC) and suitable size for RSnnn PSnnn or ESnnn. Because you gave jjwt a SecretKeySpec it tries to use the only signing algorithm it knows that is usable with a secret key, namely HMAC, but the type you specified is invalid for a secret key and thus for HMAC.
And your key is not PKCS8.
Your private key is in the OpenSSL-specific 'traditional' or 'legacy' format, which is the one first defined by SECG in SEC1 and later officialized (if that's a word) by RFC5915. Java crypto does not directly support the (several) OpenSSL traditional formats, only the industry-standard PKCS8 format published as RFC5208 and updated under a new name as RFC5958.
You say your filename has extension .p8 which suggests someone thinks it is, or should be, PKCS8, but in fact it's not. The command you asked about, openssl ec, will not convert to PKCS8, in fact the reverse: if you give it a PKCS8 format input it will produce traditional format output, exactly what you don't want. If you are able to fix the key before using it, there are two choices:
openssl pkey -in trad_pem_file -out pkcs8_pem_file
# only in 1.0.0 up, but that's been 11 years and pretty much everyone has it now
This produces PKCS8 format, but in PEM 'armor' which Java doesn't directly support, so to read it you must: remove the BEGIN and END lines; decode the base64 part to binary (byte[] in Java) ignoring the newlines, which can be done by removing them before decoding or by using j8+ java.util.Base64.getMimeDecoder() which ignores them; and finally put the result through a suitable KeyFactory:
PrivateKey key = KeyFactory.getInstance("EC").generatePrivateKey(new PKCS8EncodedKeySpec(decodedbase64));
# note KeyFactory is for asymmetric algorithms (and private and public keys) only
# while SecretKeyFactory is for symmetric algorithms and secret keys,
# but KeyGenerator is for symmetric algorithms and secret keys
# while KeyPairGenerator is for asymmetric algorithsm and private/public keys
# I think this is to keep you on your toes
The other (older) conversion in OpenSSL is:
openssl pkcs8 -topk8 -nocrypt -in trad_pem_file -out pkcs8_file [-outform pem|der]
With default outform 'pem' this is the same as pkey above; with 'der' it does the PEM-decode steps for you and creates a binary file which could be read and used directly by Java:
byte[] p8der = Files.readAllBytes(Paths.of("pkcs8_der_file"));
PrivateKey key = KeyFactory.getInstance("EC").generatePrivate(new PKCS8EncodedKeySpec(p8der));
or you could embed it in your source by various means.
If you can't convert the key to pkcs8 and need your program to handle traditional format, that is possible but more complicated -- and has been asked and answered before, quite a few times. I will dig up some of them later when I have a little more time.
Thanks for dave_thompson_085 patient,I am solving the problem using this code:
public static String generateToken(AppleJwtHeader jwtHeader, AppleJwtPayload jwtPayload ) throws NoSuchAlgorithmException, InvalidKeySpecException, IOException {
byte[] p8der = Files.readAllBytes(Path.of("/opt/apps/dolphin-post/AuthKey_YDKL424AF9.p8"));
PKCS8EncodedKeySpec priPKCS8 = new PKCS8EncodedKeySpec(new org.apache.commons.codec.binary.Base64().decode(p8der));
PrivateKey appleKey = KeyFactory.getInstance("EC").generatePrivate(priPKCS8);
ObjectMapper objectMapper = new ObjectMapper();
Map claims = objectMapper.convertValue(jwtPayload, Map.class);
Map header = objectMapper.convertValue(jwtHeader,Map.class);
String accessToken = Jwts.builder()
.setClaims(claims)
.setHeader(header)
.signWith(appleKey)
.compact();
return accessToken;
}
hopes help for others.

java.security.InvalidKeyException: invalid key format while generating public, private key from PEM file

I have gone through many similar threads but no luck!!
I want to generate public and private keys using a PEM file. Following is the code I am using for the same:
String pemFileNme = "C:\\Users\\amitmm\\Desktop\\clean\\key.pem";
File pubKeyFile = new File(pemFileNme);
File privKeyFile = new File(pemFileNme);
// read public key DER file
DataInputStream dis = new DataInputStream(new
FileInputStream(pubKeyFile));
byte[] pubKeyBytes = new byte[(int)pubKeyFile.length()];
dis.readFully(pubKeyBytes);
dis.close();
// read private key DER file
dis = new DataInputStream(new FileInputStream(privKeyFile));
byte[] privKeyBytes = new byte[(int)privKeyFile.length()];
dis.read(privKeyBytes);
dis.close();
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
// decode public key
X509EncodedKeySpec pubSpec = new X509EncodedKeySpec(pubKeyBytes);
RSAPublicKey pubKey = (RSAPublicKey)
keyFactory.generatePublic(pubSpec);
// decode private key
PKCS8EncodedKeySpec privSpec = new
PKCS8EncodedKeySpec(privKeyBytes);
RSAPrivateKey privKey = (RSAPrivateKey)
keyFactory.generatePrivate(privSpec);
Exception:
Exception in thread "main" java.security.spec.InvalidKeySpecException:
java.security.InvalidKeyException: invalid key format
at
sun.security.rsa.RSAKeyFactory.engineGeneratePublic(RSAKeyFactory.java:205)
at java.security.KeyFactory.generatePublic(KeyFactory.java:334)
at main.java.me.txedo.security.Main2.f1(Main2.java:47)
at main.java.me.txedo.security.Main2.main(Main2.java:20)
Caused by: java.security.InvalidKeyException: invalid key format
at sun.security.x509.X509Key.decode(X509Key.java:387)
PEM File Content:
-----BEGIN RSA PRIVATE KEY-----
MIIEowIBAAKCAQEAwnEEodFEf86+Ae+wYyI//u1kekIWnA3RfzbAwWD77uG7D9Ci
9vVNbPO4XT2hKL03/q7d7KTgrA1sjBltfaOzVfA56x1S/0cYVk4xI440dpLo0F+m
RIqRw5fh8IuUlUIr3I4A7ESkDQQsZbDpdgCiNbrlADqLotcZyB4rU4uURW8QUI/W
eqsD6TOQs4bI+3o3xAKkky2kXujSaaa3tDxgUPTmSQ0Buk7Hx/IVzwyV7qjWiR4U
C46rHpnWxfF0DWuJUOYgJmBQ8xFOQwt4Ec/u+0m8top8cqQF+gpBn9iLXpbtahA3
pqyvLuNXRH9yn8mlEneBrjjl6U0H3W/AV7/dGwIBAwKCAQEAgaCtwTYtqonUAUp1
l2wqqfOYUYFkaAk2VM8rK5X9SevSCosXT04znffQPikWGyjP/x8+ncNAcrOdsrue
U8J3jqAmnL43VNoQOYl2F7Qi+bdF4D/ELbG2gmVBSwe4Y4FykwlV8thtXgLIQ8tG
TqsWznyYqtGybI9mhWlyN7Ji2POMDZP5Lwx7M01pMezwpnsZSmPVL9TgVrtWv4xt
C0vPyuy9THlFWtkOdHItNK+vOTcpuHn29rFUJI/D3R+SQjcdqj3aaqljOtdeBxgd
yDl2/Z4rUyetgzcZMfNTt/NRT0hOJ6R6/2S7gFCTtxMHBh3vVCH+pLLnQyJvcPQu
AsORSwKBgQDhOPr1x/8BioqaasoXvO9NsGktCgPDjbC4d3jR8n6lCa42X/eIahaD
xi1VGWyQhdO7aMXiDmzOtox7xHcMRh+a5ySIs9gTsHkMB2hqwIUNg25INRkQ3Vr3
eWnoTBGsfJqC1TEME3ocKwmyz57ZAe4yyR/ZRdDX5DUt9qCCFeA8uQKBgQDdAzbq
7BlJkbTYfdlIRNJEJAO3wWqQTx8X0ttCMMwDluOT9l+RR/KuUxl85ph+kwJci6E/
ixfeMTW1NcsMY/lB6mTP0oooalU1MP7gpPSu+24zhLXnUHZotbNbv9nk6w/1WWhz
FBt5w2DG4kQPFK6LSySqcVuzIGQyvWD5PbpGcwKBgQCWJfyj2qoBBwcRnIa6ffTe
dZtzXAKCXnXQT6XhTFRuBnQkP/pa8WRX2XOOEPMLA+J88IPsCZ3fJF2n2E9dhBUR
722wd+VidaYIBPBHKwNeV57azhC16OdPpkaa3WEdqGcB43YIDPwSx1vMimnmAUl3
ML/mLos6mCNz+cBWuUAoewKBgQCTV3nx8ruGYSM6/pDa2IwtbVfP1kcK32oP4eeB
dd1Xue0NTupg2qHJjLuombr/DKw9smt/sg/pdiPOI9yy7VDWnEM1NwbFnDjOIKnr
GKMfUkl3rc6aNaRFzneSf+aYnLVOO5r3Yrz715XZ7C1fYx8Hh23G9j0iFZgh05X7
fnwu9wKBgHyC0X26KZQ0ukan5jDSiz4dapUp2d3F+vnRzZa2AOsmo995gsXLdfsJ
n0o4Z3LsQJUDRI3tQ4dXe/5jS4oFrOdxALOAw6YmvEv/3oHwsCYPDhqLNfIJ9I6m
Dt3yG61pUJiCArhPaYG17NQoCxF6Xi6GUajRsECbr8DdyGMAu5eE
-----END RSA PRIVATE KEY-----
I have tried removing file header and footer manually. I tried code from bouncycastle, no luck, same error.
Python code which works with this file:
def t2e_enc(plaintext, pk_pem_file = './2017-12-04T062008Z.pem'):
'''
Function for encryption of Track2 credit card data.
This function uses private key to derivate public part used for encryption
'''
with open(pk_pem_file, 'rb') as pk:
private_key = serialization.load_pem_private_key(pk.read(),
password=None, backend=default_backend())
public_key = serialization.load_pem_public_key(
private_key.public_key().public_bytes(
serialization.Encoding.PEM,
serialization.PublicFormat.SubjectPublicKeyInfo),
backend=default_backend()
)
ciphertext = public_key.encrypt(
plaintext,
padding.OAEP(
mgf=padding.MGF1(algorithm=hashes.SHA1()),
algorithm=hashes.SHA1(),
label=None
)
)
b64ciphertext=base64.b64encode(ciphertext)
return b64ciphertext
I am doing this for the first time, so bear with me if there is any silly mistake.
Partial dupe Load RSA public key from file
So, you 'wrote' (I assume, copied) code that clearly says you need two files, in DER form, containing PKCS8 and 'X509' encodings. (What Java calls X.509 here is really the SubjectPublicKeyInfo component of X.509.) You give it one file, in PEM form not DER, containing a PKCS1 encoding not PKCS8 or X509 -- and you're surprised it doesn't work? Python works because it calls OpenSSL, and OpenSSL supports over a dozen encodings and formats for privatekeys, including this one; Java supports only one (outside of keystores) which isn't this one. (Bare) publickeys are a little better; internally libcrypto supports multiple forms, but in practice only two of them are used, and one of them matches Java -- although many publickeys are distributed, stored, and used in the form of X.509 certificates, which provides several more forms to worry about.
There are approximately 7 solutions to your situation:
the simplest is to use OpenSSL commandline to convert your one file to the two files Java wants:
# (corrected! pkey is inconsistent!)
openssl pkcs8 -topk8 -nocrypt -in input.pem -outform der -out private.der
openssl pkey -in input.pem -pubout -outform der -out public.der
# or for very old versions (should not be needed now)
openssl rsa -in input.pem -pubout -outform der -out public.der
Those files can now be read by the code you posted (except with the filenames separated). Note this conversion doesn't have to be done on the same system; if necessary you can do it elsewhere and copy the files, if you use a method that works for binary files i.e. NOT cut&paste.
if you really want only one file, but it can be converted, create the private.der file as above and read it with only the privatekey-related parts of your code, then do:
RSAPrivateCrtKey priv2 = (RSAPrivateCrtKey)privKey;
PublicKey pubkey = keyFactory.generatePublic(new RSAPublicKeySpec(priv2.getModulus(), priv2.getPublicExponent()));
you could convert the files to PKCS8 and 'X509' PEM by omitting -outform der from the above conversions, then read those files and manually 'de-PEM' by removing the header and trailer lines and converting the base64 to binary (removing or skipping the linebreaks); this results in binary PKCS8 and X509 encodings you can run through your existing code. This is as much work on the openssl side and more work on the Java side so there is no apparent advantage, except that PEM files are valid text and can be cut&pasted if necessary.
combining these, you could convert to PKCS8 PEM only, read that per bullet 3 (de-PEM then the privatekey parts of your code), then extract publickey from privatekey per bullet 2
one way to use the format you have (unconverted) in plain Java is to de-PEM per bullet 3 giving you a PKCS1 encoding, then manually construct the PKCS8 encoding, then proceed as before to run the PKCS8 through the KeyFactory and extract publickey per bullet 2. See my answer at Java: Convert DKIM private key from RSA to DER for JavaMail for a really ugly way to do this (including one de-PEM method). There is a better way if you use BouncyCastle (which has a class for this ASN.1 type), but if you use BouncyCastle it's better not to use this method at all, see below.
another way to use the unconverted format in plain Java is to de-PEM per bullet 3, then parse the ASN.1 structure of PKCS1 and construct an RSAPrivateCrtKeySpec which you can run through your KeyFactory instead of a PKCS8 encoding then extract publickey per bullet 2. This is even more complicated, although I think I have seen it somewhere; will add if I find it. Again BouncyCastle can improve this method, but doesn't need to, see below.
finally, if you have BouncyCastle it's dead easy. You don't say what you tried with 'no luck', but the following BouncyCastle code is all you need and does work:
try( Reader r = new FileReader(filename) ){
KeyPair pair = new JcaPEMKeyConverter().getKeyPair((PEMKeyPair)new PEMParser(r).readObject());
}
Note this gives you a KeyPair with both privatekey and publickey objects from the one file.

Generate token with RS256 and Jwts.builder().signWith() produces invalid signature

Using the JWT Java library and producing a token with the RS256 algorithm, I always get an invalid signature with the jwt.io debugger. Here is my example code, I tried to make it as simple as possible to start with my current project:
// Create a legitimate RSA public and private key pair:
KeyPair kp = RsaProvider.generateKeyPair();
PublicKey publicKey = kp.getPublic();
PrivateKey privateKey = kp.getPrivate();
String jwt = Jwts.builder().setSubject("Joe").signWith(SignatureAlgorithm.RS256, privateKey).compact();
This code is inspired from the test class here.
Any idea what I could be missing?
The jwt.io debugger expects that you provide the public key associated with the private key used to sign the token encoded in the Public Key file (PKCS#8) format.
Ensure that you specify it using exactly that format, an example follows:
-----BEGIN PUBLIC KEY-----
BASE64 DATA
-----END PUBLIC KEY-----

JAVA: How to save a private key in a pem file with password protection

I am trying to save a private key in a pem file, protected with a password. The problem is, the pem file is created and I
can even open it with openssl but, no password is asked!
Here is the code:
KeyPairGenerator keygen = KeyPairGenerator.getInstance("RSA");
keygen.initialize(2048);
KeyPair keypair = keygen.generateKeyPair();
PrivateKey privKey = keypair.getPrivate();
PKCS8Generator encryptorBuilder = new PKCS8Generator(privKey);
encryptorBuilder.setPassword("testing".toCharArray());
PEMWriter writer = new PEMWriter(new FileWriter(new File("pk.pem")));
PemObject obj = encryptorBuilder.generate();
writer.writeObject(obj);
writer.flush();
writer.close();
After it executes, I try to open the pk.pem file
openssl rsa -in pk.pem -check
and it gives:
RSA key ok
writing RSA key
-----BEGIN RSA PRIVATE KEY-----
(... some key appears here ...)
-----END RSA PRIVATE KEY-----
It was suppose to ask for the password before giving access to the private key!
Can some one please help me?
Well you should read the BouncyCastle documentation carefully. It states for the constructor you use:
// Constructor for an unencrypted private key PEM object.
PKCS8Generator(java.security.PrivateKey key)
// Constructor for an encrypted private key PEM object.
PKCS8Generator(java.security.PrivateKey key, java.lang.String algorithm, java.lang.String provider)
Hence you are using the constructor for creating an creates an unencrypted PKCS8Generator instance. The password you set as no effect.
Use one of the other constructors instead that create an encrypting instance according to the documentation.
Note: The code in the question requires an outdated version of BouncyCastle (1.4x?), because the current version (1.5x) has different constructors, incompatible with those presented in this answer.
For newer versions use:
import org.bouncycastle.openssl.jcajce.JcaPEMWriter;
JcaPEMWriter writer = new JcaPEMWriter(new PrintWriter(System.out));
writer.writeObject(sk);
writer.close();
possibly replacing the PrintWriter with any other Writer of course.

How can I create a Java KeyStore from an existing set of certificates and keys without using command line tools?

I obtain a randomly generated RSA certificate and private key as strings from another service, and I would like to use those strings to create a Java KeyStore. All of the examples I see involve saving these strings to files, using the openssl and keytool command line tools to create the keystore on disk, and then loading the resulting KeyStore into memory (like here). However, it makes more sense for my purposes to create the KeyStore entirely in memory.
To that end, I am trying to use the Java Security API. I am able to convert the certificate string into an instance of the java.security.cert.Certificate class, but I am unable to convert the private key into an instance of java.security.PrivateKey. Here's method I am trying to create:
private PrivateKey generatePrivateKey (String newKey)
throws NoSuchAlgorithmException,
InvalidKeySpecException, IOException {
//Configuring the KeyFactory to use RSA
KeyFactory kf = KeyFactory.getInstance("RSA");
//Convert the key string to a byte array
byte[] keyBytes = newKey.getBytes();
KeySpec ks = new PKCS8EncodedKeySpec(keyBytes);
PrivateKey key = kf.generatePrivate(ks);
return key;
}
Where the value of newKey is something like "-----BEGIN RSA PRIVATE KEY-----\nMIIEow...gNK3x\n-----END RSA PRIVATE KEY-----".
When I run the code, I receive the following exception:
java.security.spec.InvalidKeySpecException: java.security.InvalidKeyException: invalid key format
at sun.security.rsa.RSAKeyFactory.engineGeneratePrivate(RSAKeyFactory.java:217)
at java.security.KeyFactory.generatePrivate(KeyFactory.java:372)
... 30 more
Caused by: java.security.InvalidKeyException: invalid key format
at sun.security.pkcs.PKCS8Key.decode(PKCS8Key.java:341)
at sun.security.pkcs.PKCS8Key.decode(PKCS8Key.java:367)
at sun.security.rsa.RSAPrivateCrtKeyImpl.<init>(RSAPrivateCrtKeyImpl.java:91)
at sun.security.rsa.RSAPrivateCrtKeyImpl.newKey(RSAPrivateCrtKeyImpl.java:75)
at sun.security.rsa.RSAKeyFactory.generatePrivate(RSAKeyFactory.java:316)
at sun.security.rsa.RSAKeyFactory.engineGeneratePrivate(RSAKeyFactory.java:213)
... 32 more
This particular error is very similar to this stackoverflow question, and I would be grateful if that question were resolved, but I also want to know if my higher level goal (creating a JKS programmatically and solely in memory using Java) is feasible, and if so, whether I am on the right path.
you need to decode base64 if your key is in the base64 representation:
KeySpec ks = new PKCS8EncodedKeySpec(Base64.decodeBase64(newKey));
you can use org.apache.commons.codec.binary.Base64 to do this.
if you want to generate keyPair you can you this code:
KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
keyPairGenerator.initialize(1024);
KeyPair keyPair = keyPairGenerator.genKeyPair();
// extract the encoded private key, this is an unencrypted PKCS#8 private key
byte[] encodedprivkey = keyPair.getPrivate().getEncoded();
System.out.println(Base64.encodeBase64String(encodedprivkey));

Categories

Resources