How to verify ECC signature from android/java with python - java

I write code to sign string android using ECDSA algorithm.
Here is mycode:
String origin = txtChuoi.getText().toString();
try {
byte[] chuoiInput = origin.getBytes("UTF-8");
sig = Signature.getInstance("NONEwithECDSA","SC");
sig.initSign(privateKey);
sig.update(chuoiInput);
signatureBytes = sig.sign();
txtSign.setText(Base64.encodeToString(signatureBytes,Base64.DEFAULT));
} catch (Exception e) {
e.printStackTrace();
}
I can verify this sign string in same code app (using Java/Android). Here is my code:
String origin = txtChuoi.getText().toString();
try {
sig = Signature.getInstance("NONEwithECDSA","SC");
sig.initVerify(publicKey);
byte[] chuoiInput = origin.getBytes("UTF-8");
sig.update(chuoiInput);
txtVerify.setText(sig.verify(signatureBytes)+"");
} catch (Exception e) {
e.printStackTrace();
}
but not I want to verify it on my ubuntu server.
I have a trouble.
How can I implement verify code using python?
I cant write publickey code to pem file like this:
-----BEGIN PUBLIC KEY-----
MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEfUnusZsShxFLUuAwwAyFAkGCq3mBy98RXIkTP8YiTO3qmL8w6eMdMadiHfdCG2emktDrUwzNmTr9nMFCFhXdGQ==
-----END PUBLIC KEY-----
But how about the Signature? And I think (but not sure) it verify on bytes[].
How python do this?

Here's a similar question with the answer:
How to sign and verify signature with ecdsa in python
You'll need to prepare the public key for verification. The PEM file you mentioned has it base64 encoded.

Related

Translate Java string signing to OpenSSL

For a payment API I need to hash a string (a request payload) with SHA-512,
sign itwith "RSA" according to the documentation.
Hash the payload string (payout instruction) using SHA512 algorithm.
Sign the hashed payload string using RSA algorithm and the signing certificate private key.
Base64 encode the signed hash
Step 1 and 3 I've got no problems with. Step 2 is the problem. Support sent me a java example but we don't run java and I would like to do this in OpenSSL if at all possible.
private static String createSignature(String stringToBeSigned, PrivateKey privateKey) {
try {
byte[] hashString = hashString(stringToBeSigned);
Signature sign = Signature.getInstance("SHA512withRSA");
sign.initSign(privateKey);
sign.update(hashString);
byte[] signature = sign.sign();
return Base64.getEncoder().encodeToString(signature);
} catch (Exception e) {
throw new RuntimeException("Could not create signed payout request.", e);
}
}
private static byte[] hashString(String stringToBeHashed) {
try {
MessageDigest digest = MessageDigest.getInstance("SHA-512");
return digest.digest(stringToBeHashed.getBytes(StandardCharsets.UTF_8));
} catch (Exception e) {
throw new RuntimeException(e);
}
}
The Key is provided. How do I find what "SHA512withRSA" corresponds to using OpenSSL?

Problem decrypting a Java RSA/ECB/PKCS1Padding encrypted string in Swift

