I was trying to create JWT ("JOT") token for make my api call authentic. When ever I try creating token with RSA512 signature, I get back an error saying
java.lang.IllegalArgumentException: RSA signatures must be computed using an RSA PrivateKey. The specified key of type javax.crypto.spec.SecretKeySpec is not an RSA PrivateKey.
I am using below code:
SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.RS512;
long nowMillis = System.currentTimeMillis();
Date now = new Date(nowMillis);
byte[] apiKeySecretBytes = DatatypeConverter.parseBase64Binary(SECRET_KEY);
Key signingKey = new SecretKeySpec(apiKeySecretBytes,
signatureAlgorithm.getJcaName());
JwtBuilder builder = Jwts.builder().claim("uuid",
id).setIssuedAt(now).setExpiration(new Date(600000))
.signWith(signatureAlgorithm, signingKey);
Note : My "SECRET_KEY" is a string which is a private key generated randomly online .
my questionis how can I get a Key object from a string encoded with RSA key size as 4096.
4096 since I am using RSA512 encryption, it is recommended to use 4096 key for RSA512
Initially I was not providing an Base64 encoded RSAkey where I was encoding it again to base64 , reason why I was getting this error.
java.lang.IllegalArgumentException: RSA signatures must be computed using an RSA PrivateKey. The specified key of type javax.crypto.spec.SecretKeySpec is not an RSA PrivateKey.
I was getting back below error when ever I provide and RSAKey base 64 encoded or an byte code private key
Base64-encoded key bytes may only be specified for HMAC signatures. If using RSA or Elliptic Curve, use the signWith(SignatureAlgorithm, Key) method instead.
When ever I am providing a string /byte of private key, it is checking for HMAC algorithm all the time. see below code from JWTBuilder.
#Override
public JwtBuilder signWith(SignatureAlgorithm alg, byte[] secretKey) {
Assert.notNull(alg, "SignatureAlgorithm cannot be null.");
Assert.notEmpty(secretKey, "secret key byte array cannot be null or empty.");
Assert.isTrue(alg.isHmac(), "Key bytes may only be specified for HMAC signatures. If using RSA or Elliptic Curve, use the signWith(SignatureAlgorithm, Key) method instead.");
this.algorithm = alg;
this.keyBytes = secretKey;
return this;
}
#Override
public JwtBuilder signWith(SignatureAlgorithm alg, String base64EncodedSecretKey) {
Assert.hasText(base64EncodedSecretKey, "base64-encoded secret key cannot be null or empty.");
Assert.isTrue(alg.isHmac(), "Base64-encoded key bytes may only be specified for HMAC signatures. If using RSA or Elliptic Curve, use the signWith(SignatureAlgorithm, Key) method instead.");
byte[] bytes = TextCodec.BASE64.decode(base64EncodedSecretKey);
return signWith(alg, bytes);
}
#Override
public JwtBuilder signWith(SignatureAlgorithm alg, Key key) {
Assert.notNull(alg, "SignatureAlgorithm cannot be null.");
Assert.notNull(key, "Key argument cannot be null.");
this.algorithm = alg;
this.key = key;
return this;
}
Its always best Idea to provide an private Key of type java.security.key and must be a RSA key . I used P12 certificate to load private key.
Related
The given public key to me is in this string format
string publicKey =
"MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAlUCQZso6P43gKqw0CfTlwYb3N+m4v6IME 4nPA3WXe52wFpDM/JCFWSdXa7BewlwzDYjblgwL4u59CPxNTPTh7LTD4xXOaGDJHjX5+YgqK4fb9rs ImjMpIACrND/LAdrq5mctWWzw3UtW3F+o+sNwIZM8n65ysS+Vhq9IypFlfuQbWrKjAcWZ3u1iLtplz yf/pjhOEyyZiBUnh6D219+pMiE9nhCpc4xkH1gnlGszIDBqZMMULtGJvFXydA1vv5HxxCYJ2ydEzmA KYxVgA9BGXPEGE89dQbeJsieTj+FSsp9oTm+4vi345opRvH8DWhmZc4OPSwBEL8pwgS7cUnKPtwIDA QAB";
One line in the sample code in java that the public key needs to be converted to RSA Public key.
Does the lines below converts a string public key to RSAPublicKey? Is there a counterpart in C#?
byte[] decoedPublicKey = Base64.getDecoder().decode(publicKey);
RSAPublicKey rsaPublicKey = (RSAPublicKey) KeyFactory.getInstance("RSA").
generatePublic(new X509EncodedKeySpec(decoedPublicKey));
I am trying to send an RSA encrypted message to an external API and always the api returns an error that it could not decrypt the message. I am not doing this step in my c# app, is this required in correct RSA encryption of the public key. Below is a snippet of my RSA encryption. Is it correct?
Pkcs1Encoding pkcs1Encoding = new Pkcs1Encoding((IAsymmetricBlockCipher)new RsaEngine());
using (StringReader reader = new StringReader(publicKey))
{
AsymmetricKeyParameter parameters = (AsymmetricKeyParameter)new PemReader((TextReader)reader).ReadObject();
pkcs1Encoding.Init(true, (ICipherParameters)parameters);
}
return Convert.ToBase64String(pkcs1Encoding.ProcessBlock(bytes, 0, bytes.Length));
I am trying to implement Diffie-Hellman key exchange to generate the symmetric key for encryption/decryption using JAVA cryptography packages. This requires a public key exchange between the two parties.
The public key shared by the client is 1024 bit hexadecimal string, which should be used to calculate the shared secret key. How to convert this string into an encoded key format (ASN.1 SubjectPublicKeyInfo structure) to create a PublicKey object.
Considering a sample public key string. Parameters p and g are fed into inputDHParameterSpec object.
Sample implementation:
AutoGen keypair:
KeyPairGenerator clientKpairGen = keyPairGenerator.getInstance("DiffieHellman");
clientKpairGen.initialize(inputDHParameterSpec);
KeyPair clientKpair = clientKpairGen.generateKeyPair();
byte[] clientPubKeyEnc = clientKpair.getPublic().getEncoded();
X509EncodedKeySpec testPubKeySpec = new X509EncodedKeySpec(clientPubKeyEnc);
KeyFactory keyFactory = KeyFactory.getInstance("DiffieHellman");
PublicKey clientPubKey = keyFactory.generatePublic(testPubKeySpec);
Hex PublicKey - failing:
String testPublicKey = "85f04dd00345642ad12b65bd1a7c38728bff0b8e281ddb6ac4f2739e82a02145daabf23d173c933913b1f844059710e9125591569de427eae1d269accbfa3305069deb7622d1da3ad9820d11bd24fdcce5381d2df99bda314394738dfcbe210eae247b1303e79297ff746cd919e189f6a5776e6ecc24c8900de0f38f159072de";
X509EncodedKeySpec testPubKeySpec = new X509EncodedKeySpec(hexStringToByteArray(testPublicKey));
KeyFactory keyFactory = KeyFactory.getInstance("DiffieHellman");
PublicKey clientPubKey = keyFactory.generatePublic(testPubKeySpec);//Failing here
byte[] created in first code block has public key in ASN.1 encoded format, but hexStringToByteArray(testPublicKey) merely converts the hex to byte[]. Getting the below error on the marked line, due to this.
Exception in thread "main" java.security.spec.InvalidKeySpecException: Inappropriate key specification
at com.sun.crypto.provider.DHKeyFactory.engineGeneratePublic(DHKeyFactory.java:85)
at java.security.KeyFactory.generatePublic(KeyFactory.java:334)
at MWK_DHGen.main(MWK_DHGen.java:87)
Caused by: java.security.InvalidKeyException: Error parsing key encoding
at com.sun.crypto.provider.DHPublicKey.<init>(DHPublicKey.java:178)
at com.sun.crypto.provider.DHKeyFactory.engineGeneratePublic(DHKeyFactory.java:78)
... 2 more
Can someone help on how to convert this hex to the requried format here? A different implementation that would use this hex string to arrive at the secret key is also encouraged.
If you already have the domain parameters (p, g) and just the integer value of the public key then a DHPublicKeySpec rather than an X509EncodedKeySpec is the way to go:
String testPublicKey = "85f04dd00345642ad12b65bd1a7c38728bff0b8e281ddb6ac4f2739e82a02145daabf23d173c933913b1f844059710e9125591569de427eae1d269accbfa3305069deb7622d1da3ad9820d11bd24fdcce5381d2df99bda314394738dfcbe210eae247b1303e79297ff746cd919e189f6a5776e6ecc24c8900de0f38f159072de";
BigInteger publicKeyInteger = new BigInteger(testPublicKey, 16);
KeyFactory keyFactory = KeyFactory.getInstance("DiffieHellman");
PublicKey clientPubKey = keyFactory.generatePublic(new DHPublicKeySpec(publicKeyInteger, g, p));
I have RSA public and private key in two different files.
This is what I've done so far.
public SecretKey getAESkey() throws Exception, NoSuchAlgorithmException{
KeyGenerator generator = KeyGenerator.getInstance("AES");
generator.init(128);
SecretKey sKey = generator.generateKey();
return sKey; // will be passed to encryptSecretKey method
}
public byte[] encryptSecretKey (SecretKey sKey)
{
Cipher cipher = null;
byte[] key = null;
try
{
// initialize the cipher with the user's public key
cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
cipher.init(Cipher.ENCRYPT_MODE, keyHolder.keyPair.getPublic() );
key = cipher.doFinal(sKey.getEncoded());
}
catch(Exception e )
{
e.printStackTrace();
}
return key;
}
I have been doing it wrong. I made an object(keyHolder) that holds the public and private key. And I am trying to have access to its public key by calling getPublic() method. But instead, I'd like to access my public key file directly and read its byte stream to encrypt my AES key. How do I do that?
To save the RSA public key you can simply call PublicKey.getEncoded() which returns a byte array.
To retrieve the RSA public key you would use an instance of a KeyFactory of type "RSA" and generate the public key using an X509EncodedKeySpec that accepts the same byte array.
The rest is just normal off-the-mill binary file I/O.
The key will be saved in a DER encoded SubjectPublicKeyInfo structure as used in X509 certificate structures (hence the name of the X509EncodedKeySpec). The PKCS#1 compatible RSA public key is embedded within that structure. The additional information is used to indicate the specific key type.
You can use openssl asn1parse -inform DER -in <publickey.der> to view the contents of the file.
I'm working on a client-server secure protocol where I need to use RSA in Java to encrypt a SecretKey for HMAC digests because the key has to be sent to the server. The encryption has two stages; first, I need to encrypt the symmetric key with a public asymmetric key, then, that encrypted message is encrypted with a private asymmetric key.
For this purpose I generate the SecretKey as:
public SecretKey generate(){
KeyGenerator generator = KeyGenerator.getInstance("HMACSHA256");
k = generator.generateKey();
return k;
}
Later, I use this code to encrypt any byte array with a public key:
public byte[] encryptPublic(PublicKey key, byte[] array){
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.ENCRYPT_MODE, key);
byte[] encrypted = cipher.doFinal(array);
return encrypted;
}
The code for encryption with a private key is the same but using a private key.
For the RSA encryption I'm using 1024 bit long asymmetric keys so I have two main questions:
How can I turn my SecretKey to a byte array in order to encrypt it with RSA and a public key?
As the public key encryption produces a byte array with 128 bytes, how can I encrypt that message again with a private key if the key is 1024 bits long and can only encrypt a 117 byte long message?
How can I turn my SecretKey to a byte array in order to encrypt it with RSA and a public key?
That's called wrapping:
public static byte[] wrapKey(PublicKey pubKey, SecretKey symKey)
throws InvalidKeyException, IllegalBlockSizeException {
try {
final Cipher cipher = Cipher
.getInstance("RSA/ECB/OAEPWithSHA1AndMGF1Padding");
cipher.init(Cipher.WRAP_MODE, pubKey);
final byte[] wrapped = cipher.wrap(symKey);
return wrapped;
} catch (NoSuchAlgorithmException | NoSuchPaddingException e) {
throw new IllegalStateException(
"Java runtime does not support RSA/ECB/OAEPWithSHA1AndMGF1Padding",
e);
}
}
Note that this explicitly doesn't convert to byte[] first. That's because the key might well be within e.g. a hardware security module. In a HSM the wrapping may be possible, but the conversion to byte[] in local memory would usually not be possible.
As the public key encryption produces a byte array with 128 bytes, how can I encrypt that message again with a private key if the key is 1024 bits long and can only encrypt a 117 byte long message?
You shouldn't do this and you cannot do this either. The reason that you shouldn't do it because encryption with the private key does not provide confidentiality, as anybody would have access to the public key.
Padding is required to perform secure RSA encryption. The padding overhead (of 11 bytes for PKCS#1 v1.5 style padding) is there prohibiting you to encrypt with the private key.
Note that the entire operation: encryption with a private key isn't even specified in PKCS#1 - it's not a legit operation.
Usually the much more secure ephemeral-ephemeral (EC)DH is used to establish keys in transport protocols, using the private key(s) only for authentication. You may want to take a hint from the (draft versions of) TLS 1.3. Or you may just want to use TLS or the handshake portion of it.
Encryption and Decryption successful when encrypt with public key and decrypt with private key :
C# encryption with public key(Successful)
public string EncryptData(string data) {
RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
rsa.FromXmlString(xml); //public key
var cipher = rsa.Encrypt(Encoding.UTF8.GetBytes(data), false);
return Convert.ToBase64String(cipher );
}
Java decryption with private key(Successful)
public static void decrypt() throws Exception{
byte[] modulusBytes = Base64.getDecoder().decode(mod);
byte[] dByte = Base64.getDecoder().decode(d);
BigInteger modulus = new BigInteger(1, (modulusBytes));
BigInteger exponent = new BigInteger(1, (dByte));
RSAPrivateKeySpec rsaPrivKey = new RSAPrivateKeySpec(modulus, exponent);
KeyFactory fact = KeyFactory.getInstance("RSA");
PrivateKey privKey = fact.generatePrivate(rsaPrivKey);
Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
cipher.init(Cipher.DECRYPT_MODE, privKey);
byte[] cipherData = Base64.getDecoder().decode(cipherByte);
byte[] plainBytes = cipher.doFinal(cipherData);
System.out.println(new String(plainBytes));
}
Problem is Here
When c# encrypt with private key and java decrypt with public key bad padding error occur:
C# encryption with private key(Fail)
public stringEncryptData(string data) {
RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
rsa.FromXmlString(xml); //private key
var cypher = rsa.Encrypt(Encoding.UTF8.GetBytes(data), false);
return Convert.ToBase64String(cypher);
}
java decryption with public key (Fail)
public static void decryptPublic() throws Exception{
byte[] modulusBytes = Base64.getDecoder().decode(mod);
byte[] expBytes = Base64.getDecoder().decode(exp);
BigInteger modulus = new BigInteger(1, (modulusBytes));
BigInteger exponent = new BigInteger(1, (expBytes));
RSAPublicKeySpec pubKey = new RSAPublicKeySpec(modulus, exponent);
KeyFactory fact = KeyFactory.getInstance("RSA");
PublicKey publicKey = fact.generatePublic(pubKey);
Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
cipher.init(Cipher.DECRYPT_MODE, publicKey );
byte[] cipherData = Base64.getDecoder().decode(cipherByte);
byte[] plainBytes = cipher.doFinal(cipherData);
System.out.println(new String(plainBytes));
}
I understand public key should use to do encryption and private key for decryption.But in my situation, i need to sent out public key to mutiple clients for decryption on a text encrypted by its private key. Text should be non readable by others except client.
Can anyone see what problem on my code, or suggest a better solution to my problem.
RSA encryption is only secure if a (secure) padding scheme is being used. RSA encryption schemes have been specified in PKCS#1 standards by RSA laboratories (now part of EMC2). These have been copied into RFC, such as RFC 3447: Public-Key Cryptography Standards (PKCS) #1: RSA Cryptography Specifications Version 2.1.
For the purposes of this document, an encryption scheme consists of
an encryption operation and a decryption operation, where the
encryption operation produces a ciphertext from a message with a
recipient's RSA public key, and the decryption operation recovers the
message from the ciphertext with the recipient's corresponding RSA
private key.
So encryption with a private key is an undefined operation.
So what to do now:
securely distribute private keys instead of public keys
generate key pairs and securely transport the public key to the sender
if you require authentication/integrity instead of confidentiality, use signature generation instead of encryption
And, whatever you do, read into Public Key Infrastructure (PKI). It's a far stretching subject that you need to understand before you can apply it.
Encrypting with the private key/decrypting with the public key is a legitimate operation in RSA, however it is not used to protect data, it is instead used to authenticate the source of the data and its integrity. In this context the encryption operation is more usually called "signing".
Encrypting using the private key to protect data as you describe is insecure and so the fact that it is not easily done is likely intentional and intended to prevent incorrect use of the algorithm.
Distributing your private key to clients as suggested in the comments is also unwise since you have no control over who they may pass the key onto (accidentally or otherwise).
If you wish to encrypt data so that it can be decrypted by multiple distinct parties, then you should have each of them provide you with their own public key, and use that to encrypt the data separately for each client.