JWT signature verification - java

I'm trying to validate the access token signature with my public key retrieved from an authentication server (OpenId).
The client get an access token from the same server and then request my Resource server API with it. Now I have to check its signature with the Spring Security library.
The access token has an "alg" : "RS256" attribute.
But the code below remains unsuccessful and I'm always getting the InvalidSignatureException...
import java.math.BigInteger;
import java.security.KeyFactory;
import java.security.PublicKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.RSAPublicKeySpec;
import org.apache.commons.codec.binary.Base64;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.jwt.JwtHelper;
import org.springframework.security.jwt.crypto.sign.InvalidSignatureException;
import org.springframework.security.jwt.crypto.sign.RsaVerifier;
public class JWTValidation {
private static final Logger logger = LoggerFactory.getLogger(JWTValidation.class);
private static final String PUBLIC_KEY_MODULUS = "qOYyKKnoUpXd2qIj8A0tdumWwnDbVjXOVaPfiX5lxBvYEtgWPLknf1Nftdk371a7f1jD8SFFDxXnj-PPFx8qoNETOITvbR12uvWmS1J36B5Uo_ViHp7dC-GaZG_EdafyK0rxRPvK8b37NPXWhTggbxCZhYaqJUMb1t0xogDadEyM95lZweEXrwsJNzoyXiGnPfsRgy32TjOOXIMZnAMoj-osYd2WawymkRV6cteo3f8KMT72_kp8oG-kGm1s3ZooEfI3_9Z2jHVGWQLUWbmZKIrvjuUo2dhmqWWsNyTO3RsF4qyrRCpmZNawDf_GsioBTZ3vfPF_T58moH7cJ50Byw";
private static final String PUBLIC_KEY_PUBLIC_EXPONENT = "AQAB";
//Public key =
// {
// "keys":[
// {
// "kty":"RSA",
// "use":"sig",
// "kid":"DQr-GCc8rH3y5fkAuo0iau-ue-s",
// "x5t":"DQr-GCc8rH3y5fkAuo0iau-ue-s",
// "e":"AQAB",
// "n":"qOYyKKnoUpXd2qIj8A0tdumWwnDbVjXOVaPfiX5lxBvYEtgWPLknf1Nftdk371a7f1jD8SFFDxXnj-PPFx8qoNETOITvbR12uvWmS1J36B5Uo_ViHp7dC-GaZG_EdafyK0rxRPvK8b37NP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j7lSQY6pME2ZXU0YppC6Dctj8XHkTO9Ji9vDj+iGoS4+RvHZ3cDr5YUbOKSooOAZ/kjqtm+VK2jdjdLrkduz/24NKIxEXQqhmM28f8kh5Wc2ilaMya9pxQZpTWk7sjOBkZCcw24tx6UqpSTsV/XnnTmJMIhgXFJXWnXFc="]
// }
// ]
// }
//Access Token = base64url encoded String
public boolean verifySignature(String accessToken){
try {
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
Base64 decoder = new Base64(true);//URL-safe Base64 decoder
BigInteger modulus = new BigInteger(decoder.decode(PUBLIC_KEY_MODULUS.getBytes()));
BigInteger publicExponent = new BigInteger(decoder.decode(PUBLIC_KEY_PUBLIC_EXPONENT.getBytes()));
RSAPublicKeySpec spec = new RSAPublicKeySpec(modulus, publicExponent);
PublicKey newPublicKey = keyFactory.generatePublic(spec);
RsaVerifier verif = new RsaVerifier((RSAPublicKey) newPublicKey, "SHA256withRSA");
JwtHelper.decodeAndVerify(accessToken, verif);
} catch (InvalidSignatureException e){
logger.info(e.getMessage());
return false;
} catch (Exception e){
logger.info(e.getMessage());
return false;
}
return true;
}
}
I also tried to use the online tool jwt.io but I've not been able to make it work (the signature remains invalid)
And for the other one (tool_jwt), the only way to have a valid signature is to choose the "default X.509 certificate RSA" with comments around my public key "x5c" value :
-----BEGIN CERTIFICATE-----
MIIDBDCCAfCgAwIBAgIQt1HpvYkM6oxJ1ZjbpW1fPTAJBgUrDgMCHQUAMBkxFzAVBgNVBAMTDkRhdGFEb29ycyBUZXN0MCAXDTE1MDQwMjIyMjQwM1oYDzIwNTAwMTAxMDYwMDAwWjAZMRcwFQYDVQQDEw5EYXRhRG9vcnMgVGVzdDCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAKjmMiip6FKV3dqiI/ANLXbplsJw21Y1zlWj34l+ZcQb2BLYFjy5J39TX7XZN+9Wu39Yw/EhRQ8V54/jzxcfKqDREziE720ddrr1pktSd+geVKP1Yh6e3QvhmmRvxHWn8itK8UT7yvG9+zT11oU4IG8QmYWGqiVDG9bdMaIA2nRMjPeZWcHhF68LCTc6Ml4hpz37EYMt9k4zjlyDGZwDKI/qLGHdlmsMppEVenLXqN3/CjE+9v5KfKBvpBptbN2aKBHyN//Wdox1RlkC1Fm5mSiK747lKNnYZqllrDckzt0bBeKsq0QqZmTWsA3/xrIqAU2d73zxf0+fJqB+3CedAcsCAwEAAaNOMEwwSgYDVR0BBEMwQYAQgtiIGHLzFEskZSe/65EOTqEbMBkxFzAVBgNVBAMTDkRhdGFEb29ycyBUZXN0ghC3Uem9iQzqjEnVmNulbV89MAkGBSsOAwIdBQADggEBADtIlf41MLeGwjTbhJS88stZEBhEexxXNJDlW92GKPVv0JJWD/5m8tfADzXOgP65rTyQ4lTGOFFRYQu0ajMYAzggqJTmU1rMrHxuVwLfJ3OpSOc9UZBs2gW/IUZFvSugMKNboTsfTPgpsHK1ag68NKvR/V209zYZd6A7zisGgUr2Oc5jNEj7lSQY6pME2ZXU0YppC6Dctj8XHkTO9Ji9vDj+iGoS4+RvHZ3cDr5YUbOKSooOAZ/kjqtm+VK2jdjdLrkduz/24NKIxEXQqhmM28f8kh5Wc2ilaMya9pxQZpTWk7sjOBkZCcw24tx6UqpSTsV/XnnTmJMIhgXFJXWnXFc=
-----END CERTIFICATE-----
So I don't know what to do now, which public key attribute should I use, and how to make it work ?
Thanks a lot for your help :)

