Java Code Examples for java.security.interfaces.RSAPrivateCrtKey#getModulus()

The following examples show how to use java.security.interfaces.RSAPrivateCrtKey#getModulus() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: SimpleIngestManager.java    From snowflake-ingest-java with Apache License 2.0 7 votes vote down vote up
/**
 * generate key pair object from private key
 *
 * @param privateKey private key
 * @return a key pair object
 * @throws NoSuchAlgorithmException if can't create key factory by using
 *                                  RSA algorithm
 * @throws InvalidKeySpecException  if private key or public key is invalid
 */
private KeyPair createKeyPairFromPrivateKey(PrivateKey privateKey) throws
    NoSuchAlgorithmException, InvalidKeySpecException
{
  if(!(privateKey instanceof RSAPrivateCrtKey))
    throw new IllegalArgumentException("Input private key is not a RSA private key");

  KeyFactory kf = KeyFactory.getInstance("RSA");

  //generate public key from private key
  RSAPrivateCrtKey privk = (RSAPrivateCrtKey) privateKey;
  RSAPublicKeySpec publicKeySpec = new RSAPublicKeySpec(privk.getModulus(),
      privk.getPublicExponent());
  PublicKey publicK = kf.generatePublic(publicKeySpec);

  //create key pairs
  return new KeyPair(publicK, privateKey);
}
 
Example 2
Source File: RSA.java    From jeesuite-libs with Apache License 2.0 6 votes vote down vote up
/**
   * 从KeyStore获取公钥
   * @param location
   * @param alias
   * @param storeType
   * @param storePass
   * @param keyPass
   * @return
   */
  public static PublicKey loadPublicKeyFromKeyStore(String location,String alias,String storeType,String storePass,String keyPass){
      try {			
      	storeType = null == storeType ? KeyStore.getDefaultType() : storeType;
      	keyPass = keyPass == null ? storePass : keyPass;
      	KeyStore keyStore = KeyStore.getInstance(storeType);
      	InputStream is = new FileInputStream(location);
      	keyStore.load(is, storePass.toCharArray());
      	
      	RSAPrivateCrtKey key = (RSAPrivateCrtKey) keyStore.getKey(alias, keyPass.toCharArray());
	RSAPublicKeySpec spec = new RSAPublicKeySpec(key.getModulus(),
			key.getPublicExponent());
	PublicKey publicKey = KeyFactory.getInstance(KEY_ALGORITHM).generatePublic(spec);
          return publicKey;
} catch (Exception e) {
	throw new RuntimeException(e);
}
  }
 
Example 3
Source File: RSA.java    From azeroth with Apache License 2.0 6 votes vote down vote up
/**
 * 从KeyStore获取公钥
 * @param location
 * @param alias
 * @param storeType
 * @param storePass
 * @param keyPass
 * @return
 */
