Example usage for java.security.interfaces RSAPrivateKey getModulus

List of usage examples for java.security.interfaces RSAPrivateKey getModulus

Introduction

In this page you can find the example usage for java.security.interfaces RSAPrivateKey getModulus.

Prototype

public BigInteger getModulus();

Source Link

Document

Returns the modulus.

Usage

From source file:org.kaaproject.kaa.common.endpoint.security.KeyUtil.java

/**
 * Validates RSA public and private key.
 *
 * @param keyPair the keypair/*from   ww w  . java  2  s . c  om*/
 * @return true if keys matches
 */
public static boolean validateKeyPair(KeyPair keyPair) {
    RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
    RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();

    if (publicKey.getModulus().bitLength() != privateKey.getModulus().bitLength()) {
        LOG.error("Keypair length matching error");
        return false;
    }

    byte[] rawPayload = new byte[64];
    new Random().nextBytes(rawPayload);

    MessageEncoderDecoder encDec = new MessageEncoderDecoder(privateKey, publicKey);
    byte[] encodedPayload;
    byte[] decodedPayload;
    try {
        encodedPayload = encDec.encodeData(rawPayload);
        decodedPayload = encDec.decodeData(encodedPayload);
    } catch (GeneralSecurityException ex) {
        LOG.error("Validation keypair error ", ex);
        return false;
    }
    return Arrays.equals(rawPayload, decodedPayload);
}