Given two SSH2 keys, how can I verify that they belong to the same key pair in Java?

I am trying to find a way to verify that two SSH2 keys, one private and one public, belong to the same key pair. I used JSch to load and parse the private key.

Update. Solving the problem can cause a fragment that can show how to recover the public key from the private key (SSH2 RSA).

+4
source share
4 answers

You can do this using the BouncyCastle lite API.

For instance:

InputStream in = new FileInputStream("path/to/private/key"); AsymmetricKeyParameter privateKey = PrivateKeyFactory.createKey(in); RSAPrivateCrtKeyParameters rsaPrivateKey = (RSAPrivateCrtKeyParameters)privateKey; BigInteger modulus = rsaPrivateKey.getModulus(); BigInteger publicExponent = rsaPrivateKey.getPublicExponent(); RSAKeyParameters publicKeyParams = new RSAKeyParameters(false, modulus, publicExponent); 

The RSAKeyParameters class represents a valid key.

Hope this helps!

+8
source

Perhaps this is what you are looking for: How do you test a DSA public / private key pair?

Update: for a clean Java solution, take a look at the standardized Java Cryptography Extension (JCE): http://download.oracle.com/javase/1.4.2/docs/guide/security/jce/JCERefGuide.html#KeyGenerator

Update 2: here is a sample code from RSA (a method called "go" generates a key pair): http://www.rsa.com/products/bsafe/documentation/cryptoj35html/doc/dev_guide/group__CJ__SAMPLES__RSANOPAD__JCE.html

Update 3: And here is the link related to parsing the public key for JCE: How do we convert String from PEM to DER format

+1
source

I wrote this usage method using Java security (plain J2SE):

 public static boolean validateRSAKeyPair(RSAPrivateCrtKey privateKey, RSAPublicKey publicKey) { BigInteger n = publicKey.getModulus(); BigInteger e = publicKey.getPublicExponent(); BigInteger d = privateKey.getPrivateExponent(); BigInteger p = privateKey.getPrimeP(); BigInteger q = privateKey.getPrimeQ(); BigInteger pq = p.multiply(q);//shold equal to n BigInteger eulerMod = p.add(NEGATIVE_ONE).multiply(q.add(NEGATIVE_ONE));// φ(n)=(p-1)*(q-1) BigInteger mod = d.multiply(e).mod(eulerMod);// (d*e) mod φ(n), should be 1 return n.equals(pq) && BigInteger.ONE.equals(mod); } 

It checks the RSA key pair against the parameters of the RSA algorithm.

+1
source

I know, cheating, but you can trigger a process like:

 ssh-keygen -f ~/.ssh/id_rsa -y > ~/.ssh/id_rsa.pub 

Cm. .

0
source

All Articles