I had the use the x509 key spec in addition to the RSA key spec
RSAPublicKeySpec spec = new RSAPublicKeySpec(new BigInteger(modulusBytes), new BigInteger(exponentBytes));
KeyFactory factory = KeyFactory.getInstance("RSA");
PublicKey key = factory.generatePublic(spec);
X509EncodedKeySpec X509publicKey = new X509EncodedKeySpec(key.getEncoded());
KeyFactory kf = KeyFactory.getInstance("RSA");
PublicKey pubKey64 = kf.generatePublic(X509publicKey);
This worked for both the auth0 and jwt.io libraries

To validate the signature online with jwt.io, you just need to put there the following json as a public key:
{
"kty":"RSA",
"kid":"DQr-GCc8rH3y5fkAuo0iau-ue-s",
"e":"AQAB",
"n":"qOYyKKnoUpXd2qIj8A0tdumWwnDbVjXOVaPfiX5lxBvYEtgWPLknf1Nftdk371a7f1jD8SFFDxXnj-PPFx8qoNETOITvbR12uvWmS1J36B5Uo_ViHp7dC-GaZG_EdafyK0rxRPvK8b37NPXWhTggbxCZhYaqJUMb1t0xogDadEyM95lZweEXrwsJNzoyXiGnPfsRgy32TjOOXIMZnAMoj-osYd2WawymkRV6cteo3f8KMT72_kp8oG-kGm1s3ZooEfI3_9Z2jHVGWQLUWbmZKIrvjuUo2dhmqWWsNyTO3RsF4qyrRCpmZNawDf_GsioBTZ3vfPF_T58moH7cJ50Byw"
}

Related

Signature.verify is throwing an exception Signature length not correct: got 248 but was expecting 256