My iOS app needs to decrypt a string that was encrypted on a Java backend. The backend encrypts the string using these parameters: Cipher.getInstance("RSA/ECB/PKCS1Padding").
As a simple proof of concept, using OpenSSL from the Terminal I extracted the private key from the pfx certificate that they sent me:
$ openssl pkcs12 -in certificate.pfx -nocerts -out key.pem -nodes
$ openssl rsa -in key.pem -out server.key
Then, I hardcoded the private key as a String in my code and tried to decrypt the encrypted message using the SwiftyRSA lib:
import UIKit
import SwiftyRSA
class ViewController: UIViewController {
private let rsaPemPrivateKey = """
-----BEGIN RSA PRIVATE KEY-----
THE ACTUAL PRIVATE KEY...
-----END RSA PRIVATE KEY-----
"""
private let encryptedString = "ciSvTLKRAMqz8d8SEX8epvkyyrfAoiX28Sd1RhYbsz7oOg3/taXZxZkTeCbVeFXB8Mf8eWn2SGMcVIrmFGuxqyRoC5SluJDgrup0wcG/XRg7lrt7oD6esVBAGZT5nmS79mUoAC4CKW5cHclCh66JUysATSIvI9qrrXNUnBApGJc="
override func viewDidLoad() {
super.viewDidLoad()
do {
try decryptWithPrivateKey()
} catch {
print("Exception:")
print(error)
}
}
private func decryptWithPrivateKey() throws {
let privateKey = try PrivateKey(pemEncoded: rsaPemPrivateKey)
let encrypted = try EncryptedMessage(base64Encoded: encryptedString)
let clear = try encrypted.decrypted(with: privateKey, padding: SecPadding.PKCS1)
print("Decrypted string is: \(try clear.string(encoding: .utf8))")
}
}
This results in the following error, when the method encrypted.decrypted is called:
Exception:
chunkDecryptFailed(index: 0)
I also tried with other libraries, but similar errors occurred.
Here's the result with the SwiftRSA lib:
Exception:
decryptionFailed(error: Optional(Error Domain=NSOSStatusErrorDomain Code=-50 "RSAdecrypt wrong input (err -1)" UserInfo={NSDescription=RSAdecrypt wrong input (err -1)}))
And here's the result with the SwCrypt lib:
Exception:
decodeError
I'm not sure what could be wrong here. At first I thought the problem might be with the private key, but none of the libraries throw an exception when I instantiate their corresponding PrivateKey objects with it. Perhaps the problem is with the encrypted string I'm trying to decrypt, but it seems that no base64 decoding is required, as the EncryptedMessage object expects a base 64 encoded string anyway.
Is there anything else I can try to decrypt this RSA/ECB/PKCS1Padding encrypted string in Swift? (although in Java they pass ECB as the mode of operation, it looks like it don't actually use ECB under the hood, so I don't think I need to implement any custom management of the block size of the encrypted string as they say here).
-- Edit --
Here's a few other details as requested by zaitsman:
Dummy certificate's private key:
-----BEGIN RSA PRIVATE KEY-----
MIIEpAIBAAKCAQEAt+733lAMe2uhg3pLdhv///wuwYtlJNiRbC3xfz6y/9qkXoDn
3yKleJtw1JI7e1uZIN1h/bY4DUezSDuqio7VpHZ8VpnQ3pm9U87Fozpaqi/62hqM
MzQ7B7lWsrSUrcjgEDZAWehWLdMEZiRlgQL3IeUT8bh4YMMXL9a+3gf+dUHLge5J
FIVJ/3VjyPbRn/05KxPlUwxtkP5TIAMWsJkNbO38i+ymQ9GFhBuaV2rOC2WOV3eo
VMd7LqfIBhPdA/CDpYuo/ZxVPdY2OOdXTPX1JY2qKzoE4sqUrlwzuYaqLbGR6nU+
ZSMUVtivZN+fTCWS6HcmNvEmB14I5DTWJ5BjaQIDAQABAoIBABKS5SDkAH6uHb9D
KD+jEDTvaGFPDEWuQPElqo9o63Z+w75vUfrsar1FJR2yLqOEWnBBKtYOApcEuIwA
ynX3eoeDF4c/PSJdcAr4hGi5SdKJydEggSviiFt9Uc32AlWSRV4dvF3X4mv6NSWD
Y2SlwgMAOQVd1Xof+UVxcBDHyeBZOmFIVkvs+JKDKLAA+Gw6uCmQ+m2kUUtEAh7G
yPQdbqwYdi6vnyVOTRfoyC6J/fmRh0P3ZJtWEctGmlkGVVDt8qYHDwKrtACsbsXh
2dRkVOIUM4JclCK9vh/1xFpn9m+yaAI8c8XXLuN9ZyglDM9nmF6iPrf1n7DRDVRU
lRqO6okCgYEAv0+lTquO1S0RbCSzGCkKJ59JP12PknJQHC9zM6Psa0gd1LN3LYQ3
byEjCmJJhhAnBw95PuTF/B0ESa7nhSvAUazipc123gdTx/7V8raE0WlKZM89X6Vy
H4ZjvNikr/2S2WaNZWwPYNC5b2raOGZP5sEUpGBQz6M9UbZz42SZsN8CgYEA9iCy
DkhX1tzsKQhjRdXU9V/N5daXH65fto+qlpQMOcwIKDAe6DH36lugSR4gaQh+KtmR
nWX/58TM0iQWDIUMs3sbyBeESfCh3LEH42EN1M62BNC6F7A8pnLw8qfGeu+kfu5X
fAvqv0HgBJP4Duqdl30Ux9h4RqtGTyWiQaEnjLcCgYBDB3LR14YZ5sp963XcdzSZ
oVOWof9VvjuXRIDGjR6ekAvzpFWTWwnZI/EVCE7ea/ZgoOlIQfukU75W2rM/k460
jzByC0UkkcinAACSI6TxgkSQgZPtWRhdN0bmubkp+FxlU2sjJ/NTZo4yHWwL6r0A
CpJi7WQi+/zWDmkYOP0oXQKBgQDdC1weK6aH131ZFKljjLlnbZVTN7gdwdM/+CLy
fR/FwJIK1bzMOCQ5G/UF9cKR0gjNnvyB6Zs8oah5ieMrd0qC3quCtmweo7gapfs5
oG51kvgxtuuKXsL5kf0HUNqWiianwJJdW66F+jmgouuDKf5CkRlaqfTLMwNADcJ9
QqhsXQKBgQCJ4hUy3ptM6KUDG0oAT9s+cojVAmsCm5zITHkaFfkjP0W8srGXwrWx
63wLQCy84GOCFH3jecHSKHapq9V0laL+ARnepj6naO8ivMQFSucyAOeX7CfJAc45
BoezzHAqR1cnGn52G57ycqrX7eCHSULfIcYU7VwcqKJzxf1w+A+AVw==
-----END RSA PRIVATE KEY-----
Java code used to encrypt (the minimal reproducible example):
I asked the backend team for an example of the code they use to encript, and they sent me this Kotlin function:
fun String.encryptWithPublicKey(publicKey: String): String {
try {
val base64Decoder = Base64.getDecoder()
val decoded = base64Decoder.decode(publicKey.toByteArray(Charsets.UTF_8))
val key = RSAPublicKey.getInstance(decoded)
val keySpec = RSAPublicKeySpec(key.modulus, key.publicExponent)
val rsaKey = KeyFactory.getInstance("RSA").generatePublic(keySpec)
val cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding")
cipher.init(Cipher.ENCRYPT_MODE, rsaKey)
val encrypted = cipher.doFinal(this.toByteArray(Charsets.UTF_8))
return ByteString.of(encrypted, 0, encrypted.size).base64()
} catch (e: Exception) {
throw e
}
}
Sample encrypted string, b64 encoded:
Here's the base 64 encoded, encrypted string I get from the backend response:
ciSvTLKRAMqz8d8SEX8epvkyyrfAoiX28Sd1RhYbsz7oOg3/taXZxZkTeCbVeFXB8Mf8eWn2SGMcVIrmFGuxqyRoC5SluJDgrup0wcG/XRg7lrt7oD6esVBAGZT5nmS79mUoAC4CKW5cHclCh66JUysATSIvI9qrrXNUnBApGJc=
Sample raw value:
I don't have the exact value right now, but it should be a numeric value similar to this:
1234 5678 9012 3456

