I'd like to sign a file by using a RSA keypair. For this purpose I have this Perl script:
#!/usr/bin/perl
use Crypt::RSA;
my $data = ... # File contents
my $rsa = new Crypt::RSA;
my $key = new Crypt::RSA::Key::Private(Filename => "stackoverflow.priv", Password => "*****");
my $signature = $rsa->sign(Message => $data, Key => $key, Armour => 0);
# Write signature to file
On the client side, I'd like to use the following Java function to verify the file:
private static final String PUBLICKEY_MOD = "190343051422614110006523776876348493...";
private static String PUBLICKEY_EXP = "65537";
public boolean check() {
byte[] data = ... // Data
byte[] dataSignature = ... // Signature (as calculated in the Perl script)
Signature signature = Signature.getInstance("SHA256withRSA");
signature.initVerify(getPublicKey());
signature.update(data);
return signature.verify(dataSignature);
}
private PublicKey getPublicKey() {
RSAPublicKeySpec spec = new RSAPublicKeySpec(new BigInteger(PUBLICKEY_MOD), new BigInteger(PUBLICKEY_EXP));
KeyFactory factory = KeyFactory.getInstance("RSA");
return factory.generatePublic(spec);
}
However, check() always reports false. These things I already checked:
data and dataSignature are correctly read
PUBLICKEY_MOD and PUBLICKEY_EXP are correct
getPublicKey() returns a PublicKey which has the correct attributes
the private key and the public key are part of the same pair
Does anyone know how to verify the file correctly? Is signature correctly instanced?
Your first clue that something might be wrong is that you never tell Perl what hash function to use, but you tell Java to use SHA256. You have a lot of work to do on the Perl side. Also, the default padding scheme for Crypt::RSA seems to be PSS, whereas for Java it is PKCSv1.5
Related
We have a java program that signs a xml file with a private key like this:
byte[] privateKeyBytes = ...; // read from the .der file
PKCS8EncodedKeySpec privateSpec = new PKCS8EncodedKeySpec(privateKeyBytes);
KeyFactory privateKeyFactory = KeyFactory.getInstance("RSA");
PrivateKey = privateKeyFactory.generatePrivate(privateSpec);
Signature rsaSignature = Signature.getInstance("SHA1withRSA");
rsaSignature.initSign(privateKey);
rsaSignature.update(data);
byte[] signature = rsaSignature.sign();
Now i have to validate this signature in C++ using cryptocpp. What i tried:
void Load(const std::string& filename, BufferedTransformation& bt)
{
FileSource file(filename.c_str(), true /*pumpAll*/);
file.TransferTo(bt);
bt.MessageEnd();
}
void LoadKeyFile(const std::string& filename, PublicKey & key)
{
ByteQueue queue;
Load(filename, queue);
key.Load(queue);
}
void verifySignature(std::string xmlString, std::string signature)
{
RSA::PublicKey publicKey;
LoadKeyFile(..., publicKey);
RSASS<PSS, SHA1>::Verifier verifier(publicKey);
// also tried RSASS<PSSR, SHA1>::Verifier verifier(publicKey);
if (!verifier.VerifyMessage((byte*)xmlString.c_str(), xmlString.size(),
(byte*)signature.c_str(), signature.size()) )
{
// always returns false
}
}
I validated that the data passed as xmlString is binary identical with the one used for creating the signature in java. The signature is base64 encoded and i also tried using it decoded.
I always failed so far.
If i create a signature with the private key using cryptopp - then validating the created signature works without problems.
What may be the problem here? I am sure this has already been done?
The solution is
RSASS<PKCS1v15, SHA1>::Verifier verifier(publicKey);
Instead of
RSASS<PSS, SHA1>::Verifier verifier(publicKey);
Thanks a lot to #Topaco!
I have already posted a similar question concerning how to load RSA keys in java. See the best response of this question to fully understand the first part of my code (the method getPulicKey, I mean).
private static PublicKey getPublicKey(String publicKey)
throws IOException, NoSuchAlgorithmException, InvalidKeySpecException {
try (PEMParser pp = new PEMParser(new StringReader(publicKey))) {
SubjectPublicKeyInfo subjPubKeyInfo = (SubjectPublicKeyInfo) pp.readObject();
RSAKeyParameters rsa = (RSAKeyParameters) PublicKeyFactory.createKey(subjPubKeyInfo);
RSAPublicKeySpec rsaSpec = new RSAPublicKeySpec(rsa.getModulus(), rsa.getExponent());
KeyFactory kf = KeyFactory.getInstance("RSA");
PublicKey myKey = kf.generatePublic(rsaSpec);
System.out.println(myKey);
return myKey;
}
}
The method verify (below) raises the following exception
Signature length not correct: got 768 but was expecting 512, in Java verify
In the following code, I decode the signature because I suppose it is Base64, but I'm not sure, sorry. I don't know wether I could show you the signature and the object. The signature is a sequence of 1024 digits and numbers. It does not end with "=". The object I have to verify is a json object in String format.
The following is the method I have written to verify a String object, given a sign and a publicKey. It calls the above method getPublicKey(...).
public static boolean verify(String object, String sign, String publicKey) throws NoSuchAlgorithmException,
InvalidKeySpecException, IOException, InvalidKeyException, SignatureException {
//object to be verified
//sign is the signature stored in the postgres DB
//publicKey is the public key stored in the postgres DB
Signature signature = Signature.getInstance("SHA256withRSA");
signature.initVerify(getPublicKey(publicKey));
byte[] objectBytes = Base64.getEncoder().encode(object.getBytes("utf-8"));
signature.update(objectBytes);
byte[] signBytes = Base64.getDecoder().decode(sign.getBytes("utf-8"));
System.out.println(signBytes.length); //this line prints 768, with decode. 1024, otherwhise
return signature.verify(signBytes);
}
EDIT:
My workmates are using the following two nodejs methods (verifySign and createSign).
In the following nodejs code (where there are workmates' methods), I encript with "createSign" the message "fake message". The sign is the following:
5f188225c68dee2ce8de588dfaccb667710da94abb5388deabfe3ad83f7a94a72ee4a3c8c51be26c5b58cdec8c82cf8135c478ad609b7985496e201b23de6c5d03e93dcd9df7b5e2315efbfd2ff6496b0aea3b425bb99c912a16aeb5efb6cefc1e175c32aaf16af3a2baca5b54f974af0f14c853228bc06410e7ad1b2b0ecec19f5aed151389bd9ccebd5e998159d5205d81a7c7e37b502df3eb5229a5fd3492680576ebfa1e76b7c47fb757a9bfb18aa9ea0b71512ab9e1afc8e551ebf6d74a042bd447233953efbf374a3a6a210ead2019b8cc8548bb304979b4bfdc90dce644cb109bbddb75dda9df1322fd8e08ef1144e870324f34d4c826d9a4b64be0442aedc6f3d5f571d7336af212825c4e0216aa5eabab6218d685a3e73d81693149b45af5f1857c4a0e50b396d1a2ea5a3effafcc4e124fd23d0427abfe5509357936ef5e7c7ca4476d6a5ae7a26e9563923a03d0780f0d897039d4d3aa2ce49dc84b31907a50045456acb57edd11a896632969245d0f97fd88dace7eb256099bbc4eedf52b5d53b481b2aeb829101d0089903ea9c3621bcbd763962b84ad57407623b576cc6a9c3328d85e0f7dd78565cd39a6648a68dd6f4334dd3a68e48491ae655601a5c9be7673ae0d3f955431fb21f33c0178ecb9067072a6b1e360ee77a45f8e855e6c545276aefc7ae70b5c7e0f1ec0b66460575e3386f8a4bbf7fd3704
Then, I verify it with public key pk (see below).
const PASSPHRASE_KEY = "...";
const crypto = require('crypto');
const prk = "...";
const pk = "-----BEGIN RSA PUBLIC KEY-----\r\n" +
"MIICCgKCAgEA1ht0OqZpP7d/05373OE7pB7yCVGNGzkUEuCneyfOzps6iA03NbvI\r\n" +
"1ZL0Jpp/N3AW73lGdhaoa3X3JE4GsI/bsToVLQwTKmIOC4yjTvBctmFEoyhhTfxW\r\n" +
"s1UHZKl4XZ/7THbRlKHhRaTKyfDAbikkMAxNT/qutLAPjnN1qOwjb1oRq52NP6FJ\r\n" +
"KWTTikz4UeOHroX+Xthn2fJSJDlQ4YMdBbgrZVx5JcHKNuPTKRf5gI8QQKMSA9Q9\r\n" +
"QJRE5OGp7b6dG14ZmOUnUxb00Mp20LgcaGPcuWU+oFsbQaF6W4G4bdkSZRJJXhSg\r\n" +
"d4Q7mahpar94/gnztJmth0GzqTWUYyZIWNqIFoMwuOgeaiDV43zb3uLsRVpRKYYy\r\n" +
"esmzcOy/jTScVLRCD8QRyu9B2wgCkNAVztQOXPCOOa4O1LlVQWaecIs4WPhOqDhi\r\n" +
"KTBhyVkpC1TrrBkp+QMqMqWll1OyVb6k/7uV0qE/i6rHJtjo5v9bcIgYzswyx9CD\r\n" +
"9PKl2Q0L0Jg7TMG+yLDIrLfGeuSeEc4XYJzN7bJcCeiizzu5iU9dQUkrncOrq9jn\r\n" +
"Ub2pM/+A+JqIsoPK3IY/pJKqH4JYpGKhO1iPQF6iXIZT1r3ZgJUSQtzSeyYqhkla\r\n" +
"2uR2BsbPbDqebCuXm3lAsY5w+dujijcn96PKwYha1LsK5sACHuJ79AMCAwEAAQ==\r\n" +
"-----END RSA PUBLIC KEY-----\r\n" +
"";
function createSign(pvt_key, data_unsigned) {
//Create a SHA256 sign generator
const signer = crypto.createSign('SHA256');
//Update context with data to sign
signer.update(data_unsigned);
//Sign the document based to user's private key
return signer.sign({
key: pvt_key,
passphrase: PASSPHRASE_KEY
},
'hex'
);
}
function verifySign(pub_key, signed_data, signature) {
const verifier = crypto.createVerify('sha256');
//Update context with data to verify
verifier.update(signed_data);
//Verify sign with user's public key
const verified = verifier.verify(
pub_key,
signature,
'hex'
);
//Send result
return verified;
}
const phrase = "fake message";
var signMade = createSign(prk, phrase);
console.log("my signature: " + signMade);
//The signature is 5f188225c68dee2ce8de588dfaccb667710da94abb5388deabfe3ad83f7a94a72ee4a3c8c51be26c5b58cdec8c82cf8135c478ad609b7985496e201b23de6c5d03e93dcd9df7b5e2315efbfd2ff6496b0aea3b425bb99c912a16aeb5efb6cefc1e175c32aaf16af3a2baca5b54f974af0f14c853228bc06410e7ad1b2b0ecec19f5aed151389bd9ccebd5e998159d5205d81a7c7e37b502df3eb5229a5fd3492680576ebfa1e76b7c47fb757a9bfb18aa9ea0b71512ab9e1afc8e551ebf6d74a042bd447233953efbf374a3a6a210ead2019b8cc8548bb304979b4bfdc90dce644cb109bbddb75dda9df1322fd8e08ef1144e870324f34d4c826d9a4b64be0442aedc6f3d5f571d7336af212825c4e0216aa5eabab6218d685a3e73d81693149b45af5f1857c4a0e50b396d1a2ea5a3effafcc4e124fd23d0427abfe5509357936ef5e7c7ca4476d6a5ae7a26e9563923a03d0780f0d897039d4d3aa2ce49dc84b31907a50045456acb57edd11a896632969245d0f97fd88dace7eb256099bbc4eedf52b5d53b481b2aeb829101d0089903ea9c3621bcbd763962b84ad57407623b576cc6a9c3328d85e0f7dd78565cd39a6648a68dd6f4334dd3a68e48491ae655601a5c9be7673ae0d3f955431fb21f33c0178ecb9067072a6b1e360ee77a45f8e855e6c545276aefc7ae70b5c7e0f1ec0b66460575e3386f8a4bbf7fd3704
console.log("was it me to sign that?");
var res = verifySign(pk, phrase, signMade);
console.log(res);
It returns true. However, If I pass to the java method verify the following (same) parameters:
object = "fake message"
sign = 5f188225c68dee2ce8de588dfaccb667710da94abb5388deabfe3ad83f7a94a72ee4a3c8c51be26c5b58cdec8c82cf8135c478ad609b7985496e201b23de6c5d03e93dcd9df7b5e2315efbfd2ff6496b0aea3b425bb99c912a16aeb5efb6cefc1e175c32aaf16af3a2baca5b54f974af0f14c853228bc06410e7ad1b2b0ecec19f5aed151389bd9ccebd5e998159d5205d81a7c7e37b502df3eb5229a5fd3492680576ebfa1e76b7c47fb757a9bfb18aa9ea0b71512ab9e1afc8e551ebf6d74a042bd447233953efbf374a3a6a210ead2019b8cc8548bb304979b4bfdc90dce644cb109bbddb75dda9df1322fd8e08ef1144e870324f34d4c826d9a4b64be0442aedc6f3d5f571d7336af212825c4e0216aa5eabab6218d685a3e73d81693149b45af5f1857c4a0e50b396d1a2ea5a3effafcc4e124fd23d0427abfe5509357936ef5e7c7ca4476d6a5ae7a26e9563923a03d0780f0d897039d4d3aa2ce49dc84b31907a50045456acb57edd11a896632969245d0f97fd88dace7eb256099bbc4eedf52b5d53b481b2aeb829101d0089903ea9c3621bcbd763962b84ad57407623b576cc6a9c3328d85e0f7dd78565cd39a6648a68dd6f4334dd3a68e48491ae655601a5c9be7673ae0d3f955431fb21f33c0178ecb9067072a6b1e360ee77a45f8e855e6c545276aefc7ae70b5c7e0f1ec0b66460575e3386f8a4bbf7fd3704
publicKey copied from pk (see node code above)
java raises the exception:
Signature length not correct: got 768 but was expecting 512
Signature lenght not correct.
You're treating the signature as if it's base64-encoded, but it's not - it's just hex.
1024 characters represents 768 base64-encoded bytes, or 512 hex-encoded bytes.
Just decode using hex instead of base64 and it should be fine.
Hint that this is along the right lines, as well as observing that every character of your signature is a valid hex digit (which would be extremely unlikely if it's actually base64):
return signer.sign({
key: pvt_key,
passphrase: PASSPHRASE_KEY
},
'hex' // Note this use of 'hex'...
);
I am trying to take some working python code and convert it to java for my usage. The python code below produces the correct signature. The java code using the same key, salt, produces something different and I am at a loss for why. In the Java code I am using the key generated in python (_key) to create the signature.
What I don't understand is, if I print the value of _key in python I get "34ee7983-5ee6-4147-aa86-443ea062abf774493d6a-2a15-43fe-aace-e78566927585". Now if I take that and place it directly into the hmac(new) call I get a different result than if I just leave the _key variable. I assume this has something to do with encoding of some type but I am at a loss.
_s1 = base64.b64decode('VzeC4H4h+T2f0VI180nVX8x+Mb5HiTtGnKgH52Otj8ZCGDz9jRW'
'yHb6QXK0JskSiOgzQfwTY5xgLLSdUSreaLVMsVVWfxfa8Rw==')
_s2 = base64.b64decode('ZAPnhUkYwQ6y5DdQxWThbvhJHN8msQ1rqJw0ggKdufQjelrKuiG'
'GJI30aswkgCWTDyHkTGK9ynlqTkJ5L4CiGGUabGeo8M6JTQ==')
# bitwise and of _s1 and _s2 ascii, converted to string
_key = ''.join([chr(ord(c1) ^ ord(c2)) for (c1, c2) in zip(_s1, _s2)])
#classmethod
def get_signature(cls, song_id, salt=None):
"""Return a (sig, salt) pair for url signing."""
if salt is None:
salt = str(int(time.time() * 1000))
mac = hmac.new(cls._key, song_id, sha1)
mac.update(salt)
sig = base64.urlsafe_b64encode(mac.digest())[:-1]
return sig, salt
This is my Java code. I think ultimately my issue is how I am handling or encoding the AA_KEY but I cannot figure it out.
private static final String AA_KEY = "34ee7983-5ee6-4147-aa86-443ea062abf774493d6a-2a15-43fe-aace-e78566927585";
public void someFunc(String songId) {
salt = "1431875768596"
String sig = hmacSha1(songId + salt, AA_KEY);
sig = StringUtils.replaceChars(sig, "+/=", "-_.");
}
static String hmacSha1(String value, String key) {
try {
// Get an hmac_sha1 key from the raw key bytes
byte[] keyBytes = key.getBytes();
SecretKeySpec signingKey = new SecretKeySpec(keyBytes, "HmacSHA1");
// Get an hmac_sha1 Mac instance and initialize with the signing key
Mac mac = Mac.getInstance("HmacSHA1");
mac.init(signingKey);
// Compute the hmac on input data bytes
byte[] rawHmac = mac.doFinal(value.getBytes());
return Base64.encodeBytes(rawHmac);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
I found a couple of similar questions but they didn't help me figure it out sadly. Thanks!
Python HMAC-SHA256 signature differs from PHP signature
Python HMAC-SHA1 vs Java HMAC-SHA1 different results
I was asked to encrypt some text from client side ( web ) before sending it to server side ( java )
So i try to use CryptoJS library for client side.
I encrypt it like this :
var key = "aaaaaaaaaaaaaaaaaaaaaaaa";
var value = "KF169841";
var encryptedString = CryptoJS.TripleDES.encrypt(value, key);
console.log(encryptedString.toString());
And i get something like this : U2FsdGVkX19eYFFHgYGCr3v9/skTOKVp0pLWRNK9JTg=
I use this encryptedString and key in other Decrypt tool online ( Which also use CryptoJS ) and got back exact value KF169841.
After sending this value and key to server ( well key isn't sending directly to server though but for test, it is ), i need to decrypt it using Java.
But i quite don't know how to decrypt it. I'm tried some code from google search but it end up wrong padding if use DESese or get wrong value if i use ECB/NoPadding.
I did try to something like setting sfg for CryptoJS side like:
mode: CryptoJS.mode.EBC,
padding: CryptoJS.pad.NoPadding
But they got javascript exception ( a is not define )
So any have any experience with CryptoJS can help me decrypt this one using java ?
=============================================================
UPDATE : Sorry here my server side code i'm using
/**
* Method To Decrypt An Ecrypted String
*/
public String decrypt(String encryptedString, String myEncryptionKey) {
String decryptedText = null;
try {
byte[] keyAsBytes = myEncryptionKey.getBytes("UTF8");
KeySpec myKeySpec = new DESedeKeySpec(keyAsBytes);
SecretKeyFactory mySecretKeyFactory =
SecretKeyFactory.getInstance("DESede");
Cipher cipher = Cipher.getInstance("DESede/ECB/NoPadding");
SecretKey key = mySecretKeyFactory.generateSecret(myKeySpec);
cipher.init(Cipher.DECRYPT_MODE, key);
// BASE64Decoder base64decoder = new BASE64Decoder();
// byte[] encryptedText = base64decoder.decodeBuffer(encryptedString);
byte[] encryptedText = org.apache.commons.codec.binary.Base64.decodeBase64(encryptedString);
byte[] plainText = cipher.doFinal(encryptedText);
decryptedText= bytes2String(plainText);
} catch (Exception e) {
e.printStackTrace();
}
return decryptedText;
}
According to the documentation, your encryptedString variable contains structured data that must be split apart to be sent to Java code. You will need to send encryptedString.iv and encryptedString.ciphertext to your Java code. If you continue to use passwords (see below), you will need to send encryptedString.salt as well.
If you pass your key as a string it will be interpreted as a password and a key will be derived from it. If you actually want to pass an explicit key, follow the documentation and specify the IV and key as suggested by the code snippet below. If you stick with supplying a password, then you must figure out the derivation scheme and use the same process in your Java code.
// Code snippet from http://code.google.com/p/crypto-js/#Custom_Key_and_IV
<script src="http://crypto-js.googlecode.com/svn/tags/3.1.2/build/rollups/aes.js"></script>
<script>
var key = CryptoJS.enc.Hex.parse('000102030405060708090a0b0c0d0e0f');
var iv = CryptoJS.enc.Hex.parse('101112131415161718191a1b1c1d1e1f');
var encrypted = CryptoJS.AES.encrypt("Message", key, { iv: iv });
</script>
Regarding your Java code, it looks mostly OK (although there is plenty of room for error with string conversions). However, you probably want to convert your key from hex to binary rather than grabbing the bytes:
byte[] keyAsBytes = DatatypeConverter.parseHexBinary(myEncryptionKey);
This assumes you alter your JavaScript code to pass the literal key value.
You will also need to switch to DESede/CBC/PKCS5Padding and pass an IVParameterSpec object to your Cipher.init call, specifying the IV value sent from your Java Script code.
I'm having trouble doing the following in Java. Below is the Fantom code from the documentation for the the tool I am using.
// compute salted hmac
hmac := Buf().print("$username:$userSalt").hmac("SHA-1", password.toBuf).toBase64
// now compute login digest using nonce
digest := "${hmac}:${nonce}".toBuf.toDigest("SHA-1").toBase64
// our example variables
username: "jack"
password: "pass"
userSalt: "6s6Q5Rn0xZP0LPf89bNdv+65EmMUrTsey2fIhim/wKU="
nonce: "3da210bdb1163d0d41d3c516314cbd6e"
hmac: "IjJOApgvDoVDk9J6NiyWdktItl0="
digest: "t/nzXF3n0zzH4JhXtihT8FC1N3s="
I've been searching various examples through Google but none of them produce the results the documentation claims should be returned.
Can someone with Fantom knowledge verify if the example in the documentation is correct?
As for the Java side, here is my most recent attempt
public static String hmacSha1(String value, String key) {
try {
// Get an hmac_sha1 key from the raw key bytes
byte[] keyBytes = key.getBytes("UTF-8");
SecretKeySpec signingKey = new SecretKeySpec(keyBytes, "HmacSHA1");
// Get an hmac_sha1 Mac instance and initialize with the signing key
Mac mac = Mac.getInstance("HmacSHA1");
mac.init(signingKey);
// Compute the hmac on input data bytes
byte[] rawHmac = mac.doFinal(value.getBytes("UTF-8"));
// Convert raw bytes to Hex
byte[] hexBytes = new Hex().encode(rawHmac);
// Covert array of Hex bytes to a String
return new String(hexBytes, "UTF-8");
} catch (Exception e) {
throw new RuntimeException(e);
}
}
However, when I call the method with the following parameters
jack:6s6Q5Rn0xZP0LPf89bNdv+65EmMUrTsey2fIhim/wKU=
pass
I get
22324e02982f0e854393d27a362c96764b48b65d
Not sure where the docs came from - but they could be out-of-date - or wrong. I would actually run the Fantom code to use as your reference to make sure you're testing the right stuff ;)
You can take a look at the Java source for sys::Buf.hmac: MemBuf.java
I would also recommend separating out the 3 transformations. Make sure your raw byte array matches in both Fantom and Java, then verify the digest matches, and finally the Base64 encoding. Be alot easier to verify each stage in your code.
Turns out it was just my own lack of knowledge and with enough trial and error I was able to figure it out by doing the following:
//username: "jack"
//password: "pass"
//userSalt: "6s6Q5Rn0xZP0LPf89bNdv+65EmMUrTsey2fIhim/wKU="
//nonce: "3da210bdb1163d0d41d3c516314cbd6e"
//hmac: "IjJOApgvDoVDk9J6NiyWdktItl0="
//digest: "t/nzXF3n0zzH4JhXtihT8FC1N3s="
...
// initialize a Mac instance using a signing key from the password
SecretKeySpec signingKey = new SecretKeySpec(password.getBytes(), "HmacSHA1");
Mac mac = Mac.getInstance("HmacSHA1");
mac.init(signingKey);
// compute salted hmac
byte[] hmacByteArray = mac.doFinal((username + ':' + userSalt).getBytes());
String hmacString = new String(Base64.encodeBase64(hmacByteArray));
// hmacString == hmac
// now compute login digest using nonce
MessageDigest md = MessageDigest.getInstance("SHA-1");
md.update((hmacString + ':' + nonce).getBytes());
byte[] digestByteArray = md.digest();
String digestString = new String(Base64.encodeBase64(digestByteArray));
// digestString == digest
Used org.apache.commons.codec.binary.Base64 to encode the byte arrays.