public static void main(String[] args) {
try{
String mod = "q0AwozeUj0VVkoksDQSCTj3QEgODomq4sAr02xMyIrWldZrNHhWfZAIcWt2MuAY3X6S3ZVUfOFXOrVbltRrO3F9Z6R8/jJIMv7wjkeVBFC5gncwGR0C3aV9gmF6II19jTKfF1sxb26iMEMAlMEOSnAAceNaJH91zBoaW7ZIh+qk=";
String exp = "AQAB";
byte[] modulusBytes = Base64.decodeBase64(mod.getBytes("UTF-8"));
byte[] exponentBytes = Base64.decodeBase64(exp.getBytes("UTF-8"));
String signedMessage = "3753e672cfb21e3c182ef2df51f19edeffb63432ed338a47251326ccc14aa63883e910a140cf313754ebc6425aad434e309307cc882da6cd4a4f9f40bd14a9823aca145e5ffc97cd63dbb5925c049282416bdfd7d74ddeef7055065210a841793fe315dff5a44af19c1522daafdc2f7e61ce5a2b42ebf79dfb086e6d210168dd";
BigInteger modulus = new BigInteger(1, modulusBytes );
BigInteger exponent = new BigInteger(1, exponentBytes);
RSAPublicKeySpec rsaPubKey = new RSAPublicKeySpec(modulus, exponent);
KeyFactory fact = KeyFactory.getInstance("RSA");
PublicKey pubKey = fact.generatePublic(rsaPubKey);
Signature signature = Signature.getInstance("SHA1withRSA");
byte[] sigBytes = hexStringToByteArray(signedMessage);
signature.initVerify(pubKey);
System.out.println(signature.verify(sigBytes));
}catch(Exception e){
System.out.println("Error: " + e.toString());
}
}
private static byte[] hexStringToByteArray(final String encoded) {
if ((encoded.length() % 2) != 0)
throw new IllegalArgumentException("Input string must contain an even number of characters");
final byte result[] = new byte[encoded.length()/2];
final char enc[] = encoded.toCharArray();
for (int i = 0; i < enc.length; i += 2) {
StringBuilder curr = new StringBuilder(2);
curr.append(enc[i]).append(enc[i + 1]);
result[i/2] = (byte) Integer.parseInt(curr.toString(), 16);
}
return result;
}
This code always returns false. I'm not sure where to go from here.
Where you sign the message you should have some code like this:
Signature signature = Signature.getInstance("SHA1withRSA");
signature.initSign(privKey);
signature.update(message);
byte[] signatureValue = signature.sign();
Note the byte-array named signatureValue. That is the actual signature on the data. That is what you should provide to the verify()-method. The message that is signed should be provided in a call to the update()-method. I.e.:
Signature signature = Signature.getInstance("SHA1withRSA");
signature.initVerify(pubKey);
signature.update(message);
bool ok = signature.verify(signatureValue);
I think the problem is that you are not actually giving it a message to verify.
An RSA signature works by first hashing the message (that's the "SHA1" in "SHA1withRSA"), and then performing an trapdoor operation to it. This is an operation which is easy to do in one direction and hard in the other direction, unless you know some secret information (the RSA private key).
To verify, you first invert the mathematical transformation (because it's easy in one direction), and then compare the hash that is embedded in the signature with the hash of the message you just computed. The signature does not in itself contain the message; to verify a signature you need both the signature and the message that was signed.
At an API level, it looks like the Signature class is expecting you to call update with the contents of the message that this signature was for. Without this, it probably is comparing the hash with the hash of an empty string, so unless your originally signed message was also an empty string, the signature is in fact not valid.
You were right, thanks Jack. The below method works perfectly (even with a key created in .NET)! I hope this helps others.
public static void main(String[] args) {
try{
String userID = "189711";
String companyCode = "ILIKEPIZZA";
String combine = userID + "." + companyCode;
String mod = "q0AwozeUj0VVkoksDQSCTj3QEgODomq4sAr02xMyIrWldZrNHhWfZAIcWt2MuAY3X6S3ZVUfOFXOrVbltRrO3F9Z6R8/jJIMv7wjkeVBFC5gncwGR0C3aV9gmF6II19jTKfF1sxb26iMEMAlMEOSnAAceNaJH91zBoaW7ZIh+qk=";
String exp = "AQAB";
byte[] modulusBytes = Base64.decodeBase64(mod.getBytes("UTF-8"));
byte[] exponentBytes = Base64.decodeBase64(exp.getBytes("UTF-8"));
String sign = "3753e672cfb21e3c182ef2df51f19edeffb63432ed338a47251326ccc14aa63883e910a140cf313754ebc6425aad434e309307cc882da6cd4a4f9f40bd14a9823aca145e5ffc97cd63dbb5925c049282416bdfd7d74ddeef7055065210a841793fe315dff5a44af19c1522daafdc2f7e61ce5a2b42ebf79dfb086e6d210168dd";
BigInteger modulus = new BigInteger(1, modulusBytes );
BigInteger exponent = new BigInteger(1, exponentBytes);
RSAPublicKeySpec rsaPubKey = new RSAPublicKeySpec(modulus, exponent);
KeyFactory fact = KeyFactory.getInstance("RSA");
PublicKey pubKey = fact.generatePublic(rsaPubKey);
Signature signature = Signature.getInstance("SHA1withRSA");
byte[] sigBytes = hexStringToByteArray(sign);
signature.initVerify(pubKey);
signature.update(combine.getBytes("UTF-8"));
System.out.println(signature.verify(sigBytes));
}catch(Exception e){
System.out.println("Error: " + e.toString());
}
}
Related
I have to write PHP program to do the same function with the java sign function as follow
public static String sign(byte[] data, String privateKey) throws Exception {
MessageDigest messageDigest = MessageDigest.getInstance("SHA-256");
messageDigest.update(data);
byte[] hashData = messageDigest.digest();
StringBuffer hexString = new StringBuffer();
byte[] keyBytes = Base64Utils.decode(privateKey.getBytes());
PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes);
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
PrivateKey privateK = keyFactory.generatePrivate(pkcs8KeySpec);
Signature signature = Signature.getInstance("NONEWithRSA");
signature.initSign(privateK);
signature.update(hashData);
byte[] sign = signature.sign();
return Base64.getEncoder().encodeToString(sign);
}
I have done some research on google and try to write the PHP code as follow
public function sign($data, $privateKeyString){
$privateKey = openssl_pkey_get_private($privateKeyString);
$hashData = hash("sha256",$data);
openssl_sign($hashData, $signature, $privateKey);
openssl_free_key($privateKey);
return base64_encode($signature);
}
I try to pass the same key with the data let's say "Hello" to both function and testing
the hash data are map but the outcome signature are different
Is there anyone can spot what cause the return base64 signature are different between the java and php?
public function sign($data, $privateKeyString){
$privateKey = openssl_pkey_get_private($privateKeyString);
$hashData = openssl_digest("sha256",$data);
openssl_private_encrypt($hashData, $signature, $privateKey);
openssl_free_key($privateKey);
return base64_encode($signature);
}
Finally fixing the problem by using openssl_digest "sha256" instead of passing sha256 hash value into the for private key encrytion, due to the hashing need to be convert into the hex string instead of the original value.
I have signature created in Java by following code
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
EncodedKeySpec privateKeySpec = new PKCS8EncodedKeySpec(privateKeyBytes);
PrivateKey privateKey = keyFactory.generatePrivate(privateKeySpec);
signature = (Signature) rsaSha256.getCipher();
signature.initSign(privateKey);
signature.update(binaryData);
signatureBytes = signature.sign();
By verifying signature in C#, im always getting false. Following code use BouncyCastle library
ISigner signer = SignerUtilities.GetSigner("SHA256withRSA");
using (TextReader sr = new StringReader(publicKey))
{
PemReader pr = new PemReader(sr);
RsaKeyParameters keys = (RsaKeyParameters)pr.ReadObject();
signer.Init(false, keys);
signer.BlockUpdate(value, 0, value.Length);
bool isValid = signer.VerifySignature(signature);
return isValid;
}
Following code return false too
private static bool VerifyWithPublicKey(byte[] data, byte[] sig, string publicKey)
{
RSACryptoServiceProvider rsa;
using (var keyreader = new StringReader(publicKey))
{
var pemReader = new PemReader(keyreader);
var y = (RsaKeyParameters)pemReader.ReadObject();
RSAParameters p1 = DotNetUtilities.ToRSAParameters(y);
rsa = new RSACryptoServiceProvider();
rsa.ImportParameters(p1);
}
byte[] hash;
using (var sha256 = SHA256.Create())
{
hash = sha256.ComputeHash(data);
}
RSAPKCS1SignatureDeformatter RSADeformatter = new RSAPKCS1SignatureDeformatter(rsa);
RSADeformatter.SetHashAlgorithm("SHA256");
//Verify the hash and display the results to the console.
if (RSADeformatter.VerifySignature(hash, sig))
{
Console.WriteLine("The signature was verified.");
}
else
{
Console.WriteLine("The signature was NOT verified.");
}
// This always returns false
return rsa.VerifyHash(hash, CryptoConfig.MapNameToOID("SHA256"), sig);
}
Im out of ideas. Anyone done something similar? If so, can you share your code please
This works for me, I see a difference where you use .GetSigner("SHA256withRSA") but I use "SHA-256withRSA"
public static bool VerifySignature(byte[] hashBytes, byte[] signatureBytes)
{
PemReader pemReader = new PemReader(new StreamReader("PublicKey.pem"));
RsaKeyParameters parameters = (RsaKeyParameters)pemReader.ReadObject();
RsaDigestSigner signer = (RsaDigestSigner)SignerUtilities.GetSigner("SHA-256withRSA");
signer.Init(false, parameters);
signer.BlockUpdate(hashBytes, 0, hashBytes.Length);
bool isValid = signer.VerifySignature(signatureBytes);
return isValid;
}
I'm currently doing RSA encryption on Java and I have to use private and public modulus for the encryption. I currently Have the following:
private void createPublicKey() throws NoSuchAlgorithmException, InvalidKeySpecException {
String publicModulus = "d2c34017ef94f8ab6696dae66e3c0d1ad186bbd9ce4461b68d7cd017c15bda174045bfef36fbf048" +
"73cfd6d09e3806af3949f99c3e09d6d3c37f6398d8c63f9a3e39b78a187809822e8bcf912f4c44a8" +
"92fe6a65a477ddea9582738317317286a2610ba30b6b090c3b8c61ffb64207229b3f01afe928a960" +
"c5a44c24b26f5f91";
BigInteger keyInt = new BigInteger(publicModulus, 16);
BigInteger exponentInt = new BigInteger("10001", 16);
RSAPublicKeySpec keySpeck = new RSAPublicKeySpec(keyInt, exponentInt);
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
publicKey = keyFactory.generatePublic(keySpeck);
}
private void createPrivateKey() throws NoSuchAlgorithmException, InvalidKeySpecException {
String privateModulus = "6c97ab6369cf00dd174bacd7c37e6f661d04e5af10670d4d88d30148ec188e63227b8dac0c517cf9" +
"67aa73cd23684c9165dc269f091bfab33b6c5c7db95b54130e348255c30aaaac1c7f09ef701e0d6f" +
"6dc142d2e4ed78466cc104e28d50be7adf3863afc021dbdd8b5f0b968b7cd965242c7d8d4b32ee84" +
"0fac3cad134344c1";
BigInteger privateModulusInt = new BigInteger(privateModulus, 16);
BigInteger exponentInt = new BigInteger("10001", 16);
RSAPrivateKeySpec privateKeySpec = new RSAPrivateKeySpec(privateModulusInt, exponentInt);
KeyFactory factory = KeyFactory.getInstance("RSA");
privateKey = factory.generatePrivate(privateKeySpec);
}
In the main method I have the following:
createPrivateKey();
createPublicKey();
String data = "12";
Cipher cipher1 = Cipher.getInstance("RSA/ECB/NoPadding");
cipher1.init(Cipher.ENCRYPT_MODE, publicKey);
byte[] encryptedData = cipher1.doFinal(data.getBytes());
Cipher cipher2 = Cipher.getInstance("RSA/ECB/NoPadding");
cipher2.init(Cipher.DECRYPT_MODE,privateKey);
byte[] decryptedData = cipher2.doFinal(encryptedData);
System.out.println(new String(decryptedData));
In the console I get the following: ���.7���p;%kV�9y���xa�ɼ{ and not "12" If I make the String data = "12345";, I then get: javax.crypto.BadPaddingException: Message is larger than modulus
Firstly why is the encryption and decryption not working? Why am I not getting back "12". Secondly why can I not have data be greater than 2 characters?
Note I'm using the following website to get the modulus and exponent values.
There is an error creating the private key. You are providing the public exponent instead of private and (as commented #dave_thomsom_085) private exponent instead of modulus
Change createPrivateKey() with
private static PrivateKey createPrivateKey() throws NoSuchAlgorithmException, InvalidKeySpecException {
String publicModulus = "d2c34017ef94f8ab6696dae66e3c0d1ad186bbd9ce4461b68d7cd017c15bda174045bfef36fbf048" +
"73cfd6d09e3806af3949f99c3e09d6d3c37f6398d8c63f9a3e39b78a187809822e8bcf912f4c44a8" +
"92fe6a65a477ddea9582738317317286a2610ba30b6b090c3b8c61ffb64207229b3f01afe928a960" +
"c5a44c24b26f5f91";
String privateExponent = "6c97ab6369cf00dd174bacd7c37e6f661d04e5af10670d4d88d30148ec188e63227b8dac0c517cf9" +
"67aa73cd23684c9165dc269f091bfab33b6c5c7db95b54130e348255c30aaaac1c7f09ef701e0d6f" +
"6dc142d2e4ed78466cc104e28d50be7adf3863afc021dbdd8b5f0b968b7cd965242c7d8d4b32ee84" +
"0fac3cad134344c1";
BigInteger privateExponenInt = new BigInteger(privateExponent, 16);
BigInteger keyInt = new BigInteger(publicModulus, 16);
RSAPrivateKeySpec privateKeySpec = new RSAPrivateKeySpec(keyInt, privateExponenInt);
KeyFactory factory = KeyFactory.getInstance("RSA");
return factory.generatePrivate(privateKeySpec);
}
Also you should not use raw RSA without padding for security reasons. Use RSA/ECB/PKCS1Padding or the new OAEP padding RSA/ECB/OAEPWithSHA1AndMGF1Padding
According to this answer you can encrypt with PKCS1Padding data up to 11 bytes less than the key size. and using OAEP it must be less than the size of the key modulus – 41
Then, using your 1024 bits key:
PKCS1: (1024 bits / 8) - 11 = 117 bytes
OAEP: (1024 bits / 8) - 42 = 86 bytes
Also is recommended to use CRT instead of private exponent directly
RSAPrivateCrtKeySpec privateKeySpec =
new RSAPrivateCrtKeySpec(modulus, publicExponent, privateExponent, primeP, primeQ, primeExpP, primeExpQ, crtCoefficient);
I am trying to encypt some data using RSA public key and signing with SHA-512 algo. But response recevied is differnet in different plat
form.
In C#:
RSACryptoServiceProvider crypto = new RSACryptoServiceProvider();
crypto.ImportCspBlob(Convert.FromBase64String(publickey));
crypto.exportParameters(false); // and got the public key modulus and exp
byte[] response = crypto.SignData(data, "SHA512");
In Java:
// got modulus and exp for public key from c#
byte[] modulo = {.....};
byte[] exp = {1,0,1};
BigInteger modulus = new BigInteger(1, modulo);
BigInteger pubExp = new BigInteger(1, exp);
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
RSAPublicKeySpec priKeySpec = new RSAPublicKeySpec(modulus, pubExp);
RSAPublicKey Key = (RSAPublicKey)keyFactory.generatePublic(priKeySpec);
// Calculate Hash
MessageDigest sha1 = MessageDigest.getInstance("SHA-512");
byte[] digest = sha1.digest(data);
// Encrypt digest
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.ENCRYPT_MODE, Key);
byte[] response = cipher.doFinal(digest);
but both response are not matching.C# generate correct one but java not generating the same byte[]
Any missing part in java code.
private static final String algorithm = "AES/CBC/NOPadding";
if we convert type 中國傳統的 languages then we get null value when we encryt.To overcome this problem we use below thing.
private static final String algorithm = "AES/CBC/PKCS5Padding";
if we do diifferent type languages like 中國傳統的 converion can be encryted.
I've been using the Java security api and was following the tutorial on how to generate digital signatures: http://docs.oracle.com/javase/tutorial/security/apisign/gensig.html
The problem is when I run the code, the output signature is always different even when the private key and data which is to be signed stays constant. I have provided the code below which I used to run. "priv" is a file which holds the private key and is used to sign the data: "hello".
Basically the two outputs show the same data: "hello" signed with the same key but it gives a different output. I was expecting the same output to be given. Also when I run the program again, the signed data is different again from the initial run. Any help would be much appreciated. Thanks in advance
public static void main(String[] args) {
try {
FileInputStream privfis;
privfis = new FileInputStream("priv");
byte[] encKey = new byte[privfis.available()];
// obtain the encoded key in the file
privfis.read(encKey);
privfis.close();
PKCS8EncodedKeySpec privKeySpec = new PKCS8EncodedKeySpec( encKey);
KeyFactory keyFactory = KeyFactory.getInstance("DSA", "SUN");
PrivateKey priv = keyFactory.generatePrivate(privKeySpec);
Signature dsa = Signature.getInstance("SHA1withDSA", "SUN");
dsa.initSign(priv);
String message = "hello";
System.out.println(getHexString(message.getBytes()));
dsa.update(message.getBytes());
byte[] realSig = dsa.sign();
System.out.println(getHexString(realSig));
dsa.update(message.getBytes());
System.out.println(getHexString(message.getBytes()));
byte[] realSig2 = dsa.sign();
System.out.println(getHexString(realSig2));
} catch (Exception e) {
System.err.println("Caught exception " + e.toString());
e.printStackTrace();
}
}
private static String getHexString(byte[] b) {
String result = "";
for (int i = 0; i < b.length; i++) {
result += Integer.toString((b[i] & 0xff) + 0x100, 16).substring(1);
}
return result;
}
}