List of usage examples for java.security.interfaces RSAPrivateCrtKey getModulus
public BigInteger getModulus();
From source file:de.alpharogroup.crypto.key.PrivateKeyExtensions.java
/** * Generate the corresponding {@link PublicKey} object from the given {@link PrivateKey} object. * * @param privateKey/*from ww w . j av a 2 s . com*/ * the private key * @return the corresponding {@link PublicKey} object or null if generation failed. * @throws NoSuchAlgorithmException * the no such algorithm exception * @throws InvalidKeySpecException * the invalid key spec exception */ public static PublicKey generatePublicKey(final PrivateKey privateKey) throws NoSuchAlgorithmException, InvalidKeySpecException { if (privateKey instanceof RSAPrivateKey) { final RSAPrivateCrtKey privk = (RSAPrivateCrtKey) privateKey; final RSAPublicKeySpec publicKeySpec = new RSAPublicKeySpec(privk.getModulus(), privk.getPublicExponent()); final KeyFactory keyFactory = KeyFactory.getInstance(KeyPairGeneratorAlgorithm.RSA.getAlgorithm()); final PublicKey publicKey = keyFactory.generatePublic(publicKeySpec); return publicKey; } return null; }
From source file:com.vmware.o11n.plugin.crypto.model.CryptoUtil.java
/** * Compute the RSA Public Key from an RSA Private Key * * @param privateKey RSA Private Key//from w w w .j av a2 s . c o m * @return RSA Public Key * @throws NoSuchAlgorithmException * @throws InvalidKeySpecException */ public static RSAPublicKey getPublicFromPrivate(RSAPrivateCrtKey privateKey) throws NoSuchAlgorithmException, InvalidKeySpecException { RSAPublicKeySpec spec = new RSAPublicKeySpec(privateKey.getModulus(), privateKey.getPublicExponent()); return (RSAPublicKey) getPublicKey(spec); }
From source file:jenkins.bouncycastle.api.PEMEncodable.java
/** * Creates a {@link PEMEncodable} by decoding PEM formated data from a {@link String} * /*from w ww. j a va 2 s. c o m*/ * @param pem {@link String} with the PEM data * @param passphrase passphrase for the encrypted PEM data. null if PEM data is not passphrase protected. The caller * is responsible for zeroing out the char[] after use to ensure the password does not stay in memory, e.g. with * <code>Arrays.fill(passphrase, (char)0)</code> * @return {@link PEMEncodable} object * @throws IOException launched if a problem exists reading the PEM information * @throws UnrecoverableKeyException in case PEM is passphrase protected and none or wrong is provided */ @Nonnull public static PEMEncodable decode(@Nonnull String pem, @Nullable final char[] passphrase) throws IOException, UnrecoverableKeyException { try (PEMParser parser = new PEMParser(new StringReader(pem));) { Object object = parser.readObject(); JcaPEMKeyConverter kConv = new JcaPEMKeyConverter().setProvider("BC"); // handle supported PEM formats. if (object instanceof PEMEncryptedKeyPair) { if (passphrase != null) { PEMDecryptorProvider dp = new JcePEMDecryptorProviderBuilder().build(passphrase); PEMEncryptedKeyPair ekp = (PEMEncryptedKeyPair) object; return new PEMEncodable(kConv.getKeyPair(ekp.decryptKeyPair(dp))); } else { throw new UnrecoverableKeyException(); } } else if (object instanceof PKCS8EncryptedPrivateKeyInfo) { if (passphrase != null) { InputDecryptorProvider dp = new JceOpenSSLPKCS8DecryptorProviderBuilder().build(passphrase); PKCS8EncryptedPrivateKeyInfo epk = (PKCS8EncryptedPrivateKeyInfo) object; return new PEMEncodable(kConv.getPrivateKey(epk.decryptPrivateKeyInfo(dp))); } else { throw new UnrecoverableKeyException(); } } else if (object instanceof PEMKeyPair) { return new PEMEncodable(kConv.getKeyPair((PEMKeyPair) object)); } else if (object instanceof PrivateKeyInfo) { PrivateKey pk = kConv.getPrivateKey((PrivateKeyInfo) object); // JENKINS-35661 in this case we know how to get the public key too if (pk instanceof RSAPrivateCrtKey) { // obtain public key spec from the private key RSAPrivateCrtKey rsaPK = (RSAPrivateCrtKey) pk; RSAPublicKeySpec pubKeySpec = new RSAPublicKeySpec(rsaPK.getModulus(), rsaPK.getPublicExponent()); KeyFactory kf = KeyFactory.getInstance("RSA"); return new PEMEncodable(new KeyPair(kf.generatePublic(pubKeySpec), rsaPK)); } return new PEMEncodable(pk); } else if (object instanceof SubjectPublicKeyInfo) { return new PEMEncodable(kConv.getPublicKey((SubjectPublicKeyInfo) object)); } else if (object instanceof X509CertificateHolder) { JcaX509CertificateConverter cConv = new JcaX509CertificateConverter().setProvider("BC"); return new PEMEncodable(cConv.getCertificate((X509CertificateHolder) object)); } else { throw new IOException( "Could not parse PEM, only key pairs, private keys, public keys and certificates are supported. Received " + object.getClass().getName()); } } catch (OperatorCreationException e) { throw new IOException(e.getMessage(), e); } catch (PKCSException | InvalidKeySpecException e) { LOGGER.log(Level.WARNING, "Could not read PEM encrypted information", e); throw new UnrecoverableKeyException(); } catch (CertificateException e) { throw new IOException("Could not read certificate", e); } catch (NoSuchAlgorithmException e) { throw new AssertionError( "RSA algorithm support is mandated by Java Language Specification. See https://docs.oracle.com/javase/7/docs/api/java/security/KeyFactory.html"); } }
From source file:com.thoughtworks.go.security.X509CertificateGeneratorTest.java
@Test public void shouldGeneratePrivateKeyWithCRTFactorsForCompatibilityWithOtherPlatform() throws Exception { X509CertificateGenerator generator = new X509CertificateGenerator(); Registration registration = generator.createAgentCertificate(keystore, "agentHostName"); assertThat(registration.getPrivateKey(), instanceOf(RSAPrivateCrtKey.class)); RSAPrivateCrtKey key = (RSAPrivateCrtKey) registration.getPrivateKey(); assertThat(key.getModulus().signum(), is(1)); assertThat(key.getPrivateExponent().signum(), is(1)); assertThat(key.getPrimeP().signum(), is(1)); assertThat(key.getPrimeExponentQ().signum(), is(1)); assertThat(key.getCrtCoefficient().signum(), is(1)); }
From source file:jenkins.security.RSAConfidentialKey.java
/** * Obtains the private key (lazily.)/*from ww w . j av a 2 s. c o m*/ * <p> * This method is not publicly exposed as per the design principle of {@link ConfidentialKey}. * Instead of exposing private key, define methods that use them in specific way, such as * {@link RSADigitalSignatureConfidentialKey}. * * @throws Error * If key cannot be loaded for some reasons, we fail. */ protected synchronized RSAPrivateKey getPrivateKey() { try { if (priv == null) { byte[] payload = load(); if (payload == null) { KeyPairGenerator gen = KeyPairGenerator.getInstance("RSA"); gen.initialize(2048, new SecureRandom()); // going beyond 2048 requires crypto extension KeyPair keys = gen.generateKeyPair(); priv = (RSAPrivateKey) keys.getPrivate(); pub = (RSAPublicKey) keys.getPublic(); store(priv.getEncoded()); } else { KeyFactory keyFactory = KeyFactory.getInstance("RSA"); priv = (RSAPrivateKey) keyFactory.generatePrivate(new PKCS8EncodedKeySpec(payload)); RSAPrivateCrtKey pks = (RSAPrivateCrtKey) priv; pub = (RSAPublicKey) keyFactory .generatePublic(new RSAPublicKeySpec(pks.getModulus(), pks.getPublicExponent())); } } return priv; } catch (IOException e) { throw new Error("Failed to load the key: " + getId(), e); } catch (GeneralSecurityException e) { throw new Error("Failed to load the key: " + getId(), e); } }
From source file:io.kodokojo.config.module.SecurityModule.java
@Provides @Singleton//from www . j a va 2s .com SSLKeyPair provideSSLKeyPair(SecurityConfig securityConfig) { if (securityConfig == null) { throw new IllegalArgumentException("securityConfig must be defined."); } if (StringUtils.isNotBlank(securityConfig.wildcardPemPath())) { File pemFile = new File(securityConfig.wildcardPemPath()); try { String content = IOUtils.toString(new FileReader(pemFile)); String contentPrivate = RSAUtils.extractPrivateKey(content); String contentPublic = RSAUtils.extractPublic(content); RSAPrivateKey rsaPrivateKey = RSAUtils.readRsaPrivateKey(new StringReader(contentPrivate)); X509Certificate certificate = RSAUtils.readRsaPublicKey(new StringReader(contentPublic)); RSAPublicKey rsaPublicKey = (RSAPublicKey) certificate.getPublicKey(); X509Certificate[] certificates = new X509Certificate[1]; certificates[0] = certificate; LOGGER.info( "Using Wildcard SSL certificat {} from path {}to provide Certificat to all instances of Kodo Kojo. ", certificate.getSubjectDN().toString(), securityConfig.wildcardPemPath()); return new SSLKeyPair(rsaPrivateKey, rsaPublicKey, certificates); } catch (IOException e) { throw new IllegalArgumentException("Unable to read pem file " + pemFile.getAbsolutePath() + ".", e); } } else { try { KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType()); ks.load(new FileInputStream(System.getProperty("javax.net.ssl.keyStore")), System.getProperty("javax.net.ssl.keyStorePassword", "").toCharArray()); RSAPrivateCrtKey key = (RSAPrivateCrtKey) ks.getKey(securityConfig.sslRootCaKsAlias(), securityConfig.sslRootCaKsPassword().toCharArray()); if (key == null) { return null; } RSAPublicKeySpec publicKeySpec = new RSAPublicKeySpec(key.getModulus(), key.getPublicExponent()); KeyFactory keyFactory = KeyFactory.getInstance("RSA"); RSAPublicKey publicKey = (RSAPublicKey) keyFactory.generatePublic(publicKeySpec); Certificate[] certificateChain = ks.getCertificateChain(securityConfig.sslRootCaKsAlias()); List<X509Certificate> x509Certificates = Arrays.asList(certificateChain).stream() .map(c -> (X509Certificate) c).collect(Collectors.toList()); LOGGER.info( "Using a CA SSL certificat {} from keystore to provide Certificat to all instances of Kodo Kojo. ", securityConfig.sslRootCaKsAlias(), System.getProperty("javax.net.ssl.keyStore")); return new SSLKeyPair(key, publicKey, x509Certificates.toArray(new X509Certificate[x509Certificates.size()])); } catch (UnrecoverableKeyException | NoSuchAlgorithmException | KeyStoreException | InvalidKeySpecException | CertificateException | IOException e) { throw new RuntimeException("Unable to open default Keystore", e); } } }
From source file:org.ebayopensource.fido.uaf.crypto.KeyCodec.java
static public RSAKeyParameters generatePrivateKeyParameter(RSAPrivateKey key) { if (key instanceof RSAPrivateCrtKey) { RSAPrivateCrtKey k = (RSAPrivateCrtKey) key; return new RSAPrivateCrtKeyParameters(k.getModulus(), k.getPublicExponent(), k.getPrivateExponent(), k.getPrimeP(), k.getPrimeQ(), k.getPrimeExponentP(), k.getPrimeExponentQ(), k.getCrtCoefficient());//from w ww .j a v a 2s .c o m } else { RSAPrivateKey k = key; return new RSAKeyParameters(true, k.getModulus(), k.getPrivateExponent()); } }
From source file:org.opensaml.xml.security.SecurityHelper.java
/** * Derives the public key from either a DSA or RSA private key. * /* www . ja v a2 s. c om*/ * @param key the private key to derive the public key from * * @return the derived public key * * @throws KeyException thrown if the given private key is not a DSA or RSA key or there is a problem generating the * public key */ public static PublicKey derivePublicKey(PrivateKey key) throws KeyException { KeyFactory factory; if (key instanceof DSAPrivateKey) { DSAPrivateKey dsaKey = (DSAPrivateKey) key; DSAParams keyParams = dsaKey.getParams(); BigInteger y = keyParams.getQ().modPow(dsaKey.getX(), keyParams.getP()); DSAPublicKeySpec pubKeySpec = new DSAPublicKeySpec(y, keyParams.getP(), keyParams.getQ(), keyParams.getG()); try { factory = KeyFactory.getInstance("DSA"); return factory.generatePublic(pubKeySpec); } catch (GeneralSecurityException e) { throw new KeyException("Unable to derive public key from DSA private key", e); } } else if (key instanceof RSAPrivateCrtKey) { RSAPrivateCrtKey rsaKey = (RSAPrivateCrtKey) key; RSAPublicKeySpec pubKeySpec = new RSAPublicKeySpec(rsaKey.getModulus(), rsaKey.getPublicExponent()); try { factory = KeyFactory.getInstance("RSA"); return factory.generatePublic(pubKeySpec); } catch (GeneralSecurityException e) { throw new KeyException("Unable to derive public key from RSA private key", e); } } else { throw new KeyException("Private key was not a DSA or RSA key"); } }
From source file:org.panbox.core.crypto.CryptCore.java
/** * Converts a given RSA PrivateKey instance to a KeyPair instance. The * PublicKey will be extracted from PrivateKey instance. * /*from w w w .j a v a 2 s .c om*/ * @param pKey * The RSA PrivateKey used to generate the KeyPair * @return KeyPair instance including the private and public key. * @throws NoSuchAlgorithmException * @throws InvalidKeySpecException */ public static KeyPair privateKeyToKeyPair(PrivateKey pKey) throws NoSuchAlgorithmException, InvalidKeySpecException { KeyFactory keyFactory = KeyFactory.getInstance(KeyConstants.KEY_FACTORY, new BouncyCastleProvider()); RSAPrivateCrtKey rsaPKey = (RSAPrivateCrtKey) pKey; RSAPublicKeySpec publicKeySpec = new java.security.spec.RSAPublicKeySpec(rsaPKey.getModulus(), rsaPKey.getPublicExponent()); return new KeyPair(keyFactory.generatePublic(publicKeySpec), pKey); }
From source file:test.be.fedict.eid.applet.RSATest.java
@Test public void testManualEncryption() throws Exception { while (true) { KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA", BouncyCastleProvider.PROVIDER_NAME); SecureRandom random = new SecureRandom(); int keySize = 128; keyPairGenerator.initialize(new RSAKeyGenParameterSpec(keySize, RSAKeyGenParameterSpec.F0), random); KeyPair keyPair = keyPairGenerator.generateKeyPair(); PrivateKey privateKey = keyPair.getPrivate(); PublicKey publicKey = keyPair.getPublic(); RSAPrivateCrtKey rsaPrivateKey = (RSAPrivateCrtKey) privateKey; LOG.debug("private key modulus: " + rsaPrivateKey.getModulus()); RSAPublicKey rsaPublicKey = (RSAPublicKey) publicKey; LOG.debug("public key modulus: " + rsaPublicKey.getModulus()); LOG.debug("public key exponent: " + rsaPublicKey.getPublicExponent()); LOG.debug("modulus size: " + rsaPublicKey.getModulus().toByteArray().length); Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding"); cipher.init(Cipher.ENCRYPT_MODE, privateKey); int dataSize = keySize / 8 - 11; byte[] data1 = new byte[dataSize]; for (int i = 0; i < data1.length; i++) { data1[i] = 0x00;//from ww w .j a v a 2 s . c o m } byte[] data2 = new byte[dataSize]; for (int i = 0; i < data2.length; i++) { data2[i] = 0x00; } data2[data2.length - 1] = 0x07; byte[] signatureValue1 = cipher.doFinal(data1); LOG.debug("signature size: " + signatureValue1.length); cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding"); cipher.init(Cipher.ENCRYPT_MODE, privateKey); byte[] signatureValue2 = cipher.doFinal(data2); BigInteger sigBigInt1 = new BigInteger(signatureValue1); BigInteger sigBigInt2 = new BigInteger(signatureValue2); BigInteger msgBigInt1 = sigBigInt1.modPow(rsaPublicKey.getPublicExponent(), rsaPublicKey.getModulus()); BigInteger msgBigInt2 = sigBigInt2.modPow(rsaPublicKey.getPublicExponent(), rsaPublicKey.getModulus()); LOG.debug("msg big int: " + msgBigInt1); byte[] msgBytes1 = msgBigInt1.toByteArray(); LOG.debug("original message size: " + msgBytes1.length); LOG.debug("original message1: " + new String(Hex.encodeHex(msgBytes1))); LOG.debug("original message2: " + new String(Hex.encodeHex(msgBigInt2.toByteArray()))); LOG.debug("msg1 prime: " + msgBigInt1.isProbablePrime(100)); LOG.debug("msg2 prime: " + msgBigInt2.isProbablePrime(100)); // BigInteger.pow offers a very naive implementation LOG.debug("calculating s1^e..."); BigInteger s1_e = sigBigInt1.pow(rsaPublicKey.getPublicExponent().intValue()); LOG.debug("s1^e: " + s1_e); LOG.debug("calculating s2^e..."); BigInteger s2_e = sigBigInt2.pow(rsaPublicKey.getPublicExponent().intValue()); LOG.debug("s2^e: " + s2_e); LOG.debug("calculating GCD..."); LOG.debug("msg1: " + msgBigInt1); LOG.debug("msg2: " + msgBigInt2); BigInteger a = s1_e.subtract(msgBigInt1); BigInteger b = s2_e.subtract(msgBigInt2); LOG.debug("a: " + a); LOG.debug("b: " + b); BigInteger candidateModulus = a.gcd(b); LOG.debug("candidate modulus: " + candidateModulus); LOG.debug("candidate modulus size: " + candidateModulus.toByteArray().length); BigInteger s_e = s1_e.multiply(s2_e); BigInteger m = msgBigInt1.multiply(msgBigInt2); while (false == rsaPublicKey.getModulus().equals(candidateModulus)) { LOG.error("incorrect candidate modulus"); LOG.debug("modulus | candidate modulus: " + candidateModulus.remainder(rsaPublicKey.getModulus()).equals(BigInteger.ZERO)); s_e = s_e.multiply(s1_e); m = m.multiply(msgBigInt1); BigInteger n1 = s_e.subtract(m).gcd(a); BigInteger n2 = s_e.subtract(m).gcd(b); candidateModulus = n1.gcd(n2); // try / 2 LOG.debug("new modulus: " + n1); LOG.debug("new modulus: " + n2); LOG.debug("candidate modulus: " + candidateModulus); LOG.debug("actual mod: " + rsaPublicKey.getModulus()); } } }