public static PublicKey loadPublicKeyFromKeyStore(String location, String alias, String storeType, String storePass, String keyPass) {
    try {
        storeType = null == storeType ? KeyStore.getDefaultType() : storeType;
        keyPass = keyPass == null ? storePass : keyPass;
        KeyStore keyStore = KeyStore.getInstance(storeType);
        InputStream is = new FileInputStream(location);
        keyStore.load(is, storePass.toCharArray());

        RSAPrivateCrtKey key = (RSAPrivateCrtKey) keyStore.getKey(alias, keyPass.toCharArray());
        RSAPublicKeySpec spec = new RSAPublicKeySpec(key.getModulus(),
                key.getPublicExponent());
        PublicKey publicKey = KeyFactory.getInstance(KEY_ALGORITHM).generatePublic(spec);
        return publicKey;
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
 
Example 4
Source File: BCRSAPrivateCrtKey.java    From RipplePower with Apache License 2.0 5 votes vote down vote up
/**
 * construct a private key from another RSAPrivateCrtKey.
 *
 * @param key the object implementing the RSAPrivateCrtKey interface.
 */
BCRSAPrivateCrtKey(
    RSAPrivateCrtKey key)
{
    this.modulus = key.getModulus();
    this.publicExponent = key.getPublicExponent();
    this.privateExponent = key.getPrivateExponent();
    this.primeP = key.getPrimeP();
    this.primeQ = key.getPrimeQ();
    this.primeExponentP = key.getPrimeExponentP();
    this.primeExponentQ = key.getPrimeExponentQ();
    this.crtCoefficient = key.getCrtCoefficient();
}
 
Example 5
Source File: JCERSAPrivateCrtKey.java    From RipplePower with Apache License 2.0 5 votes vote down vote up
/**
 * construct a private key from another RSAPrivateCrtKey.
 *
 * @param key the object implementing the RSAPrivateCrtKey interface.
 */
JCERSAPrivateCrtKey(
    RSAPrivateCrtKey key)
{
    this.modulus = key.getModulus();
    this.publicExponent = key.getPublicExponent();
    this.privateExponent = key.getPrivateExponent();
    this.primeP = key.getPrimeP();
    this.primeQ = key.getPrimeQ();
    this.primeExponentP = key.getPrimeExponentP();
    this.primeExponentQ = key.getPrimeExponentQ();
    this.crtCoefficient = key.getCrtCoefficient();
}
 
Example 6
Source File: SignerUtil.java    From xipki with Apache License 2.0 5 votes vote down vote up
public static RSAKeyParameters generateRSAPrivateKeyParameter(RSAPrivateKey key) {
  Args.notNull(key, "key");
  if (key instanceof RSAPrivateCrtKey) {
    RSAPrivateCrtKey rsaKey = (RSAPrivateCrtKey) key;

    return new RSAPrivateCrtKeyParameters(rsaKey.getModulus(), rsaKey.getPublicExponent(),
        rsaKey.getPrivateExponent(), rsaKey.getPrimeP(), rsaKey.getPrimeQ(),
        rsaKey.getPrimeExponentP(), rsaKey.getPrimeExponentQ(), rsaKey.getCrtCoefficient());
  } else {
    return new RSAKeyParameters(true, key.getModulus(), key.getPrivateExponent());
  }
}
 
Example 7
Source File: KeyUtils.java    From keycloak with Apache License 2.0 5 votes vote down vote up
public static PublicKey extractPublicKey(PrivateKey key) {
    if (key == null) {
        return null;
    }

    try {
        RSAPrivateCrtKey rsaPrivateCrtKey = (RSAPrivateCrtKey) key;
        RSAPublicKeySpec publicKeySpec = new RSAPublicKeySpec(rsaPrivateCrtKey.getModulus(), rsaPrivateCrtKey.getPublicExponent());
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        return keyFactory.generatePublic(publicKeySpec);
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
 
Example 8
Source File: JCERSAPrivateCrtKey.java    From ripple-lib-java with ISC License 5 votes vote down vote up
/**
 * construct a private key from another RSAPrivateCrtKey.
 *
 * @param key the object implementing the RSAPrivateCrtKey interface.
 */
JCERSAPrivateCrtKey(
    RSAPrivateCrtKey key)
{
    this.modulus = key.getModulus();
    this.publicExponent = key.getPublicExponent();
    this.privateExponent = key.getPrivateExponent();
    this.primeP = key.getPrimeP();
    this.primeQ = key.getPrimeQ();
    this.primeExponentP = key.getPrimeExponentP();
    this.primeExponentQ = key.getPrimeExponentQ();
    this.crtCoefficient = key.getCrtCoefficient();
}
 
Example 9
Source File: KeyStoreGenerator.java    From cute-proxy with BSD 2-Clause "Simplified" License 5 votes vote down vote up
private RSAPrivateCrtKeyParameters getPrivateKeyParameters(RSAPrivateCrtKey privateCrtKey) {
    return new RSAPrivateCrtKeyParameters(privateCrtKey.getModulus(),
            privateCrtKey.getPublicExponent(),
            privateCrtKey.getPrivateExponent(),
            privateCrtKey.getPrimeP(), privateCrtKey.getPrimeQ(), privateCrtKey.getPrimeExponentP(),
            privateCrtKey.getPrimeExponentQ(),
            privateCrtKey.getCrtCoefficient());
}
 
Example 10
Source File: BCRSAPrivateCrtKey.java    From ripple-lib-java with ISC License 5 votes vote down vote up
/**
 * construct a private key from another RSAPrivateCrtKey.
 *
 * @param key the object implementing the RSAPrivateCrtKey interface.
 */
BCRSAPrivateCrtKey(
    RSAPrivateCrtKey key)
{
    this.modulus = key.getModulus();
    this.publicExponent = key.getPublicExponent();
    this.privateExponent = key.getPrivateExponent();
    this.primeP = key.getPrimeP();
    this.primeQ = key.getPrimeQ();
    this.primeExponentP = key.getPrimeExponentP();
    this.primeExponentQ = key.getPrimeExponentQ();
    this.crtCoefficient = key.getCrtCoefficient();
}
 
Example 11
Source File: PrivateKeyEqualityTest.java    From jdk8u-jdk with GNU General Public License v2.0 4 votes vote down vote up
public static void main(String[] args) throws NoSuchAlgorithmException,
        NoSuchProviderException, InvalidKeySpecException {
    // Generate the first key.
    KeyPairGenerator generator
            = KeyPairGenerator.getInstance(KEYALG, PROVIDER_NAME);
    KeyPair keyPair = generator.generateKeyPair();
    RSAPrivateKey rsaPrivateKey = (RSAPrivateKey) keyPair.getPrivate();
    if (!(rsaPrivateKey instanceof RSAPrivateCrtKey)) {
        System.err.println("rsaPrivateKey class : " + rsaPrivateKey.getClass().getName());
        throw new RuntimeException("rsaPrivateKey is not a RSAPrivateCrtKey instance");
    }

    // Generate the second key.
    KeyFactory factory = KeyFactory.getInstance(KEYALG, PROVIDER_NAME);
    RSAPrivateKeySpec rsaPrivateKeySpec = new RSAPrivateKeySpec(
            rsaPrivateKey.getModulus(), rsaPrivateKey.getPrivateExponent());
    RSAPrivateKey rsaPrivateKey2 = (RSAPrivateKey) factory.generatePrivate(
            rsaPrivateKeySpec);

    // Generate the third key.
    PKCS8EncodedKeySpec encodedKeySpec = new PKCS8EncodedKeySpec(
            rsaPrivateKey.getEncoded());
    RSAPrivateKey rsaPrivateKey3 = (RSAPrivateKey) factory.generatePrivate(
            encodedKeySpec);

    // Check for equality.
    if (rsaPrivateKey.equals(rsaPrivateKey2)) {
        throw new RuntimeException("rsaPrivateKey should not equal to rsaPrivateKey2");
    }
    if (!rsaPrivateKey3.equals(rsaPrivateKey)) {
        throw new RuntimeException("rsaPrivateKey3 should equal to rsaPrivateKey");
    }
    if (rsaPrivateKey3.equals(rsaPrivateKey2)) {
        throw new RuntimeException("rsaPrivateKey3 should not equal to rsaPrivateKey2");
    }
    if (rsaPrivateKey2.equals(rsaPrivateKey3)) {
        throw new RuntimeException("rsaPrivateKey2 should not equal to rsaPrivateKey3");
    }

    // Generate the fourth key.
    RSAPrivateCrtKey rsaPrivateCrtKey =  (RSAPrivateCrtKey)rsaPrivateKey;
    RSAPrivateCrtKeySpec rsaPrivateCrtKeySpec = new RSAPrivateCrtKeySpec(
            rsaPrivateCrtKey.getModulus(),
            rsaPrivateCrtKey.getPublicExponent(),
            rsaPrivateCrtKey.getPrivateExponent(),
            rsaPrivateCrtKey.getPrimeP(),
            rsaPrivateCrtKey.getPrimeQ(),
            rsaPrivateCrtKey.getPrimeExponentP(),
            rsaPrivateCrtKey.getPrimeExponentQ(),
            rsaPrivateCrtKey.getCrtCoefficient()
        );
    RSAPrivateCrtKey rsaPrivateKey4 = (RSAPrivateCrtKey) factory.generatePrivate(
            rsaPrivateCrtKeySpec);
    if (!rsaPrivateKey.equals(rsaPrivateKey4)) {
        throw new RuntimeException("rsaPrivateKey should equal to rsaPrivateKey4");
    }
}
 
Example 12
Source File: PrivateKeyEqualityTest.java    From openjdk-jdk9 with GNU General Public License v2.0 4 votes vote down vote up
public static void main(String[] args) throws NoSuchAlgorithmException,
        NoSuchProviderException, InvalidKeySpecException {
    // Generate the first key.
    KeyPairGenerator generator
            = KeyPairGenerator.getInstance(KEYALG, PROVIDER_NAME);
    KeyPair keyPair = generator.generateKeyPair();
    RSAPrivateKey rsaPrivateKey = (RSAPrivateKey) keyPair.getPrivate();
    if (!(rsaPrivateKey instanceof RSAPrivateCrtKey)) {
        System.err.println("rsaPrivateKey class : " + rsaPrivateKey.getClass().getName());
        throw new RuntimeException("rsaPrivateKey is not a RSAPrivateCrtKey instance");
    }

    // Generate the second key.
    KeyFactory factory = KeyFactory.getInstance(KEYALG, PROVIDER_NAME);
    RSAPrivateKeySpec rsaPrivateKeySpec = new RSAPrivateKeySpec(
            rsaPrivateKey.getModulus(), rsaPrivateKey.getPrivateExponent());
    RSAPrivateKey rsaPrivateKey2 = (RSAPrivateKey) factory.generatePrivate(
            rsaPrivateKeySpec);

    // Generate the third key.
    PKCS8EncodedKeySpec encodedKeySpec = new PKCS8EncodedKeySpec(
            rsaPrivateKey.getEncoded());
    RSAPrivateKey rsaPrivateKey3 = (RSAPrivateKey) factory.generatePrivate(
            encodedKeySpec);

    // Check for equality.
    if (rsaPrivateKey.equals(rsaPrivateKey2)) {
        throw new RuntimeException("rsaPrivateKey should not equal to rsaPrivateKey2");
    }
    if (!rsaPrivateKey3.equals(rsaPrivateKey)) {
        throw new RuntimeException("rsaPrivateKey3 should equal to rsaPrivateKey");
    }
    if (rsaPrivateKey3.equals(rsaPrivateKey2)) {
        throw new RuntimeException("rsaPrivateKey3 should not equal to rsaPrivateKey2");
    }
    if (rsaPrivateKey2.equals(rsaPrivateKey3)) {
        throw new RuntimeException("rsaPrivateKey2 should not equal to rsaPrivateKey3");
    }

    // Generate the fourth key.
    RSAPrivateCrtKey rsaPrivateCrtKey =  (RSAPrivateCrtKey)rsaPrivateKey;
    RSAPrivateCrtKeySpec rsaPrivateCrtKeySpec = new RSAPrivateCrtKeySpec(
            rsaPrivateCrtKey.getModulus(),
            rsaPrivateCrtKey.getPublicExponent(),
            rsaPrivateCrtKey.getPrivateExponent(),
            rsaPrivateCrtKey.getPrimeP(),
            rsaPrivateCrtKey.getPrimeQ(),
            rsaPrivateCrtKey.getPrimeExponentP(),
            rsaPrivateCrtKey.getPrimeExponentQ(),
            rsaPrivateCrtKey.getCrtCoefficient()
        );
    RSAPrivateCrtKey rsaPrivateKey4 = (RSAPrivateCrtKey) factory.generatePrivate(
            rsaPrivateCrtKeySpec);
    if (!rsaPrivateKey.equals(rsaPrivateKey4)) {
        throw new RuntimeException("rsaPrivateKey should equal to rsaPrivateKey4");
    }
}
 
Example 13
Source File: PrivateKeyEqualityTest.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 4 votes vote down vote up
public static void main(String[] args) throws NoSuchAlgorithmException,
        NoSuchProviderException, InvalidKeySpecException {
    // Generate the first key.
    KeyPairGenerator generator
            = KeyPairGenerator.getInstance(KEYALG, PROVIDER_NAME);
    KeyPair keyPair = generator.generateKeyPair();
    RSAPrivateKey rsaPrivateKey = (RSAPrivateKey) keyPair.getPrivate();
    if (!(rsaPrivateKey instanceof RSAPrivateCrtKey)) {
        System.err.println("rsaPrivateKey class : " + rsaPrivateKey.getClass().getName());
        throw new RuntimeException("rsaPrivateKey is not a RSAPrivateCrtKey instance");
    }

    // Generate the second key.
    KeyFactory factory = KeyFactory.getInstance(KEYALG, PROVIDER_NAME);
    RSAPrivateKeySpec rsaPrivateKeySpec = new RSAPrivateKeySpec(
            rsaPrivateKey.getModulus(), rsaPrivateKey.getPrivateExponent());
    RSAPrivateKey rsaPrivateKey2 = (RSAPrivateKey) factory.generatePrivate(
            rsaPrivateKeySpec);

    // Generate the third key.
    PKCS8EncodedKeySpec encodedKeySpec = new PKCS8EncodedKeySpec(
            rsaPrivateKey.getEncoded());
    RSAPrivateKey rsaPrivateKey3 = (RSAPrivateKey) factory.generatePrivate(
            encodedKeySpec);

    // Check for equality.
    if (rsaPrivateKey.equals(rsaPrivateKey2)) {
        throw new RuntimeException("rsaPrivateKey should not equal to rsaPrivateKey2");
    }
    if (!rsaPrivateKey3.equals(rsaPrivateKey)) {
        throw new RuntimeException("rsaPrivateKey3 should equal to rsaPrivateKey");
    }
    if (rsaPrivateKey3.equals(rsaPrivateKey2)) {
        throw new RuntimeException("rsaPrivateKey3 should not equal to rsaPrivateKey2");
    }
    if (rsaPrivateKey2.equals(rsaPrivateKey3)) {
        throw new RuntimeException("rsaPrivateKey2 should not equal to rsaPrivateKey3");
    }

    // Generate the fourth key.
    RSAPrivateCrtKey rsaPrivateCrtKey =  (RSAPrivateCrtKey)rsaPrivateKey;
    RSAPrivateCrtKeySpec rsaPrivateCrtKeySpec = new RSAPrivateCrtKeySpec(
            rsaPrivateCrtKey.getModulus(),
            rsaPrivateCrtKey.getPublicExponent(),
            rsaPrivateCrtKey.getPrivateExponent(),
            rsaPrivateCrtKey.getPrimeP(),
            rsaPrivateCrtKey.getPrimeQ(),
            rsaPrivateCrtKey.getPrimeExponentP(),
            rsaPrivateCrtKey.getPrimeExponentQ(),
            rsaPrivateCrtKey.getCrtCoefficient()
        );
    RSAPrivateCrtKey rsaPrivateKey4 = (RSAPrivateCrtKey) factory.generatePrivate(
            rsaPrivateCrtKeySpec);
    if (!rsaPrivateKey.equals(rsaPrivateKey4)) {
        throw new RuntimeException("rsaPrivateKey should equal to rsaPrivateKey4");
    }
}
 
Example 14
Source File: SessionUtilKeyPair.java    From snowflake-jdbc with Apache License 2.0 4 votes vote down vote up
SessionUtilKeyPair(PrivateKey privateKey, String privateKeyFile, String privateKeyFilePwd,
                   String accountName,
                   String userName) throws SFException
{
  this.userName = userName.toUpperCase();
  this.accountName = accountName.toUpperCase();

  // check if in FIPS mode
  for (Provider p : Security.getProviders())
  {
    if ("BCFIPS".equals(p.getName()))
    {
      this.isFipsMode = true;
      this.SecurityProvider = p;
      break;
    }
  }

  // if there is both a file and a private key, there is a problem
  if (!Strings.isNullOrEmpty(privateKeyFile) && privateKey != null)
  {
    throw new SFException(ErrorCode.INVALID_OR_UNSUPPORTED_PRIVATE_KEY,
                          "Cannot have both private key value and private key file.");
  }
  else
  {
    // if privateKeyFile has a value and privateKey is null
    this.privateKey = Strings.isNullOrEmpty(privateKeyFile) ?
                      privateKey :
                      extractPrivateKeyFromFile(privateKeyFile, privateKeyFilePwd);
  }
  // construct public key from raw bytes
  if (this.privateKey instanceof RSAPrivateCrtKey)
  {
    RSAPrivateCrtKey rsaPrivateCrtKey = (RSAPrivateCrtKey) this.privateKey;
    RSAPublicKeySpec rsaPublicKeySpec = new RSAPublicKeySpec(
        rsaPrivateCrtKey.getModulus(), rsaPrivateCrtKey.getPublicExponent());

    try
    {
      this.publicKey = getKeyFactoryInstance().generatePublic(rsaPublicKeySpec);
    }
    catch (NoSuchAlgorithmException | InvalidKeySpecException e)
    {
      throw new SFException(e, ErrorCode.INTERNAL_ERROR,
                            "Error retrieving public key");
    }
  }
  else
  {
    throw new SFException(ErrorCode.INVALID_OR_UNSUPPORTED_PRIVATE_KEY,
                          "Use java.security.interfaces.RSAPrivateCrtKey.class for the private key");
  }
}
 
Example 15
Source File: RsaKeyTest.java    From wycheproof with Apache License 2.0 4 votes vote down vote up
private void checkPrivateCrtKey(RSAPrivateCrtKey key, int expectedKeySize) throws Exception {
  BigInteger p = key.getPrimeP();
  BigInteger q = key.getPrimeQ();
  BigInteger n = key.getModulus();
  BigInteger e = key.getPublicExponent();
  BigInteger d = key.getPrivateExponent();
  BigInteger dp = key.getPrimeExponentP();
  BigInteger dq = key.getPrimeExponentQ();
  BigInteger crtCoeff = key.getCrtCoefficient();

  // Simple test that (n,d,e) is a valid RSA key.
  assertEquals(n, p.multiply(q));
  assertEquals(expectedKeySize, n.bitLength());
  int certainty = 80;
  assertTrue(p.isProbablePrime(certainty));
  assertTrue(q.isProbablePrime(certainty));
  // Very simple checks for weak random number generators.
  RandomUtil.checkPrime(p);
  RandomUtil.checkPrime(q);
  // TODO(bleichen): Keys that are very imbalanced can be broken with elliptic curve factoring.
  //   Add other checks. E.g. for the size of dp and dq
  assertTrue(p.bitLength() > 256);
  assertTrue(q.bitLength() > 256);
  BigInteger p1 = p.subtract(BigInteger.ONE);
  BigInteger q1 = q.subtract(BigInteger.ONE);
  BigInteger phi = p1.multiply(q1);
  BigInteger order = phi.divide(p1.gcd(q1)); // maximal order of elements
  // RFC 8017 Section 3.2 specifies that d is a positive integer smaller than n satisfying
  //    e * d == 1 (mod lcm(p-1, q-1)).
  // FIPS-PUB 186-4 specifies that d is the smallest positive integer satisfying
  // the equation above and further specifies that key with d < 2^(n.bitlenght()/2) are not
  // allowed. The second condition is very unlikely to hold if keys are chosen at random.
  // Hence seeing a small d indicates with high probability a faulty key generation, such
  // as switching e and d, or selecting the primes p and q incorretly.
  // Such keys can likely be broken easily. I.e. since lcm(p - 1, q - 1) divides d * e - 1,
  // it follows that (p - 1) * (q - 1) divides (d * e - 1) * gcd(p - 1, q - 1).
  // Hence if d * e - 1 is small then p - 1 and q - 1 must have a large common factor g.
  assertEquals(1, d.compareTo(BigInteger.ONE));
  assertEquals(-1, d.compareTo(n)); // This is the requirement of RFC 8017
  // The following would be the stricter requirement of FIPS-PUB 186-4.
  // assertEquals(-1, d.compareTo(order));
  assertTrue(d.bitLength() > expectedKeySize / 2);
  assertEquals(BigInteger.ONE, d.multiply(e).mod(order));
  assertEquals(d.mod(p1), dp.mod(p1));
  assertEquals(d.mod(q1), dq.mod(q1));
  assertEquals(q.multiply(crtCoeff).mod(p), BigInteger.ONE);
  // Checks that p - 1 and q - 1 do not have a large common factor g. Since large common
  // factors are very unlikely to occur at random one has to assume that such an event is caused
  // by a faulty generation and that g is in fact known. Coppersmith showed how to factor an RSA
  // modulus if about 1/4 of the low order bits of a factor is known.
  assertTrue(p1.gcd(q1).bitLength() < expectedKeySize / 4);
}
 
Example 16
Source File: PrivateKeyEqualityTest.java    From openjdk-jdk8u with GNU General Public License v2.0 4 votes vote down vote up
public static void main(String[] args) throws NoSuchAlgorithmException,
        NoSuchProviderException, InvalidKeySpecException {
    // Generate the first key.
    KeyPairGenerator generator
            = KeyPairGenerator.getInstance(KEYALG, PROVIDER_NAME);
    KeyPair keyPair = generator.generateKeyPair();
    RSAPrivateKey rsaPrivateKey = (RSAPrivateKey) keyPair.getPrivate();
    if (!(rsaPrivateKey instanceof RSAPrivateCrtKey)) {
        System.err.println("rsaPrivateKey class : " + rsaPrivateKey.getClass().getName());
        throw new RuntimeException("rsaPrivateKey is not a RSAPrivateCrtKey instance");
    }

    // Generate the second key.
    KeyFactory factory = KeyFactory.getInstance(KEYALG, PROVIDER_NAME);
    RSAPrivateKeySpec rsaPrivateKeySpec = new RSAPrivateKeySpec(
            rsaPrivateKey.getModulus(), rsaPrivateKey.getPrivateExponent());
    RSAPrivateKey rsaPrivateKey2 = (RSAPrivateKey) factory.generatePrivate(
            rsaPrivateKeySpec);

    // Generate the third key.
    PKCS8EncodedKeySpec encodedKeySpec = new PKCS8EncodedKeySpec(
            rsaPrivateKey.getEncoded());
    RSAPrivateKey rsaPrivateKey3 = (RSAPrivateKey) factory.generatePrivate(
            encodedKeySpec);

    // Check for equality.
    if (rsaPrivateKey.equals(rsaPrivateKey2)) {
        throw new RuntimeException("rsaPrivateKey should not equal to rsaPrivateKey2");
    }
    if (!rsaPrivateKey3.equals(rsaPrivateKey)) {
        throw new RuntimeException("rsaPrivateKey3 should equal to rsaPrivateKey");
    }
    if (rsaPrivateKey3.equals(rsaPrivateKey2)) {
        throw new RuntimeException("rsaPrivateKey3 should not equal to rsaPrivateKey2");
    }
    if (rsaPrivateKey2.equals(rsaPrivateKey3)) {
        throw new RuntimeException("rsaPrivateKey2 should not equal to rsaPrivateKey3");
    }

    // Generate the fourth key.
    RSAPrivateCrtKey rsaPrivateCrtKey =  (RSAPrivateCrtKey)rsaPrivateKey;
    RSAPrivateCrtKeySpec rsaPrivateCrtKeySpec = new RSAPrivateCrtKeySpec(
            rsaPrivateCrtKey.getModulus(),
            rsaPrivateCrtKey.getPublicExponent(),
            rsaPrivateCrtKey.getPrivateExponent(),
            rsaPrivateCrtKey.getPrimeP(),
            rsaPrivateCrtKey.getPrimeQ(),
            rsaPrivateCrtKey.getPrimeExponentP(),
            rsaPrivateCrtKey.getPrimeExponentQ(),
            rsaPrivateCrtKey.getCrtCoefficient()
        );
    RSAPrivateCrtKey rsaPrivateKey4 = (RSAPrivateCrtKey) factory.generatePrivate(
            rsaPrivateCrtKeySpec);
    if (!rsaPrivateKey.equals(rsaPrivateKey4)) {
        throw new RuntimeException("rsaPrivateKey should equal to rsaPrivateKey4");
    }
}
 
Example 17
Source File: PrivateKeyEqualityTest.java    From TencentKona-8 with GNU General Public License v2.0 4 votes vote down vote up
public static void main(String[] args) throws NoSuchAlgorithmException,
        NoSuchProviderException, InvalidKeySpecException {
    // Generate the first key.
    KeyPairGenerator generator
            = KeyPairGenerator.getInstance(KEYALG, PROVIDER_NAME);
    KeyPair keyPair = generator.generateKeyPair();
    RSAPrivateKey rsaPrivateKey = (RSAPrivateKey) keyPair.getPrivate();
    if (!(rsaPrivateKey instanceof RSAPrivateCrtKey)) {
        System.err.println("rsaPrivateKey class : " + rsaPrivateKey.getClass().getName());
        throw new RuntimeException("rsaPrivateKey is not a RSAPrivateCrtKey instance");
    }

    // Generate the second key.
    KeyFactory factory = KeyFactory.getInstance(KEYALG, PROVIDER_NAME);
    RSAPrivateKeySpec rsaPrivateKeySpec = new RSAPrivateKeySpec(
            rsaPrivateKey.getModulus(), rsaPrivateKey.getPrivateExponent());
    RSAPrivateKey rsaPrivateKey2 = (RSAPrivateKey) factory.generatePrivate(
            rsaPrivateKeySpec);

    // Generate the third key.
    PKCS8EncodedKeySpec encodedKeySpec = new PKCS8EncodedKeySpec(
            rsaPrivateKey.getEncoded());
    RSAPrivateKey rsaPrivateKey3 = (RSAPrivateKey) factory.generatePrivate(
            encodedKeySpec);

    // Check for equality.
    if (rsaPrivateKey.equals(rsaPrivateKey2)) {
        throw new RuntimeException("rsaPrivateKey should not equal to rsaPrivateKey2");
    }
    if (!rsaPrivateKey3.equals(rsaPrivateKey)) {
        throw new RuntimeException("rsaPrivateKey3 should equal to rsaPrivateKey");
    }
    if (rsaPrivateKey3.equals(rsaPrivateKey2)) {
        throw new RuntimeException("rsaPrivateKey3 should not equal to rsaPrivateKey2");
    }
    if (rsaPrivateKey2.equals(rsaPrivateKey3)) {
        throw new RuntimeException("rsaPrivateKey2 should not equal to rsaPrivateKey3");
    }

    // Generate the fourth key.
    RSAPrivateCrtKey rsaPrivateCrtKey =  (RSAPrivateCrtKey)rsaPrivateKey;
    RSAPrivateCrtKeySpec rsaPrivateCrtKeySpec = new RSAPrivateCrtKeySpec(
            rsaPrivateCrtKey.getModulus(),
            rsaPrivateCrtKey.getPublicExponent(),
            rsaPrivateCrtKey.getPrivateExponent(),
            rsaPrivateCrtKey.getPrimeP(),
            rsaPrivateCrtKey.getPrimeQ(),
            rsaPrivateCrtKey.getPrimeExponentP(),
            rsaPrivateCrtKey.getPrimeExponentQ(),
            rsaPrivateCrtKey.getCrtCoefficient()
        );
    RSAPrivateCrtKey rsaPrivateKey4 = (RSAPrivateCrtKey) factory.generatePrivate(
            rsaPrivateCrtKeySpec);
    if (!rsaPrivateKey.equals(rsaPrivateKey4)) {
        throw new RuntimeException("rsaPrivateKey should equal to rsaPrivateKey4");
    }
}
 
Example 18
Source File: MsPvkUtil.java    From keystore-explorer with GNU General Public License v3.0 4 votes vote down vote up
private static byte[] rsaPrivateKeyToBlob(RSAPrivateCrtKey rsaPrivCrtKey) throws CryptoException {
	try {
		ByteBuffer bb = ByteBuffer.wrap(new byte[4096]); // 2316 sufficient for a 4096 bit RSA key
		bb.order(ByteOrder.LITTLE_ENDIAN);

		// Write out the blob fields

		UnsignedUtil.putInt(bb, RSA_PRIV_MAGIC); // rsapubkey.magic

		BigInteger modulus = rsaPrivCrtKey.getModulus();
		int bitLength = modulus.bitLength();
		UnsignedUtil.putInt(bb, bitLength); // rsapubkey.bitlen

		BigInteger publicExponent = rsaPrivCrtKey.getPublicExponent();
		UnsignedUtil.putInt(bb, (int) publicExponent.longValue()); // rsapubkey.pubexp

		/*
		 * Byte lengths divisions may have remainders to take account for if
		 * not factors of 16 and/or 8
		 */
		int add8 = 0;
		if ((bitLength % 8) != 0) {
			add8++;
		}

		int add16 = 0;
		if ((bitLength % 16) != 0) {
			add16++;
		}

		writeBigInteger(bb, modulus, (bitLength / 8) + add8); // modulus
		writeBigInteger(bb, rsaPrivCrtKey.getPrimeP(), (bitLength / 16) + add16); // prime1
		writeBigInteger(bb, rsaPrivCrtKey.getPrimeQ(), (bitLength / 16) + add16); // prime2
		writeBigInteger(bb, rsaPrivCrtKey.getPrimeExponentP(), (bitLength / 16) + add16); // exponent1
		writeBigInteger(bb, rsaPrivCrtKey.getPrimeExponentQ(), (bitLength / 16) + add16); // exponent2
		writeBigInteger(bb, rsaPrivCrtKey.getCrtCoefficient(), (bitLength / 16) + add16); // coefficient
		writeBigInteger(bb, rsaPrivCrtKey.getPrivateExponent(), (bitLength / 8) + add8); // privateExponent

		return getBufferBytes(bb);
	} catch (IOException ex) {
		throw new CryptoException(res.getString("NoConvertKeyToBlob.exception.message"), ex);
	}
}
 
Example 19
Source File: PrivateKeyEqualityTest.java    From dragonwell8_jdk with GNU General Public License v2.0 4 votes vote down vote up
public static void main(String[] args) throws NoSuchAlgorithmException,
        NoSuchProviderException, InvalidKeySpecException {
    // Generate the first key.
    KeyPairGenerator generator
            = KeyPairGenerator.getInstance(KEYALG, PROVIDER_NAME);
    KeyPair keyPair = generator.generateKeyPair();
    RSAPrivateKey rsaPrivateKey = (RSAPrivateKey) keyPair.getPrivate();
    if (!(rsaPrivateKey instanceof RSAPrivateCrtKey)) {
        System.err.println("rsaPrivateKey class : " + rsaPrivateKey.getClass().getName());
        throw new RuntimeException("rsaPrivateKey is not a RSAPrivateCrtKey instance");
    }

    // Generate the second key.
    KeyFactory factory = KeyFactory.getInstance(KEYALG, PROVIDER_NAME);
    RSAPrivateKeySpec rsaPrivateKeySpec = new RSAPrivateKeySpec(
            rsaPrivateKey.getModulus(), rsaPrivateKey.getPrivateExponent());
    RSAPrivateKey rsaPrivateKey2 = (RSAPrivateKey) factory.generatePrivate(
            rsaPrivateKeySpec);

    // Generate the third key.
    PKCS8EncodedKeySpec encodedKeySpec = new PKCS8EncodedKeySpec(
            rsaPrivateKey.getEncoded());
    RSAPrivateKey rsaPrivateKey3 = (RSAPrivateKey) factory.generatePrivate(
            encodedKeySpec);

    // Check for equality.
    if (rsaPrivateKey.equals(rsaPrivateKey2)) {
        throw new RuntimeException("rsaPrivateKey should not equal to rsaPrivateKey2");
    }
    if (!rsaPrivateKey3.equals(rsaPrivateKey)) {
        throw new RuntimeException("rsaPrivateKey3 should equal to rsaPrivateKey");
    }
    if (rsaPrivateKey3.equals(rsaPrivateKey2)) {
        throw new RuntimeException("rsaPrivateKey3 should not equal to rsaPrivateKey2");
    }
    if (rsaPrivateKey2.equals(rsaPrivateKey3)) {
        throw new RuntimeException("rsaPrivateKey2 should not equal to rsaPrivateKey3");
    }

    // Generate the fourth key.
    RSAPrivateCrtKey rsaPrivateCrtKey =  (RSAPrivateCrtKey)rsaPrivateKey;
    RSAPrivateCrtKeySpec rsaPrivateCrtKeySpec = new RSAPrivateCrtKeySpec(
            rsaPrivateCrtKey.getModulus(),
            rsaPrivateCrtKey.getPublicExponent(),
            rsaPrivateCrtKey.getPrivateExponent(),
            rsaPrivateCrtKey.getPrimeP(),
            rsaPrivateCrtKey.getPrimeQ(),
            rsaPrivateCrtKey.getPrimeExponentP(),
            rsaPrivateCrtKey.getPrimeExponentQ(),
            rsaPrivateCrtKey.getCrtCoefficient()
        );
    RSAPrivateCrtKey rsaPrivateKey4 = (RSAPrivateCrtKey) factory.generatePrivate(
            rsaPrivateCrtKeySpec);
    if (!rsaPrivateKey.equals(rsaPrivateKey4)) {
        throw new RuntimeException("rsaPrivateKey should equal to rsaPrivateKey4");
    }
}
 
Example 20
Source File: RsaPrivateKeyDef.java    From swim with Apache License 2.0 4 votes vote down vote up
private static RsaPrivateKeyDef from(RSAPrivateCrtKey key) {
  FingerTrieSeq<RsaPrimeDef> primeDefs = FingerTrieSeq.empty();
  primeDefs = primeDefs.appended(new RsaPrimeDef(key.getPrimeP(), key.getPrimeExponentP()));
  primeDefs = primeDefs.appended(new RsaPrimeDef(key.getPrimeQ(), key.getPrimeExponentQ(), key.getCrtCoefficient()));
  return new RsaPrivateKeyDef(key.getModulus(), key.getPublicExponent(), key.getPrivateExponent(), primeDefs, key);
}