How to Reproduce Following JAVA Encryption into NODEJS Equivalent (Either Using node-rsa or crypto module)?

I have following java method where i need to convert into nodejs, the problems was the output from nodejs seems rather odd.
Here is my java code
private static final String SIGN_ALGORITHMS = "MD5WithRSA";
public static String sign(String content, String privateKey, String input_charset) {
try {
PKCS8EncodedKeySpec priPKCS8 = new PKCS8EncodedKeySpec(Base64.decode(privateKey));
KeyFactory keyf = KeyFactory.getInstance("RSA");
PrivateKey priKey = keyf.generatePrivate(priPKCS8);
java.security.Signature signature = java.security.Signature.getInstance(SIGN_ALGORITHMS);
signature.initSign(priKey);
signature.update(content.getBytes(input_charset));
byte[] signed = signature.sign();
return Base64.encode(signed);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
where:
content is just regular string to encrypt e.g: lorem ipsum,
privateKey is string representation of private key, and
input_charset is UTF-8
How do i get the value of Base64.encode(signed) in nodejs?
Just use NodeJS in built Crypto functions:
https://nodejs.org/dist/latest-v10.x/docs/api/crypto.html#crypto_crypto

JavaScript encryption based on Java generated RSA key

I'm trying to implement a solution for encryption between Java and JavaScript.
on the Java end I have the following static block:
public class Manager {
public static KeyPairGenerator keyPairGenerator;
public static KeyPair keyPair;
static{
try {
keyPairGenerator = KeyPairGenerator.getInstance("RSA");
keyPairGenerator.initialize(1024);
keyPair = keyPairGenerator.genKeyPair();
} catch (NoSuchAlgorithmException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
...
}
This basically generates a fresh KeyPair once my server is up and running...
then I give the public key in a JSON format:
<%
JSONObject json = new JSONObject();
json.put("publicKey", "-----BEGIN PUBLIC KEY-----" + Base64.encodeBase64URLSafeString(Manager.keyPair.getPublic().getEncoded()) + "-----END PUBLIC KEY-----");
%>
and I want to use that key (be it 1024 or 2048 bit) to encode information coming from client's forms...
anyone knows how can I encode the information using an RSA 1024 bit, base64 encoded public key?
I tried jCryption and severel other libraries to no avail...
If you don't send your public key as a certificate, you are better off just sending the modulus and the public exponent separately (e.g. base 64 encoded in separate fields). The default encoding will result in a X509 SubjectPublicKeyInfo ASN.1 structure, which you would need to parse in your JavaScript libraries.
Note that you are protecting only against eavesdroppers; man-in-the-middle attacks are still viable as they can replace your public key with their own. RSA 1024 is of course outdated by now. Fortunately you still have TLS/SSL to protect you.

SHA256withRSA sign from PHP verify from JAVA

For my current project I have to send a signature from PHP to Java application. I am using Crypt/RSA right now for signing my data.
For test I am signing just "abc" with following code :
$rsa = new Crypt_RSA();
$plaintext = 'abc';
$rsa->loadKey("MIICXgIBAAKBgQDjh+hNsqJe566JO0Sg7Iq5H1AdkauACdd8QMLp9YNY0HPslVH0
rXaOFo0zgH0Ktu/Ku3lS1lfxbFQAY8b6ywZKvu4eoxlnEwuBwy09CG+3ZiVLBjCj
TZHA/KOkpVLa+tA6KsoP6zv/xI/ACkSCxPGR0q3SiRuhXV/6tacoKxUYnwIDAQAB
AoGBAIC00GOjONYWmFRoglnFdHNjkx4m2KyE5LAUsi1GBBapU+nwTXvq47VcbGNF
u3XkJaC4i9igBv86GApgZp5XWia86On/Lz9NR4fB2EFP6Ydy84GfCDNNvkism4BR
aA+eYdNiQ3Wfyi98ZpUi+rPsoI6Cid4eSkCC4poTUaqzMkiBAkEA9Gn1oIlUEoVI
q/u5Y9vflXRDt95AA9AokJkQj7XTNjsz8ypU8TO6D6ZykpcbK6zjU0UJsQiC3dKj
AgmAR2VzYwJBAO5RETMAyDnR+5g+MtHpwGqGdY4dq0j4y4CsdtOYKWwSTh3VQy+C
eghJoyPRfIpulw2Mk/l+occEI0ohJl0+UJUCQQDSZtjVLwMZwnUx4EvSw/ewL9sP
0Jpo7evNtoaEQDEncUWiYeGnljDowg/FU6FHMtiq2TajmMEXdflvioBMdfAjAkEA
3TB60SbJr/i4Fo6sJm5ZO8W+eAALiTf50VzBERTqZTb8L+5PZFoqn2SROV5mxClu
o5G1idzBlHC/vD7WV7bNnQJAd0FrxaMBurJ4Uv/B8TDP+eeBdB7d9rKw0+TVlcel
cbpIz6BIP6+nmsgy6dbDRnx0eC/MgF2EU0wrCu1DK0PyWA==");
$rsa->setHash("sha256");
$signature = $rsa->sign($plaintext);
$signature_encoding = mb_convert_encoding($signature, "UTF-8");
error_log("signature encoded in UTF-8 :" . $signature_encoding);
$encoded_sign = base64_encode($signature_encoding);
error_log("encoded sign for abc: " . $encoded_sign);
I can verify the signature from php code. But when it comes to verifying from JAVA, i was not successfull. Here is the java code that does the verify operation :
public boolean verify(String signed, String data, PubKey pubKey) throws Exception{
PublicKey publicKey = jceProvider.generateRSAPublicKeyFromX509(
base64.decode(pubKey.getEncodedKey())
);
byte[] signature = base64.decode(signed);
byte[] verifier = data.getBytes(Charset.forName("UTF-8"));
return jceProvider.verify(signature, verifier, publicKey);
}
public class JCEProvider {
public boolean verify (byte[] signature, byte[] verifier, PublicKey publicKey) throws Exception{
Signature rsaSignature = Signature.getInstance("SHA256withRSA");
rsaSignature.initVerify(publicKey);
rsaSignature.update(verifier);
return rsaSignature.verify(signature);
}
I dont think it is because of keys, I can already verify it from PHP as I told before. There is something that I miss about PHP encoding or byte streams but I am lost for the moment.
Any help would be appreciated.
I'm using openssl like Whity already mentioned. Here is my striped down example. Be aware of any character encoding, line ending, etc. This results in changed binary representation of your text data.
PHP-RSA_SHA256-Sign:
<?php
$data = "For my current project I have to send a signature from PHP to Java application. I am using Crypt/RSA right now for signing my data.";
$private_key = <<<EOD
-----BEGIN RSA PRIVATE KEY-----
MIIBOgIBAAJBANDiE2+Xi/WnO+s120NiiJhNyIButVu6zxqlVzz0wy2j4kQVUC4Z
RZD80IY+4wIiX2YxKBZKGnd2TtPkcJ/ljkUCAwEAAQJAL151ZeMKHEU2c1qdRKS9
sTxCcc2pVwoAGVzRccNX16tfmCf8FjxuM3WmLdsPxYoHrwb1LFNxiNk1MXrxjH3R
6QIhAPB7edmcjH4bhMaJBztcbNE1VRCEi/bisAwiPPMq9/2nAiEA3lyc5+f6DEIJ
h1y6BWkdVULDSM+jpi1XiV/DevxuijMCIQCAEPGqHsF+4v7Jj+3HAgh9PU6otj2n
Y79nJtCYmvhoHwIgNDePaS4inApN7omp7WdXyhPZhBmulnGDYvEoGJN66d0CIHra
I2SvDkQ5CmrzkW5qPaE2oO7BSqAhRZxiYpZFb5CI
-----END RSA PRIVATE KEY-----
EOD;
$binary_signature = "";
$algo = "SHA256";
openssl_sign($data, $binary_signature, $private_key, $algo);
print(base64_encode($binary_signature) ."\n");
?>
The output of base64 encoded binary signature is:
OnqiWnFQ2nAjOa1S57Du9jDpVr4Wp2nLdMk2FX+/qX1+SAHpVsW1JvQYqQUDlxvbTOE9vg6dlU6i3omR7KipLw==
JAVA-RSA_SHA256-Verify:
import java.security.GeneralSecurityException;
import java.security.KeyFactory;
import java.security.PublicKey;
import java.security.Signature;
import java.security.spec.X509EncodedKeySpec;
import org.apache.commons.codec.binary.Base64;
public class RsaVerify {
public static void main(String args[]){
String publicKey =
// "-----BEGIN PUBLIC KEY-----"+
"MFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBANDiE2+Xi/WnO+s120NiiJhNyIButVu6"+
"zxqlVzz0wy2j4kQVUC4ZRZD80IY+4wIiX2YxKBZKGnd2TtPkcJ/ljkUCAwEAAQ==";
// "-----END PUBLIC KEY-----";
byte[] data = "For my current project I have to send a signature from PHP to Java application. I am using Crypt/RSA right now for signing my data.".getBytes();
byte[] signature = Base64.decodeBase64("OnqiWnFQ2nAjOa1S57Du9jDpVr4Wp2nLdMk2FX+/qX1+SAHpVsW1JvQYqQUDlxvbTOE9vg6dlU6i3omR7KipLw==");
try {
System.out.println(verify(data, signature, publicKey));
} catch (GeneralSecurityException e) {
e.printStackTrace();
}
}
private static boolean verify(byte[] data, byte[] signature, String publicKey) throws GeneralSecurityException{
X509EncodedKeySpec pubKeySpec = new X509EncodedKeySpec(Base64.decodeBase64(publicKey));
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
PublicKey pubKey = keyFactory.generatePublic(pubKeySpec);
Signature sig = Signature.getInstance("SHA256withRSA");
sig.initVerify(pubKey);
sig.update(data);
return sig.verify(signature);
}
}
phpseclib uses the more secure PSS padding by default. Java is probably using PKCS#1 padding. So if you were to go the phpseclib route (which I'd recommend doing)... do this:
$rsa->setSignatureMode(CRYPT_RSA_SIGNATURE_PKCS1);
I think u need to improve your PHP solution.
According to http://php.net/manual/en/function.openssl-get-md-methods.php you can use directly [47] => sha256WithRSAEncryption from PHP, probably call openssl from commandline also be possible:
openssl dgst -sha256 -sign my.key -out in.txt.sha256 in.txt

Categories