java version 1.8
import java.io.ByteArrayInputStream;
import java.security.KeyFactory;
import java.security.Signature;
import java.security.cert.Certificate;
import java.security.cert.CertificateFactory;
import java.security.interfaces.RSAPublicKey;
import java.util.Base64;
/**
*
* #author user
*/
public class Test {
public static void main(String[] args) throws Exception {
String publicKeyB64 = "MIIJRzCCBy+gAwIBAgITIAAJCdv4ae0wATxOVgAAAAkJ2zANBgkqhkiG9w0BAQsFADCBizELMAkGA1UEBhMCVVMxEzARBgNVBAgTCldhc2hpbmd0b24xEDAOBgNVBAcTB1JlZG1vbmQxHjAcBgNVBAoTFU1pY3Jvc29mdCBDb3Jwb3JhdGlvbjEVMBMGA1UECxMMTWljcm9zb2Z0IElUMR4wHAYDVQQDExVNaWNyb3NvZnQgSVQgVExTIENBIDIwHhcNMTkwODE5MDEzMTA2WhcNMjEwODE5MDEzMTA2WjAqMSgwJgYDVQQDEx9lc3RzY2xpZW50LmNvcmVhdXRoLm91dGxvb2suY29tMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAwEET72EiQSES+R96JDoOVBopnKtMJKrODwz5brOXWvzqQ4a5KxOVj7wYjpGLTNgkUPnNtOYdc8xee0pmXYunPQVV+PsfyypD+KZr4v0qP/1NPt2Qa9qoKIx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zAsImV4cCI6MTU5MzA0OTYzMCwiaXNzIjoiMDAwMDAwMDItMDAwMC0wZmYxLWNlMDAtMDAwMDAwMDAwMDAwQDhlOTAwMzU4LTliYzAtNGJkMi05ZjM0LTQ1OTk2Nzg5OTA1ZCIsImF1ZCI6Imh0dHBzOi8vbWFpbGFwcC5mb3JjZS5jb20vY2xpZW50cy9tYWlsYXBwL2FjdGl2YXRpb24ifQ";
String signature = "oifeWN-wnci-WCS6XPLC-74ynG9rmXdePVfMMxX9WsAXOK5tvRpNmNsPqu9bllufAIUhgpNIYtHEB39-_o2pzpugyfkohLJfPovEQa-1X8zzudjxY3j5tRyISzVuwL9l6zROhJIdOvXsoarzcuQ38j492H7ol7auTvfDI4Mwu4Ri_e2rbiFYWsYU36Htj39DEiOvpQ12z7Onu-Yrj1inICTDtJsOdv9HWrO2nZ5IwRdl45Tt0Ks3ZrBeStleNVCXQdU_xKvYtbO02fUfgkFrIzEUZYHgXbK8sE2m0phmeU7Wp-KdW4jVVl9yLQtB98_FJJfw9tI4Oys2NBBY2sLyhQ";
RSAPublicKey secret = null;
try {
secret = null;
CertificateFactory cf = CertificateFactory.getInstance("X.509");
Certificate cert = cf.generateCertificate(new ByteArrayInputStream(Base64.getMimeDecoder().decode(publicKeyB64)));
secret = (RSAPublicKey) cert.getPublicKey();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
KeyFactory kf = KeyFactory.getInstance("RSA");
Signature privateSignature = Signature.getInstance("SHA256withRSA");
privateSignature.initVerify(secret);
privateSignature.update(data.getBytes("UTF-8"));
System.out.println(privateSignature.verify(Base64.getMimeDecoder().decode(signature.getBytes())));
}
}
Getting the following exception:
Exception in thread "main" java.security.SignatureException: Signature length not correct: got 248 but was expecting 256
at sun.security.rsa.RSASignature.engineVerify(RSASignature.java:211)
at java.security.Signature$Delegate.engineVerify(Signature.java:1394)
at java.security.Signature.verify(Signature.java:771)
at com.ciphercloud.plugin.salesforce.rewriters.Test.main(Test.java:35)
One more question:
Earlier, I used the Base64.getDecoder().decode(signature.getBytes())) but it's throwing an error, so I changed to Base64.getMimeDecoder().decode(signature.getBytes())). May I know why it faild with Base64.getDecoder().decode()?
The problem here is the wrong decoding.
Neither Mime (Base64.getMimeDecoder().decode()) nor Base64 (Base64.getDecoder().decode()) are correct.
JWT uses Base64url encoding, not Base64. The difference are the - and _ characters, which are used in base64url to replace the + and / of the Base64 standard. Also the padding = is omitted in Base64url encoding.
The correct way to decode the JWT header, payload and signature is to use the Base64url decoder:
Base64.getUrlDecoder().withoutPadding().decode()

A java server use SHA256WithRSA to sign message, but python can not verify

