The output of tpm_getpubek is of the form:
http://trousers.sourceforge.net/man/tpm_getpubek.8.html
Key Size: 2048 bits
Public Key:
be262286 b51d0a21 88860ae7 32db7478 503c9213 bbb5545a 7e5d7c5f 30ff83da
37c5b548 fee21fd1 650181e8 3401a86b 1462e94e 118fc7f3 eb976b4c eb3a091f
6c5ea72c 527711dc ffbf1ae5 51fcbe1a aec95c64 7e2ac0eb 93484551 339f4959
6332b500 024cfe5c e08697cb 7431b3f4 328b4569 5e2e3eed 93a962d9 8387a58c
df15ecd1 9d01dd08 e2e60002 2baa6197 485dfbfc dd2f1898 fdff3913 7cc3bdc1
cc8bcb04 19e26ac8 466b6daf 4d53e9ea 88e45364 d029c1af b035a354 0f2e4484
e51bc0aa d216cdb6 71f50abb 44a0fdba 38715a6c 0c97d45d 5f3c08ab e7a46117
3666e6b0 d840ee54 4c617388 1714f0a1 acded3bd fc3ea323 8e7d1fcb 9fe74340
1) I am having a hard time to understand how to use it. I am trying to convert it to a java PublicKey object via the code:
byte[] derPublicKey = DatatypeConverter.parseHexBinary(keyBloc);
X509EncodedKeySpec x509publicKey = new X509EncodedKeySpec(derPublicKey);
KeyFactory factory = KeyFactory.getInstance("RSA");
PublicKey publicKey = factory.generatePublic(x509publicKey);
But this returns the following error:
java.security.spec.InvalidKeySpecException: java.security.InvalidKeyException: invalid key format
at sun.security.rsa.RSAKeyFactory.engineGeneratePublic(RSAKeyFactory.java:205)
[java] at java.security.KeyFactory.generatePublic(KeyFactory.java:334)
tpm_getpubek returns the hex-encoded public key modulus in its raw form, not an X509 encoded blob. Assuming you saved the returned data into a string called keyBlock (with whitespace removed) you would generate the public key like this:
PublicKey pk = KeyFactory.getInstance("RSA").generatePublic(
new RSAPublicKeySpec(new BigInteger(keyBlock, 16), new BigInteger("65537")));
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
Go generates a signature using a DSA private key
Java verifies first step result using the DSA public key
Java should return true, but returns false
package main
import (
"crypto/dsa"
"crypto/rand"
"encoding/asn1"
"encoding/hex"
"fmt"
"golang.org/x/crypto/ssh"
"math/big"
)
func main() {
// a dsa private key
pemData := []byte("-----BEGIN DSA PRIVATE KEY-----\n" +
"MIIBvAIBAAKBgQD9f1OBHXUSKVLfSpwu7OTn9hG3UjzvRADDHj+AtlEmaUVdQCJR\n" +
"+1k9jVj6v8X1ujD2y5tVbNeBO4AdNG/yZmC3a5lQpaSfn+gEexAiwk+7qdf+t8Yb\n" +
"+DtX58aophUPBPuD9tPFHsMCNVQTWhaRMvZ1864rYdcq7/IiAxmd0UgBxwIVAJdg\n" +
"UI8VIwvMspK5gqLrhAvwWBz1AoGBAPfhoIXWmz3ey7yrXDa4V7l5lK+7+jrqgvlX\n" +
"TAs9B4JnUVlXjrrUWU/mcQcQgYC0SRZxI+hMKBYTt88JMozIpuE8FnqLVHyNKOCj\n" +
"rh4rs6Z1kW6jfwv6ITVi8ftiegEkO8yk8b6oUZCJqIPf4VrlnwaSi2ZegHtVJWQB\n" +
"TDv+z0kqAoGBAIb9o0KPsjAdzjK571e1Mx7ZhEyJGrcxHiN2sW8IztEbqrKKiMxp\n" +
"NlTwm234uBdtzVHE3uDWZpfHPMIRmwBjCYDFRowWWVRdhdFXZlpCyp1gMWqJ11dh\n" +
"3FI3+O43DevRSyyuLRVCNQ1J3iVgwY5ndRpZU7n6y8DPH4/4EBT7KvnVAhR4Vwun\n" +
"Fhu/+4AGaVeMEa814I3dqg==\n" +
"-----END DSA PRIVATE KEY-----")
// parse dsa
p, _ := ssh.ParseRawPrivateKey(pemData)
pp := p.(*dsa.PrivateKey)
// orign data
hashed := []byte{1}
r, s, _ := dsa.Sign(rand.Reader, pp, hashed)
type dsaSignature struct {
R, S *big.Int
}
var ss dsaSignature
ss.S = s
ss.R = r
signatureBytes, _ := asn1.Marshal(ss)
// print sign
fmt.Println(hex.EncodeToString(signatureBytes))
}
Java reads the DSA public key and initialize a signer
Java verify first step sign result
returns false
#Test
public void ttt() throws InvalidKeySpecException, NoSuchAlgorithmException, InvalidKeyException, SignatureException {
// DSA public key
String pubKey = "-----BEGIN PUBLIC KEY-----\n" +
"MIIBuDCCASwGByqGSM44BAEwggEfAoGBAP1/U4EddRIpUt9KnC7s5Of2EbdSPO9E\n" +
"AMMeP4C2USZpRV1AIlH7WT2NWPq/xfW6MPbLm1Vs14E7gB00b/JmYLdrmVClpJ+f\n" +
"6AR7ECLCT7up1/63xhv4O1fnxqimFQ8E+4P208UewwI1VBNaFpEy9nXzrith1yrv\n" +
"8iIDGZ3RSAHHAhUAl2BQjxUjC8yykrmCouuEC/BYHPUCgYEA9+GghdabPd7LvKtc\n" +
"NrhXuXmUr7v6OuqC+VdMCz0HgmdRWVeOutRZT+ZxBxCBgLRJFnEj6EwoFhO3zwky\n" +
"jMim4TwWeotUfI0o4KOuHiuzpnWRbqN/C/ohNWLx+2J6ASQ7zKTxvqhRkImog9/h\n" +
"WuWfBpKLZl6Ae1UlZAFMO/7PSSoDgYUAAoGBAIb9o0KPsjAdzjK571e1Mx7ZhEyJ\n" +
"GrcxHiN2sW8IztEbqrKKiMxpNlTwm234uBdtzVHE3uDWZpfHPMIRmwBjCYDFRowW\n" +
"WVRdhdFXZlpCyp1gMWqJ11dh3FI3+O43DevRSyyuLRVCNQ1J3iVgwY5ndRpZU7n6\n" +
"y8DPH4/4EBT7KvnV\n" +
"-----END PUBLIC KEY-----";
String publicKeyPEM = pubKey
.replace("-----BEGIN PUBLIC KEY-----\n", "")
.replaceAll(System.lineSeparator(), "")
.replace("-----END PUBLIC KEY-----", "");
byte[] publicEncoded = Base64.decodeBase64(publicKeyPEM);
KeyFactory keyFactory1 = KeyFactory.getInstance("DSA");
X509EncodedKeySpec publicKeySpec = new X509EncodedKeySpec(publicEncoded);
DSAPublicKey pubKeyy = (DSAPublicKey) keyFactory1.generatePublic(publicKeySpec);
// init signer
Signature sig1 = Signature.getInstance("DSA");
sig1.initVerify(pubKeyy);
sig1.update(new byte[]{1});
// verify first result
System.out.println(sig1.verify(HexUtil.decodeHex("first step result")));
}
i tred to use NONEwithDSA within the Java implementation but it didnt do it
Signature sig1 = Signature.getInstance("NONEwithDSA");
java.security.SignatureException: Data for RawDSA must be exactly 20 bytes long
i tred to use SHA1withDSA within the Java implementation but it didnt do it
Signature sig1 = Signature.getInstance("SHA1withDSA");
returns false
In Java the (Signature) algorithm name DSA is an alias for SHA1withDSA, i.e. the original FIPS186-0 algorithm. This is not the same as the nonstandard 'raw' primitive apparently implemented by Go. NONEwithDSA is indeed the correct Java name for what you want, but the implementation in the 'standard' (SUN) provider is something of a kludge that requires exactly 20 bytes of data, not more or less, because that was the size of the SHA1 hash which was the only standard hash for DSA prior to FIPS186-3.
If you (have or can get and) use the BouncyCastle provider, it does not have this restriction, and should work for your code changed to NONEwithDSA (and either the code or security config modified so that BC is selected as the provider, of course).
If you don't use Bouncy, I think you'll have to code the algorithm yourself; I don't think there's any way to get the SUN implementation to do what you want.
Although it would be better to sign a properly-sized hash as specified in the standard, not raw data, and then you could use the Java providers as specified and designed.
I have been trying to solve this issue regarding AndroidKeyStore. My app seems to not getting Android native provider for NONEwithRSA signing algorithm. This is the code reference:
Calendar startDate = Calendar.getInstance();
Calendar endDate = Calendar.getInstance();
endDate.add(Calendar.YEAR, 30);
KeyPairGeneratorSpec keyPairGeneratorSpec = new KeyPairGeneratorSpec.Builder(context)
.setAlias("aliasName")
.setSubject(new X500Principal("CN=aliasName"))
.setSerialNumber(BigInteger.TEN)
.setStartDate(startDate.getTime())
.setEndDate(endDate.getTime())
.build();
KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA", "AndroidKeyStore");
keyPairGenerator.initialize(keyPairGeneratorSpec);
keyPairGenerator.generateKeyPair();
Once generateKeyPair() gets called, I got the following exception stack trace.
Caused by: java.security.SignatureException: java.security.ProviderException: No provider for NONEwithRSA
at com.google.android.gms.org.conscrypt.OpenSSLSignature.engineSign(:com.google.android.gms#12673012#12.6.73 (020408-194189626):6)
at java.security.Signature$SignatureImpl.engineSign(Signature.java:672)
at java.security.Signature.sign(Signature.java:381)
at com.android.org.bouncycastle.x509.X509Util.calculateSignature(X509Util.java:248)
at com.android.org.bouncycastle.x509.X509V3CertificateGenerator.generate(X509V3CertificateGenerator.java:434)
at com.android.org.bouncycastle.x509.X509V3CertificateGenerator.generate(X509V3CertificateGenerator.java:412)
at android.security.AndroidKeyPairGenerator.generateKeyPair(AndroidKeyPairGenerator.java:133)
... 26 more
Caused by: java.security.ProviderException: No provider for NONEwithRSA
at java.security.Signature$SignatureImpl.getSpi(Signature.java:734)
at java.security.Signature$SignatureImpl.engineInitSign(Signature.java:692)
at java.security.Signature.initSign(Signature.java:343)
at com.google.android.gms.org.conscrypt.CryptoUpcalls.rawSignDigestWithPrivateKey(:com.google.android.gms#12673012#12.6.73 (020408-194189626):11)
at com.google.android.gms.org.conscrypt.NativeCrypto.EVP_DigestSignFinal(Native Method)
at com.google.android.gms.org.conscrypt.OpenSSLSignature.engineSign(:com.google.android.gms#12673012#12.6.73 (020408-194189626):2)
... 32 more
No solution is found related to my issue. Does anyone have any idea on how to solve this?
You can replace the line with
KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA", "AndroidKeyStore");
As it is showing in logs that No provider for NONEwithRSA
Updated
You can try the below code for generating key pair in Androidkeystore and android version should be greater than 18
KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA", "AndroidKeyStore");
// generator.initialize(spec);
generator.initialize(new KeyGenParameterSpec.Builder(
alias ,
KeyProperties.PURPOSE_SIGN | KeyProperties.PURPOSE_VERIFY)
.setDigests(KeyProperties.DIGEST_SHA256,
KeyProperties.DIGEST_SHA512)
.setCertificateSubject(new X500Principal("CN=aliasName" ))
.setCertificateNotBefore(start.getTime())
.setCertificateNotAfter(end.getTime())
.setCertificateSerialNumber(BigInteger.ONE)
.setSignaturePaddings(KeyProperties.SIGNATURE_PADDING_RSA_PKCS1)
.build());
KeyPair keyPair = generator.generateKeyPair();
Is there a Java library/example to read an openssh format ecdsa public key to a JCE PublicKey in Java? I want to use EC for JWT .
The format I'm trying to read is as per authorized_keys, or Github API (e.g. https://api.github.com/users/davidcarboni/keys): ecdsa-sha2-nistp256 AAAAE2VjZHNhLXNoYTItbmlzdHAyNTYAAAAIbmlzdHAyNTYAAABBBK8hPtB72/sfYgNw1WTska2DNOJFx+QhUxuV6OLINSD2ty+6gxcM8yZrvMqWdMePGRb2cGh8L/0bGOk+64IQ/pM=
I've found this answer, which is fine for RSA and DSS:
Using public key from authorized_keys with Java security, and this discussion of the openssh format for ECDSA: https://security.stackexchange.com/questions/129910/ecdsa-why-do-ssh-keygen-and-java-generated-public-keys-have-different-sizes
However I'm getting lost trying to adapt the RSS/DSA code for ECDSA - I'm not sure how to set up an ECPublicKeySpec. It needs ECPoint, EllipticCurve, ECParameterSpec, ECField. The openssh format only contains two integers, which makes sense for ECPoint, but I don't know how to set up the rest.
I've been poking around a bunch of libraries, including jsch, sshj, ssh-tools and good old Bouncycastle. The closest I have is:
com.jcraft.jsch.KeyPair load = com.jcraft.jsch.KeyPair.load(jsch, null, bytes[openSshKey]);
Which loads the key fine, but doesn't get me to a JCE PublicKey - just a byte[] getPublicKeyBlob() method.
Am I missing something obvious?
I've found a way to do this using Bouncycastle (but would like to find a JCE way).
Adapting the code from Using public key from authorized_keys with Java security, and refering to RFC 5656, section 3.1, the following block added to decodePublicKey will parse the single BigInt value Q, which is "the public key encoded from an elliptic curve point":
if (type.startsWith("ecdsa-sha2-") &&
(type.endsWith("nistp256") || type.endsWith("nistp384") || type.endsWith("nistp521"))) {
// Based on RFC 5656, section 3.1 (https://www.rfc-editor.org/rfc/rfc5656#section-3.1)
// The string [identifier] is the identifier of the elliptic curve
// domain parameters. The format of this string is specified in
// Section 6.1 (https://www.rfc-editor.org/rfc/rfc5656#section-6.1).
// Information on the REQUIRED and RECOMMENDED sets of
// elliptic curve domain parameters for use with this algorithm can be
// found in Section 10 (https://www.rfc-editor.org/rfc/rfc5656#section-10).
String identifier = decodeType();
if (!type.endsWith(identifier)) {
throw new IllegalArgumentException("Invalid identifier " + identifier + " for key type " + type + ".");
}
// Q is the public key encoded from an elliptic curve point into an
// octet string as defined in Section 2.3.3 of [SEC1];
// (https://www.rfc-editor.org/rfc/rfc5656#ref-SEC1)
// point compression MAY be used.
BigInteger q = decodeBigInt();
ECPublicKey keyBC = getKeyBC(q, identifier);
return keyBC;
}
The solution I've found for getting from Q to an ECPublicKey is the following, using the Bouncycastle API (credit to Generate ECPublicKey from ECPrivateKey for providing the starting point):
ECPublicKey getKeyBC(BigInteger q, String identifier) {
// https://stackoverflow.com/questions/42639620/generate-ecpublickey-from-ecprivatekey
try {
// This only works with the Bouncycastle library:
Security.addProvider(new BouncyCastleProvider());
// http://www.bouncycastle.org/wiki/pages/viewpage.action?pageId=362269#SupportedCurves(ECDSAandECGOST)-NIST(aliasesforSECcurves)
String name = identifier.replace("nist", "sec") + "r1";
KeyFactory keyFactory = KeyFactory.getInstance("ECDSA", "BC");
ECNamedCurveParameterSpec ecSpec = ECNamedCurveTable.getParameterSpec(name);
ECPoint point = ecSpec.getCurve().decodePoint(q.toByteArray());
ECPublicKeySpec pubSpec = new ECPublicKeySpec(point, ecSpec);
ECPublicKey publicKey = (ECPublicKey) keyFactory.generatePublic(pubSpec);
return publicKey;
} catch (NoSuchAlgorithmException | InvalidKeySpecException | NoSuchProviderException e) {
throw new RuntimeException(e);
}
}
That gets you from an openssh format elliptic curve public key (ssh-keygen -t ecdsa -b [256|384|521]) to a JCE ECPublicKey.
For completeness, here's the code I've gone with. It's nearly-pure JCE, with a sprinkling of Bouncycastle inside helper methods (this updates the example code in Using public key from authorized_keys with Java security):
...
} else if (type.startsWith("ecdsa-sha2-") &&
(type.endsWith("nistp256") || type.endsWith("nistp384") || type.endsWith("nistp521"))) {
// Based on RFC 5656, section 3.1 (https://tools.ietf.org/html/rfc5656#section-3.1)
String identifier = decodeType();
BigInteger q = decodeBigInt();
ECPoint ecPoint = getECPoint(q, identifier);
ECParameterSpec ecParameterSpec = getECParameterSpec(identifier);
ECPublicKeySpec spec = new ECPublicKeySpec(ecPoint, ecParameterSpec);
return KeyFactory.getInstance("EC").generatePublic(spec);
} ...
/**
* Provides a means to get from a parsed Q value to the X and Y point values.
* that can be used to create and ECPoint compatible with ECPublicKeySpec.
*
* #param q According to RFC 5656:
* "Q is the public key encoded from an elliptic curve point into an octet string"
* #param identifier According to RFC 5656:
* "The string [identifier] is the identifier of the elliptic curve domain parameters."
* #return An ECPoint suitable for creating a JCE ECPublicKeySpec.
*/
ECPoint getECPoint(BigInteger q, String identifier) {
String name = identifier.replace("nist", "sec") + "r1";
ECNamedCurveParameterSpec ecSpec = ECNamedCurveTable.getParameterSpec(name);
org.bouncycastle.math.ec.ECPoint point = ecSpec.getCurve().decodePoint(q.toByteArray());
BigInteger x = point.getAffineXCoord().toBigInteger();
BigInteger y = point.getAffineYCoord().toBigInteger();
System.out.println("BC x = " + x);
System.out.println("BC y = " + y);
return new ECPoint(x, y);
}
/**
* Gets the curve parameters for the given key type identifier.
*
* #param identifier According to RFC 5656:
* "The string [identifier] is the identifier of the elliptic curve domain parameters."
* #return An ECParameterSpec suitable for creating a JCE ECPublicKeySpec.
*/
ECParameterSpec getECParameterSpec(String identifier) {
try {
// http://www.bouncycastle.org/wiki/pages/viewpage.action?pageId=362269#SupportedCurves(ECDSAandECGOST)-NIST(aliasesforSECcurves)
String name = identifier.replace("nist", "sec") + "r1";
AlgorithmParameters parameters = AlgorithmParameters.getInstance("EC");
parameters.init(new ECGenParameterSpec(name));
return parameters.getParameterSpec(ECParameterSpec.class);
} catch (InvalidParameterSpecException | NoSuchAlgorithmException e) {
throw new IllegalArgumentException("Unable to get parameter spec for identifier " + identifier, e);
}
}
I got a rsa primary key from an android app, but I don't know how to use it in python.
in java code:
public class RSAHelper
{
public static String decrypt(String paramString)
throws Exception
{
return new String(RSAUtils.decryptByPrivateKey(Base64Utils.decode(paramString), "MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBAIrrUGxh+yvNNI1c9hUg1rH+EtipI0nPk3zRm2Cj4mLDWLJ6DaTzdJTXTF3BYZaancWeG3QtBL+fITUi72InwBP7zaNG8uv/guwuhWT6V/YO7AaTrOFeTkg9NXuaFbn3hWVtZxQm2tIlaVa8snoNj3VGnPqIjXmGcxk4axuYd7sTAgMBAAECgYA43YhnRVh2nqJzd2k4Tt/zrmhyjhHm5fSetIKg9ZT3DrXhITsymYHQZ61X95AGATayLT1Zug/mjLIgOTO6f0ENkRQtjVCmKd8Yf/BeDEc5kRLUYDfSqoEydHK0+rCw5tJMgrAnQc5lHc+FVdGe2bOxKTEtZoss9VQ2jYuQ+Z5fUQJBANnvDOcI2OYSksX3PpHzO9F272xkmqYBRGkMc/a5RuOv1CY6FqMIkkloTf6nVl9y6XYV8gnHfbbI/wj4Q4UnPYsCQQCjLxyRYaOeEb/qOzSmFXytgMuCM9sr4eY9jpjzDgNWhpbtaVaf1QvSTXqN0zaUu4Se2tmWGX7zXw9p/dFf8DmZAkEAzl1o0FU2XhZ0WXVYEIhMunpvGSrirhNBHmAmZxjmoa/bqh8TVGpHa6+TO3JlfZioraL2QIBg8Ha/2VSNS0bvJQJALfCLaFpGh6+TicuVLNSLvwStRkB3CUmVWesVIAfn5KoLP1cSbfi6VUA+qkK18PVBhr8x1lHjLXyriDlOgmXMsQJAW9vD/IoBs4QJF87xF7tZvu/b1KRVgLM1edqOgVwMNbIQHBAXghjVjrpuln5w6z1dJ2cEjRP98OxKC0hqEIwIuQ=="), Charset.defaultCharset());
}
public static String encrypt(String paramString)
throws Exception
{
return Base64Utils.encode(RSAUtils.encryptByPrivateKey(paramString.getBytes(), "MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBAIrrUGxh+yvNNI1c9hUg1rH+EtipI0nPk3zRm2Cj4mLDWLJ6DaTzdJTXTF3BYZaancWeG3QtBL+fITUi72InwBP7zaNG8uv/guwuhWT6V/YO7AaTrOFeTkg9NXuaFbn3hWVtZxQm2tIlaVa8snoNj3VGnPqIjXmGcxk4axuYd7sTAgMBAAECgYA43YhnRVh2nqJzd2k4Tt/zrmhyjhHm5fSetIKg9ZT3DrXhITsymYHQZ61X95AGATayLT1Zug/mjLIgOTO6f0ENkRQtjVCmKd8Yf/BeDEc5kRLUYDfSqoEydHK0+rCw5tJMgrAnQc5lHc+FVdGe2bOxKTEtZoss9VQ2jYuQ+Z5fUQJBANnvDOcI2OYSksX3PpHzO9F272xkmqYBRGkMc/a5RuOv1CY6FqMIkkloTf6nVl9y6XYV8gnHfbbI/wj4Q4UnPYsCQQCjLxyRYaOeEb/qOzSmFXytgMuCM9sr4eY9jpjzDgNWhpbtaVaf1QvSTXqN0zaUu4Se2tmWGX7zXw9p/dFf8DmZAkEAzl1o0FU2XhZ0WXVYEIhMunpvGSrirhNBHmAmZxjmoa/bqh8TVGpHa6+TO3JlfZioraL2QIBg8Ha/2VSNS0bvJQJALfCLaFpGh6+TicuVLNSLvwStRkB3CUmVWesVIAfn5KoLP1cSbfi6VUA+qkK18PVBhr8x1lHjLXyriDlOgmXMsQJAW9vD/IoBs4QJF87xF7tZvu/b1KRVgLM1edqOgVwMNbIQHBAXghjVjrpuln5w6z1dJ2cEjRP98OxKC0hqEIwIuQ=="));
}
}
I try in python:
key = "MIICdgIBADANBgkqhkiG9w0BAQEFA..."
rsa.PrivateKey.load_pkcs1(key)
but I got:
ValueError: No PEM start marker "b'-----BEGIN RSA PRIVATE KEY-----'" found
how can I load this string primary key using python rsa module?
add BEGIN and END
In [109]: key
Out[109]: '-----BEGIN RSA PRIVATE KEY-----\nMIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBAIrrUGxh+yvNNI1c9hUg1rH+Etip I0nPk3zRm2Cj4mLDWLJ6DaTzdJTXTF3BYZaancWeG3QtBL+fITUi72InwBP7zaNG8uv/guwuhWT6V/YO7AaTrOFeTkg9NXuaFbn3hWVtZxQm2tIlaVa8snoN j3VGnPqIjXmGcxk4axuYd7sTAgMBAAECgYA43YhnRVh2nqJzd2k4Tt/zrmhyjhHm5fSetIKg9ZT3DrXhITsymYHQZ61X95AGATayLT1Zug/mjLIgOTO6f0EN kRQtjVCmKd8Yf/BeDEc5kRLUYDfSqoEydHK0+rCw5tJMgrAnQc5lHc+FVdGe2bOxKTEtZoss9VQ2jYuQ+Z5fUQJBANnvDOcI2OYSksX3PpHzO9F272xkmqYB RGkMc/a5RuOv1CY6FqMIkkloTf6nVl9y6XYV8gnHfbbI/wj4Q4UnPYsCQQCjLxyRYaOeEb/qOzSmFXytgMuCM9sr4eY9jpjzDgNWhpbtaVaf1QvSTXqN0zaU u4Se2tmWGX7zXw9p/dFf8DmZAkEAzl1o0FU2XhZ0WXVYEIhMunpvGSrirhNBHmAmZxjmoa/bqh8TVGpHa6+TO3JlfZioraL2QIBg8Ha/2VSNS0bvJQJALfCL aFpGh6+TicuVLNSLvwStRkB3CUmVWesVIAfn5KoLP1cSbfi6VUA+qkK18PVBhr8x1lHjLXyriDlOgmXMsQJAW9vD/IoBs4QJF87xF7tZvu/b1KRVgLM1edqO gVwMNbIQHBAXghjVjrpuln5w6z1dJ2cEjRP98OxKC0hqEIwIuQ==\n-----END RSA PRIVATE KEY-----'
In [110]: rsa.PrivateKey.load_pkcs1(key)
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-110-0a0425032302> in <module>()
----> 1 rsa.PrivateKey.load_pkcs1(key)
c:\users\winside824\appdata\local\programs\python\python35-32\lib\site-packages\rsa\key.py in load_pkcs1(cls, keyfile, f ormat)
73
74 method = cls._assert_format_exists(format, methods)
---> 75 return method(keyfile)
76
77 #staticmethod
c:\users\winside824\appdata\local\programs\python\python35-32\lib\site-packages\rsa\key.py in _load_pkcs1_pem(cls, keyfi le)
509
510 der = rsa.pem.load_pem(keyfile, b('RSA PRIVATE KEY'))
--> 511 return cls._load_pkcs1_der(der)
512
513 def _save_pkcs1_pem(self):
c:\users\winside824\appdata\local\programs\python\python35-32\lib\site-packages\rsa\key.py in _load_pkcs1_der(cls, keyfi le)
457 raise ValueError('Unable to read this file, version %s != 0' % priv[0])
458
--> 459 as_ints = tuple(int(x) for x in priv[1:9])
460 return cls(*as_ints)
461
c:\users\winside824\appdata\local\programs\python\python35-32\lib\site-packages\rsa\key.py in <genexpr>(.0)
457 raise ValueError('Unable to read this file, version %s != 0' % priv[0])
458
--> 459 as_ints = tuple(int(x) for x in priv[1:9])
460 return cls(*as_ints)
461
TypeError: int() argument must be a string, a bytes-like object or a number, not 'Sequence'
solve:
from Crypto.PublicKey import RSA
from Crypto.Cipher import PKCS1_v1_5
from base64 import b64decode
key = "MIICdgIBADANBgkqhkiG9w0BAQEFA..."
msg = "plain text"
key = b64decode(key)
private_key = RSA.importKey(key)
cipher = PKCS1_v1_5.new(private_key)
cipher.encrypt(msg)
rsa.PrivateKey.load_pkcs1 uses the PEM format by default.
As such it requires the key to begin with '-----BEGIN RSA PRIVATE KEY-----\n and end with
'\n-----END RSA PRIVATE KEY-----'.
try
pem_prefix = '-----BEGIN RSA PRIVATE KEY-----\n'
pem_suffix = '\n-----END RSA PRIVATE KEY-----'
key = "MIICdgIBADANBgkqhkiG9w0BAQEFA..."
key = '{}{}{}'.format(pem_prefix, key, pem_suffix)
rsa.PrivateKey.load_pkcs1(key)
Since a few days I've got a problem that I can't solve on my own:
On a JavaCard I generate a RSA KeyPair (length: 1024) and a signature (Mode:ALG_RSA_MD5_PKCS1).
Now I have to verify the signature in php.
From my JavaCard I get the exponent, modulus and the signature in hexadecimal:
$mod = '951ADDA04637190B6202BB52787D3C19160A383C80C2E7242D0A7850FDD80C1CD1CCCF1395F8CA0B20270E3BC6C86F78232D65D148258BEFD0884563C60AB2C327506FB4FA0095CF0B1C527D942155731451F790EC0A227D38613C9EBFB2E04A657B3BA5456B35F71E92E14B7E1CB38DB6572559BFCA3B0AD8AA061D48F68931';
$exp = '010001';
$sign ='75867D42BDE6DF1066D4AF69418FCDD4B0F19173141128DFEBC64AF6C014CB92D38F4824E52BB064A610E07C7783AE57AE993A792F15208FB199CB1F45B64623AACB7FBA07AD89513C8DBA893C9FA6939857AA2CA53AAD99D9A9C1C32DF4E2769FCACB72E2C2C495727D368D953A911D32E79E230751202714DD15C0B6A34782';
$plaintext = '01020304';
A Verification in Java is no problem. But know I have to verify the signature in PHP (I take phpseclib).
In PHP I generate my public_key with CRYPT_RSA_PUBLIC_FORMAT_RAW:
$rsa = new Crypt_RSA();
$pk = array(
'e' => new Math_BigInteger($exp, 16),
'n' => new Math_BigInteger($mod, 16)
);
$rsa->loadKey($pk, CRYPT_RSA_PUBLIC_FORMAT_RAW);
$rsa->setSignatureMode(CRYPT_RSA_SIGNATURE_PKCS1);
echo $rsa->verify($plaintext, $sign) ? 'verified' : 'unverified';
The problem know is to set the correct values in the function verify.
If I just set my signature in hexadecimal I get the notice:
Invalid signature: length = 256, k = 128 in C:\xampp\php\PEAR\Crypt\RSA.php on line 2175
So I have to customize the length of my signature:
$sign_bigInteger = new Math_BigInteger($sign, 16);
$sign_bytes = $sign_bigInteger->toBytes();
echo $rsa->verify($plaintext, $sign_bytes) ? 'verified' : 'unverified';
But the verification is false.
I get the output of the verification function in RSA.php (_rsassa_pkcs1_v1_5_verify) where plaintext is compared with the signature :
//sign
"ÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿ0 0*†H†÷ ÖÀZ!Q*y¡ßë*&/"
//plaintext
"ÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿ0!0 +•q£îê“O•äQ».åüÓSœÝ["
I don't really understand whats happening in the Class RSA.php.
Can anyone help me and say what I do wrong?
EDIT:
Now I tried to convert my hexString.
$plaintext_bin = pack("H*", $plaintext);
$sign_bin = pack("H*", $sign);
I think that my public key is correct generated, so I just change the input of my verify:
$rsa->verify($plaintext_bin, $sign_bin) ? 'verified' : 'unverified';
Output:
em: string(128) "ÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿ0 0*†H†÷ ÖÀZ!Q*y¡ßë*&/"
em2: string(128) "ÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿ0!0 +ÚÚÿMG‡ã31G ,;D>7o"
It's still not the same.
EDIT:
I fixed my problem. I forgot to set the Hash:
$rsa1->setHash('md5');
Now it works!
Thank you GregS.
All your values are hex strings. Just convert them using hex2bin() or pack("H*", $hex_string);