How to validate a public and private key pair in Java

前端 未结 2 1450
深忆病人
深忆病人 2021-02-09 07:30

Is there a way to validate in java if the given private key, say certain *.key file matches with the certain public key, to a certain .pub file using RSA algorithm?

2条回答
  •  既然无缘
    2021-02-09 07:42

    The answer that was marked as being correct wastes a lot of CPU cycles. This answer is waaaay more CPU efficient:

    KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
    keyGen.initialize(2048);
    
    KeyPair keyPair = keyGen.generateKeyPair();
    RSAPrivateCrtKey privateKey = (RSAPrivateCrtKey) keyPair.getPrivate();
    RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
    
    // comment this out to verify the behavior when the keys are different
    //keyPair = keyGen.generateKeyPair();
    //publicKey = (RSAPublicKey) keyPair.getPublic();
    
    boolean keyPairMatches = privateKey.getModulus().equals(publicKey.getModulus()) &&
        privateKey.getPublicExponent().equals(publicKey.getPublicExponent());
    

提交回复
热议问题