Here is the code, the second (message, signature and public key) works fine on Java, can verify the message. But when I am using python, it will failed.
If am signed the message and the code will verify the message correctly.
Would some one help me to check the problem? Thank you.
# -*- coding:utf-8 -*-
from Crypto.PublicKey import RSA
from Crypto.Hash import SHA256
from Crypto.Signature import PKCS1_v1_5
from base64 import b64decode, b64encode
public_key = 'MFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBALyJy3rlD9EtWqVBzSIYxRRuFWRVn3juht2nupDCBSsWi7uKaRu3W0gn5y6aCacArtCkrf0EehwYRm0A4iHf8rkCAwEAAQ=='
private_key = 'MIIBVQIBADANBgkqhkiG9w0BAQEFAASCAT8wggE7AgEAAkEAvInLeuUP0S1apUHNIhjFFG4VZFWfeO6G3ae6kMIFKxaLu4ppG7dbSCfnLpoJpwCu0KSt/QR6HBhGbQDiId/yuQIDAQABAkEAqm/y15UtOE7Ey/HxLCqyNqbRhdN1h5AxsT0IhgYvP+PhWGc3hRElMwNCdiNaJBh04R1iK6wmKoi3DSjkdU6IAQIhAPRL9khAdPMxjy5tpswNWeaDjNJrlUKEnItQUkoHqve5AiEAxZIDz235HcUgLg9ApYK4spOpzLDGCCgfO3FxmrUEUwECIEaLjQIOQvdbT1p75Ze1H0nWoRq+YGrF+qKsPicMkc1ZAiARlNTR+K9afthGQQU3tVJKUemiVXjJ8QgWehnp8oHYAQIhANsC2fEVjWv94Oy2c8I9qhuX+yfNtvZ2m+Kmf2o4JFrR'
bank_response_data = """{"head":{"vernbr":"1.0","mchnbr":"BILL0003","mchtyp":"BILLTYP","trscod":"BILL001","msgidc":"201805011230500001","sigtim":"20190307115511","sigalg":"SHA256WithRSA","retcod":"F","retmsg":"GWB2B006 源IP地址不在商户IP白名单中;商户编号:BILL0003;IP地址:123.139.40.150"}}"""
bank_response_signature = """uZl0/5D694GnAd/G9OPRs9BSd9fb0fZGXSGThBtgLnKi+CDQAdasOX05mKazXZki0blXxApGYRAWa/kOrf+Wl0USfklx0G5w/eGERfMdRWpvtV3S2MBCH/H/0T81nKGgn8svkT/Trj7+Mc+e654Jn8IijGyV9m8Ak92hG2bLtbc="""
bank_public_key = """MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDZs4l8Ez3F4MG0kF7RRSL+pn8MmxVE3nfdXzjx6d3rH8IfDbNvNRLS0X0b5iJnPyFO8sbbUo1Im4zX0M8XA0xnnviGyn5E6occiyUXJRgokphWb5BwaYdVhnLldctdimHoJTk3NFEQFav3guygR54i3tymrDc8lWtuG8EczVu8FwIDAQAB"""
def sign():
key_bytes = bytes(private_key, encoding="utf-8")
key_bytes = b64decode(key_bytes)
key = RSA.importKey(key_bytes)
hash_value = SHA256.new(bytes(bank_response_data, encoding="utf-8"))
signer = PKCS1_v1_5.new(key)
signature = signer.sign(hash_value)
return b64encode(signature)
def verify(data, signature, the_pub_key):
print(signature)
key_bytes = bytes(the_pub_key, encoding="utf-8")
key_bytes = b64decode(key_bytes)
key = RSA.importKey(key_bytes)
hash_value = SHA256.new(bytes(data, encoding="utf-8"))
verifier = PKCS1_v1_5.new(key)
if verifier.verify(hash_value, b64decode(signature)):
print("The signature is authentic.")
else:
print("The signature is not authentic.")
verify(bank_response_data, sign(), public_key)
verify(bank_response_data, bank_response_signature.encode('utf-8'),
bank_public_key)
# -*- coding:utf-8 -*-
from Cryptodome.Signature import PKCS1_v1_5 # pip install pycryptodomex
from Cryptodome.Hash import SHA256
from Cryptodome.PublicKey import RSA
from base64 import decodebytes, encodebytes
public_key = "MFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBALyJy3rlD9EtWqVBzSIYxRRuFWRVn3juht2nupDCBSsWi7uKaRu3W0gn5y6aCacArtCkrf0EehwYRm0A4iHf8rkCAwEAAQ=="
private_key = "MIIBVQIBADANBgkqhkiG9w0BAQEFAASCAT8wggE7AgEAAkEAvInLeuUP0S1apUHNIhjFFG4VZFWfeO6G3ae6kMIFKxaLu4ppG7dbSCfnLpoJpwCu0KSt/QR6HBhGbQDiId/yuQIDAQABAkEAqm/y15UtOE7Ey/HxLCqyNqbRhdN1h5AxsT0IhgYvP+PhWGc3hRElMwNCdiNaJBh04R1iK6wmKoi3DSjkdU6IAQIhAPRL9khAdPMxjy5tpswNWeaDjNJrlUKEnItQUkoHqve5AiEAxZIDz235HcUgLg9ApYK4spOpzLDGCCgfO3FxmrUEUwECIEaLjQIOQvdbT1p75Ze1H0nWoRq+YGrF+qKsPicMkc1ZAiARlNTR+K9afthGQQU3tVJKUemiVXjJ8QgWehnp8oHYAQIhANsC2fEVjWv94Oy2c8I9qhuX+yfNtvZ2m+Kmf2o4JFrR"
bank_response_data = """{"head":{"vernbr":"1.0","mchnbr":"BILL0003","mchtyp":"BILLTYP","trscod":"BILL001","msgidc":"201805011230500001","sigtim":"20190307115511","sigalg":"SHA256WithRSA","retcod":"F","retmsg":"GWB2B006 源IP地址不在商户IP白名单中;商户编号:BILL0003;IP地址:123.139.40.150"}}"""
bank_response_signature = """uZl0/5D694GnAd/G9OPRs9BSd9fb0fZGXSGThBtgLnKi+CDQAdasOX05mKazXZki0blXxApGYRAWa/kOrf+Wl0USfklx0G5w/eGERfMdRWpvtV3S2MBCH/H/0T81nKGgn8svkT/Trj7+Mc+e654Jn8IijGyV9m8Ak92hG2bLtbc="""
bank_public_key = """MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDZs4l8Ez3F4MG0kF7RRSL+pn8MmxVE3nfdXzjx6d3rH8IfDbNvNRLS0X0b5iJnPyFO8sbbUo1Im4zX0M8XA0xnnviGyn5E6occiyUXJRgokphWb5BwaYdVhnLldctdimHoJTk3NFEQFav3guygR54i3tymrDc8lWtuG8EczVu8FwIDAQAB"""
def sign(private_key=private_key, raw_string=bank_response_data):
private_key = RSA.importKey(decodebytes(private_key.encode()))
signer = PKCS1_v1_5.new(private_key)
signature = signer.sign(SHA256.new(raw_string.encode()))
return encodebytes(signature).decode().replace("\n", "")
def verify(data, signature, public_key):
print(signature)
key = RSA.importKey(decodebytes(public_key.encode()))
hash_value = SHA256.new(data.encode())
verifier = PKCS1_v1_5.new(key)
if verifier.verify(hash_value, decodebytes(signature.encode())):
print("The signature is authentic.")
else:
print("The signature is not authentic.")
verify(bank_response_data, sign(), public_key)
verify(bank_response_data, bank_response_signature, bank_public_key)
Below is the java code, it works fine with the same signature and public key.
import org.apache.commons.codec.digest.DigestUtils;
import java.security.KeyFactory;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.Signature;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.Base64;
public class MyTest {
public static final String KEY_ALGORITHM = "RSA";
public static final String SIGNATURE_ALGORITHM = "SHA256WithRSA";
public static void main(String[] args) {
String data = "{\"head\":{\"vernbr\":\"1.0\",\"mchnbr\":\"BILL0003\",\"mchtyp\":\"BILLTYP\",\"trscod\":\"BILL001\",\"msgidc\":\"201805011230500001\",\"sigtim\":\"20190307115511\",\"sigalg\":\"SHA256WithRSA\",\"retcod\":\"F\",\"retmsg\":\"GWB2B006 源IP地址不在商户IP白名单中;商户编号:BILL0003;IP地址:123.139.40.150\"}}";
String signature = "dnAFU2e5zFb8rJ1mXDNk5AG9UyujVIUArkBjb1Nonf7iMhZwHfHRO633eW5n7uELFnyJZk6Go2D6ovp4jEnIoA==";
String cmbcRespSignature = "uZl0/5D694GnAd/G9OPRs9BSd9fb0fZGXSGThBtgLnKi+CDQAdasOX05mKazXZki0blXxApGYRAWa/kOrf+Wl0USfklx0G5w/eGERfMdRWpvtV3S2MBCH/H/0T81nKGgn8svkT/Trj7+Mc+e654Jn8IijGyV9m8Ak92hG2bLtbc=";
String cmbcPublicKey = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDZs4l8Ez3F4MG0kF7RRSL+pn8MmxVE3nfdXzjx6d3rH8IfDbNvNRLS0X0b5iJnPyFO8sbbUo1Im4zX0M8XA0xnnviGyn5E6occiyUXJRgokphWb5BwaYdVhnLldctdimHoJTk3NFEQFav3guygR54i3tymrDc8lWtuG8EczVu8FwIDAQAB";
try {
boolean verify = verify(DigestUtils.sha256(data), cmbcPublicKey, cmbcRespSignature);
if (verify) {
}
} catch (Exception e) {
}
}
public static boolean verify(byte[] data, String publicKey, String sign) throws Exception {
final Base64.Decoder decoder = Base64.getDecoder();
final byte[] keyBytes = publicKey.getBytes("UTF-8");
X509EncodedKeySpec keySpec = new X509EncodedKeySpec(decoder.decode(keyBytes));
KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
PublicKey pubKey = keyFactory.generatePublic(keySpec);
Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM);
signature.initVerify(pubKey);
signature.update(data);
return signature.verify(decoder.decode(sign));
}
}
Finally, I get the answer.
In java
DigestUtils.sha256(data) did hash,
SHA256WithRSA algorithm will do hash
So what I should do is hash 2 times in my python code

Instantiate java.security classes PrivateKey and X509Certificate from .key and .cer files

The original goal is:
Generate a https url where one of parameters is PKCS7 detached signature (RSA, SHA-256, UTF-8, BASE64).
What do I have:
private key (.key file begin with "-----BEGIN RSA PRIVATE KEY-----",
end like this "kIng0BFt5cjuur81oQqGJgvU+dC4vQio+hVc+eAQTGmNQJV56vAHcq4v
-----END RSA PRIVATE KEY-----")
self signed certificate (.cer file begin with "-----BEGIN CERTIFICATE-----",
end like this "xwRtGsSkfOFL4ehKn/K7mgQEc1ZVPrxTC7C/g+7grbKufvqNmsYW4w==
-----END CERTIFICATE-----")
data to sign
I found a java code that do almost what I need.
Method signature:
public static String sign(PrivateKey privateKey,
X509Certificate certificate,
String data);
Now I'm stuck on how to get PrivateKey and X509Certficiate classes from given files.
I looked at many examples and got confused by these moments:
1.
KeyStore ks = KeyStore.getInstance("pkcs12");
or
PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(keyBytes);
Didn't find alternatives for PKCS7 standard.
A snippet of method that builds PrivateKey using bouncycastle library:
inputStream = Files.newInputStream(privateKeyFile.toPath());
reader = new InputStreamReader(inputStream, StandardCharsets.UTF_8);
pemParser = new PEMParser(reader);
PEMDecryptorProvider decryptorProvider = new JcePEMDecryptorProviderBuilder()
.setProvider(PROVIDER)
.build(privateKeyPassword.toCharArray());
PEMEncryptedKeyPair encryptedKeyPair = (PEMEncryptedKeyPair) pemParser.readObject();
PEMKeyPair keyPair = encryptedKeyPair.decryptKeyPair(decryptorProvider);
...
In this example I have to provide some privateKeyPassword to PEMDecryptorProvider. What is the point of this password and where can I get it?
From keyPair value I can get both privateKey and publicKey.
What is the connection between publicKey from PEMKeyPair and my certificate ? Are they the same?
Any help will be appreciated, thanks!
You don't need bouncycastle to read in the public key as Java's CertificateFactory directly supports the format of your .cer file.
The private key appears to be in a PKCS1 format that openssl can produce. If you wish to keep that format this answer shows how to extract the private key. Combining the two, here is a short snippet to read in a certificate and a private key.
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.openssl.PEMKeyPair;
import org.bouncycastle.openssl.PEMParser;
import org.bouncycastle.openssl.jcajce.JcaPEMKeyConverter;
import java.io.FileInputStream;
import java.io.FileReader;
import java.security.KeyPair;
import java.security.PrivateKey;
import java.security.Security;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
public class Main {
private static PrivateKey readPrivateKey(String filename) throws Exception {
PEMParser pemParser = new PEMParser(new FileReader(filename));
JcaPEMKeyConverter converter = new JcaPEMKeyConverter().setProvider("BC");
PEMKeyPair pemKeyPair = (PEMKeyPair) pemParser.readObject();
KeyPair kp = converter.getKeyPair(pemKeyPair);
return kp.getPrivate();
}
private static X509Certificate readCertificate(String filename) throws Exception {
CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
return (X509Certificate) certificateFactory.generateCertificate(new FileInputStream(filename));
}
public static void main(String[] args) throws Exception {
Security.addProvider(new BouncyCastleProvider());
PrivateKey privateKey = readPrivateKey("myKey.priv");
X509Certificate cert = readCertificate("mycert.cer");
}
}

Verifying signature of a file using the certificates available in store

I am totally new to security and signature verification and so far I couldn't find a place which explained the basics of signature verification. I need to verify the signature of a file by obtaining the public key from the appropriate certificate available from certificate store. the tutorial in Java (https://docs.oracle.com/javase/tutorial/security/apisign/versig.html) doesn't teach how to obtain a certificate from the trusted certificate store and verify using that. I went through Bouncy castle WIKI http://www.bouncycastle.org/wiki/display/JA1/BC+Version+2+APIs but its not really explanatory for a beginner. How do I do this? Given a signed file, how can I check for its public key from the certificate store and verify if its the right person who has sent the file? Please advice.
Because you did not provide what build management you use, I assume it will be Maven.
First, include BouncyCastle in your dependency
<dependency>
<groupId>org.bouncycastle</groupId>
<artifactId>bcprov-jdk15on</artifactId>
<version>1.53</version>
</dependency>
After that, you need to make a util class that you will be using for sign or verify the certificate. Something like this:
package your.pack.location;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.bouncycastle.util.encoders.Base64;
import org.bouncycastle.util.io.pem.PemObject;
import org.bouncycastle.util.io.pem.PemReader;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.security.*;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.KeySpec;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
/**
* Author: harunalfat
*/
public class SignatureUtils {
private static final Logger log = LogManager.getLogger(SignatureUtils.class);
public static String sign(String plainText, PrivateKey privateKey) throws Exception {
byte[] data = plainText.getBytes("ISO-8859-1");
Signature signature = Signature.getInstance("SHA1WithRSA", "BC");
signature.initSign(privateKey);
signature.update(data);
return Base64.toBase64String(signature.sign());
}
public static boolean verify(String plainText, String signString, PublicKey publicKey) throws Exception{
byte[] data = plainText.getBytes("ISO-8859-1");
Signature signature = Signature.getInstance("SHA1WithRSA", "BC");
signature.initVerify(publicKey);
signature.update(data);
byte[] signByte = Base64.decode(signString);
return signature.verify(signByte);
}
private static PemObject getPemObjectFromResource(String fileLocation) throws IOException {
Resource resource = new ClassPathResource(fileLocation);
InputStream is = resource.getInputStream();
PemObject pemObject = new PemReader(new InputStreamReader( is )).readPemObject();
return pemObject;
}
private static X509EncodedKeySpec getPubKeySpec(String fileLocation) throws IOException, NoSuchAlgorithmException {
PemObject pemObject = getPemObjectFromResource(fileLocation);
byte[] data = pemObject.getContent();
X509EncodedKeySpec keySpec = new X509EncodedKeySpec(data);
return keySpec;
}
private static PKCS8EncodedKeySpec getPriKeySpec(String fileLocation) throws IOException, NoSuchAlgorithmException {
PemObject pemObject = getPemObjectFromResource(fileLocation);
byte[] data = pemObject.getContent();
PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(data);
return keySpec;
}
public static PublicKey getPublicKey(String fileLocation) throws IOException, NoSuchAlgorithmException, InvalidKeySpecException {
KeyFactory kf = KeyFactory.getInstance("RSA");
KeySpec keySpec = getPubKeySpec(fileLocation);
return kf.generatePublic(keySpec);
}
public static PrivateKey getPrivateKey(String fileLocation) throws IOException, NoSuchAlgorithmException, InvalidKeySpecException {
KeyFactory kf = KeyFactory.getInstance("RSA");
KeySpec keySpec = getPriKeySpec(fileLocation);
return kf.generatePrivate(keySpec);
}
}
And then you will use it like this
package your.another.pack;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.tomcat.util.codec.binary.Base64;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.junit.Test;
import org.mockito.MockitoAnnotations;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.Security;
import static org.junit.Assert.assertTrue;
/**
* Author: harunalfat
*/
public class SignatureUtilsTest {
private static final Logger log = LogManager.getLogger(SignatureUtilsTest.class);
private static final String PLAIN = "attack at dawn";
#Test
public void testSignAndVerify() throws Exception {
Security.addProvider(new BouncyCastleProvider()); // <-- IMPORTANT!!! This will add BouncyCastle as provider in Java Security
PrivateKey privateKey = SignatureUtils.getPrivateKey("key/private2.pem"); // This is located on src/main/resources/key/private2.pem
PublicKey publicKey = SignatureUtils.getPublicKey("key/public2.pem"); // This is located on src/main/resources/key/public2.pem
// In this example, I use junit test, so it will be on src/test/resources/...
log.info("Private Key : "+Base64.encodeBase64String(privateKey.getEncoded()));
log.info("Public Key : "+Base64.encodeBase64String(publicKey.getEncoded()));
String sign = SignatureUtils.sign(PLAIN, privateKey);
log.info("Plain String : "+PLAIN);
log.info("Sign : "+sign);
boolean result = SignatureUtils.verify(PLAIN,sign, publicKey);
log.info("Result : "+result);
assertTrue(result);
}
}
Of course, you can change the Signature instance with another Algorithm. In my case I use "SHA1WithRSA", but you get the point right?
With this, someone will encrypt their data using their private key, and send it to you. After that, you will verify the data using the public key they give.
In example, Bob send to you message about money amount he sent to you ($5000), and sign it using their private key, become encrypted. When the data arrived to you, you know Bob supposed to send $5000, then you verify the encrypted data with text $5000 and public key Bob share, but is it really $5000 OR does it comes from Bob?
If the data has been changed, OR when someday you ask for some Money to Bob, but the message tapped by someone else and s/he send you the amount message with private key other than Bob's, you will know.
Feel free to ask :)

EC2 Windows - Get Administrator Password

Currently, the only way I know to retrieve the administrator password from a newly created EC2 windows instance is through the AWS management console. This is fine, but I need to know how to accomplish this via the Java API - I can't seem to find anything on the subject. Also, once obtained, how do I modify the password using the same API?
The EC2 API has a call "GetPasswordData" which you can use to retrieve an encrypted block of data containing the Administrator password. To decrypt it, you need 2 things:
First, the private key. This is the private half of the keypair you used to instantiate the instance. A complication is that normally Amazon uses keys in PEM format ("-----BEGIN"...) but the Java Crypto API wants keys in DER format. You can do the conversion yourself - strip off the -----BEGIN and -----END lines, take the block of text in the middle and base64-decode it.
Second, the encryption parameters. The data is encrypted with RSA, with PKCS1 padding – so the magic invocation to give to JCE is: Cipher.getInstance("RSA/NONE/PKCS1Padding")
Here's a full example (that relies on BouncyCastle, but could be modified to use a different crypto engine)
package uk.co.frontiertown;
import com.amazonaws.auth.AWSCredentials;
import com.amazonaws.auth.BasicAWSCredentials;
import com.amazonaws.services.ec2.AmazonEC2Client;
import com.amazonaws.services.ec2.model.GetPasswordDataRequest;
import com.amazonaws.services.ec2.model.GetPasswordDataResult;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.util.encoders.Base64;
import javax.crypto.Cipher;
import java.nio.charset.Charset;
import java.security.GeneralSecurityException;
import java.security.KeyFactory;
import java.security.PrivateKey;
import java.security.Security;
import java.security.spec.PKCS8EncodedKeySpec;
public class GetEc2WindowsAdministratorPassword {
private static final String ACCESS_KEY = "xxxxxxxxxxxxxxxxxxxx";
private static final String SECRET_KEY = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
private static final String PRIVATE_KEY_MATERIAL = "-----BEGIN RSA PRIVATE KEY-----\n" +
"MIIEowIBAAKCAQEAjdD54kJ88GxkeRc96EQPL4h8c/7V2Q2QY5VUiJ+EblEdcVnADRa12qkohT4I\n" +
// several more lines of key data
"srz+xXTvbjIJ6RL/FDqF8lvWEvb8uSC7GeCMHTznkicwUs0WiFax2AcK3xjgtgQXMgoP\n" +
"-----END RSA PRIVATE KEY-----\n";
public static void main(String[] args) throws GeneralSecurityException, InterruptedException {
Security.addProvider(new BouncyCastleProvider());
String password = getPassword(ACCESS_KEY, SECRET_KEY, "i-XXXXXXXX", PRIVATE_KEY_MATERIAL);
System.out.println(password);
}
private static String getPassword(String accessKey, String secretKey, String instanceId, String privateKeyMaterial) throws GeneralSecurityException, InterruptedException {
// Convert the private key in PEM format to DER format, which JCE can understand
privateKeyMaterial = privateKeyMaterial.replace("-----BEGIN RSA PRIVATE KEY-----\n", "");
privateKeyMaterial = privateKeyMaterial.replace("-----END RSA PRIVATE KEY-----", "");
byte[] der = Base64.decode(privateKeyMaterial);
PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(der);
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
PrivateKey privateKey = keyFactory.generatePrivate(keySpec);
// Get the encrypted password data from EC2
AWSCredentials awsCredentials = new BasicAWSCredentials(accessKey, secretKey);
AmazonEC2Client client = new AmazonEC2Client(awsCredentials);
GetPasswordDataRequest getPasswordDataRequest = new GetPasswordDataRequest().withInstanceId(instanceId);
GetPasswordDataResult getPasswordDataResult = client.getPasswordData(getPasswordDataRequest);
String passwordData = getPasswordDataResult.getPasswordData();
while (passwordData == null || passwordData.isEmpty()) {
System.out.println("No password data - probably not generated yet - waiting and retrying");
Thread.sleep(10000);
getPasswordDataResult = client.getPasswordData(getPasswordDataRequest);
passwordData = getPasswordDataResult.getPasswordData();
}
// Decrypt the password
Cipher cipher = Cipher.getInstance("RSA/NONE/PKCS1Padding");
cipher.init(Cipher.DECRYPT_MODE, privateKey);
byte[] cipherText = Base64.decode(passwordData);
byte[] plainText = cipher.doFinal(cipherText);
String password = new String(plainText, Charset.forName("ASCII"));
return password;
}
}
ObDisclosure: I originally answered this on a blog posting at http://www.frontiertown.co.uk/2012/03/java-administrator-password-windows-ec2-instance/
You can create an instance, set the password and then turn it back into an image. Effectively setting a default password for each instance you create. Wouldn't this be simpler?
Looks like you are looking for the following parts of the API: GetPasswordDataRequest and GetPasswordDataResult
You can also create a Image with default user name and Password setup on that Image.And then launch all instances with that image id..so that you dont need to create and retrieve password evry time..just launch your instance rdp that launched instance with definde credntials in Image. I am doing same.And its perfectly working for me.

Categories

Resources