java.security.interfaces.RSAPrivateCrtKey Java Examples

The following examples show how to use java.security.interfaces.RSAPrivateCrtKey. 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: KeyStore.java    From jdk8u-jdk with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Sets the private key for the keystore entry.
 */
void setPrivateKey(RSAPrivateCrtKey key)
    throws InvalidKeyException, KeyStoreException
{
    byte[] modulusBytes = key.getModulus().toByteArray();

    // Adjust key length due to sign bit
    int keyBitLength = (modulusBytes[0] == 0)
        ? (modulusBytes.length - 1) * 8
        : modulusBytes.length * 8;

    byte[] keyBlob = generatePrivateKeyBlob(
        keyBitLength,
        modulusBytes,
        key.getPublicExponent().toByteArray(),
        key.getPrivateExponent().toByteArray(),
        key.getPrimeP().toByteArray(),
        key.getPrimeQ().toByteArray(),
        key.getPrimeExponentP().toByteArray(),
        key.getPrimeExponentQ().toByteArray(),
        key.getCrtCoefficient().toByteArray());

    privateKey = storePrivateKey(Objects.requireNonNull(keyBlob),
        "{" + UUID.randomUUID().toString() + "}", keyBitLength);
}
 
Example #2
Source File: KeyStore.java    From jdk8u-jdk with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Sets the private key for the keystore entry.
 */
void setPrivateKey(RSAPrivateCrtKey key)
    throws InvalidKeyException, KeyStoreException
{
    byte[] modulusBytes = key.getModulus().toByteArray();

    // Adjust key length due to sign bit
    int keyBitLength = (modulusBytes[0] == 0)
        ? (modulusBytes.length - 1) * 8
        : modulusBytes.length * 8;

    byte[] keyBlob = generatePrivateKeyBlob(
        keyBitLength,
        modulusBytes,
        key.getPublicExponent().toByteArray(),
        key.getPrivateExponent().toByteArray(),
        key.getPrimeP().toByteArray(),
        key.getPrimeQ().toByteArray(),
        key.getPrimeExponentP().toByteArray(),
        key.getPrimeExponentQ().toByteArray(),
        key.getCrtCoefficient().toByteArray());

    privateKey = storePrivateKey(keyBlob,
        "{" + UUID.randomUUID().toString() + "}", keyBitLength);
}
 
Example #3
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 #4
Source File: Bug6415637.java    From TencentKona-8 with GNU General Public License v2.0 6 votes vote down vote up
private static void check(String encodedBlob) throws Exception {
    byte[] blob = new byte[encodedBlob.length() * 2];
    for (int i = 0; i < blob.length; ) {
        final char ch = encodedBlob.charAt(i / 2);
        blob[i++] = (byte) (ch >> 8);
        blob[i++] = (byte) ch;
    }
    KeyStore store = KeyStore.getInstance("PKCS12");
    store.load(new ByteArrayInputStream(blob), new char[0]);
    if (!store.aliases().nextElement().equals("test"))
        throw new Exception("test alias not found");
    KeyStore.PrivateKeyEntry e =
        (KeyStore.PrivateKeyEntry) store.getEntry("test",
                new KeyStore.PasswordProtection(new char[0]));
    X509Certificate cert = (X509Certificate) e.getCertificateChain()[0];
    if (!cert.getSubjectDN().toString().equals("CN=Test Key"))
        throw new Exception("invalid certificate subject DN");
    RSAPrivateCrtKey key = (RSAPrivateCrtKey) e.getPrivateKey();
    if (!key.getPublicExponent().equals(BigInteger.valueOf(65537)))
        throw new Exception("invalid public exponent");
}
 
Example #5
Source File: ModPowVectors.java    From jna-gmp with Apache License 2.0 6 votes vote down vote up
private static void generateTestVector(int rsaKeyBits, int suffix) throws Exception {
  KeyPair pair = generateKeyPair(rsaKeyBits);
  RSAPrivateCrtKey priv = (RSAPrivateCrtKey) pair.getPrivate();

  // The core RSA private key operation is doing the modPow for the two components.
  BigInteger p = priv.getPrimeP();
  BigInteger dp = priv.getPrimeExponentP();
  BigInteger q = priv.getPrimeQ();
  BigInteger dq = priv.getPrimeExponentQ();

  byte[] random = new byte[rsaKeyBits / 8];
  SECURE_RANDOM.nextBytes(random);
  // Clear the top bit to ensure it fits.
  random[0] &= 0x7F;
  BigInteger message = new BigInteger(1, random);
  BigInteger pResult = message.modPow(dp, p);
  BigInteger qResult = message.modPow(dq, q);

  System.out.println("public static final TestVector VECTOR" + suffix + " = ");
  new TestVector(message, p, dp, pResult, q, dq, qResult).printJavaConstructorFor();
  System.out.println();
}
 
Example #6
Source File: KeyStore.java    From openjdk-8 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Sets the private key for the keystore entry.
 */
void setPrivateKey(RSAPrivateCrtKey key)
    throws InvalidKeyException, KeyStoreException
{
    byte[] modulusBytes = key.getModulus().toByteArray();

    // Adjust key length due to sign bit
    int keyBitLength = (modulusBytes[0] == 0)
        ? (modulusBytes.length - 1) * 8
        : modulusBytes.length * 8;

    byte[] keyBlob = generatePrivateKeyBlob(
        keyBitLength,
        modulusBytes,
        key.getPublicExponent().toByteArray(),
        key.getPrivateExponent().toByteArray(),
        key.getPrimeP().toByteArray(),
        key.getPrimeQ().toByteArray(),
        key.getPrimeExponentP().toByteArray(),
        key.getPrimeExponentQ().toByteArray(),
        key.getCrtCoefficient().toByteArray());

    privateKey = storePrivateKey(keyBlob,
        "{" + UUID.randomUUID().toString() + "}", keyBitLength);
}
 
Example #7
Source File: Bug6415637.java    From openjdk-8 with GNU General Public License v2.0 6 votes vote down vote up
private static void check(String encodedBlob) throws Exception {
    byte[] blob = new byte[encodedBlob.length() * 2];
    for (int i = 0; i < blob.length; ) {
        final char ch = encodedBlob.charAt(i / 2);
        blob[i++] = (byte) (ch >> 8);
        blob[i++] = (byte) ch;
    }
    KeyStore store = KeyStore.getInstance("PKCS12");
    store.load(new ByteArrayInputStream(blob), new char[0]);
    if (!store.aliases().nextElement().equals("test"))
        throw new Exception("test alias not found");
    KeyStore.PrivateKeyEntry e =
        (KeyStore.PrivateKeyEntry) store.getEntry("test",
                new KeyStore.PasswordProtection(new char[0]));
    X509Certificate cert = (X509Certificate) e.getCertificateChain()[0];
    if (!cert.getSubjectDN().toString().equals("CN=Test Key"))
        throw new Exception("invalid certificate subject DN");
    RSAPrivateCrtKey key = (RSAPrivateCrtKey) e.getPrivateKey();
    if (!key.getPublicExponent().equals(BigInteger.valueOf(65537)))
        throw new Exception("invalid public exponent");
}
 
Example #8
Source File: KeyStoreKeyFactory.java    From MaxKey with Apache License 2.0 6 votes vote down vote up
public KeyPair getKeyPair(String alias, char[] password) {
	try {
		synchronized (lock) {
			if (store == null) {
				synchronized (lock) {
					store = KeyStore.getInstance("jks");
					store.load(resource.getInputStream(), this.password);
				}
			}
		}
		RSAPrivateCrtKey key = (RSAPrivateCrtKey) store.getKey(alias, password);
		RSAPublicKeySpec spec = new RSAPublicKeySpec(key.getModulus(), key.getPublicExponent());
		PublicKey publicKey = KeyFactory.getInstance("RSA").generatePublic(spec);
		return new KeyPair(publicKey, key);
	}
	catch (Exception e) {
		throw new IllegalStateException("Cannot load keys from store: " + resource, e);
	}
}
 
Example #9
Source File: KeyStore.java    From dragonwell8_jdk with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Sets the private key for the keystore entry.
 */
void setPrivateKey(RSAPrivateCrtKey key)
    throws InvalidKeyException, KeyStoreException
{
    byte[] modulusBytes = key.getModulus().toByteArray();

    // Adjust key length due to sign bit
    int keyBitLength = (modulusBytes[0] == 0)
        ? (modulusBytes.length - 1) * 8
        : modulusBytes.length * 8;

    byte[] keyBlob = generatePrivateKeyBlob(
        keyBitLength,
        modulusBytes,
        key.getPublicExponent().toByteArray(),
        key.getPrivateExponent().toByteArray(),
        key.getPrimeP().toByteArray(),
        key.getPrimeQ().toByteArray(),
        key.getPrimeExponentP().toByteArray(),
        key.getPrimeExponentQ().toByteArray(),
        key.getCrtCoefficient().toByteArray());

    privateKey = storePrivateKey(Objects.requireNonNull(keyBlob),
        "{" + UUID.randomUUID().toString() + "}", keyBitLength);
}
 
Example #10
Source File: Bug6415637.java    From jdk8u_jdk with GNU General Public License v2.0 6 votes vote down vote up
private static void check(String encodedBlob) throws Exception {
    byte[] blob = new byte[encodedBlob.length() * 2];
    for (int i = 0; i < blob.length; ) {
        final char ch = encodedBlob.charAt(i / 2);
        blob[i++] = (byte) (ch >> 8);
        blob[i++] = (byte) ch;
    }
    KeyStore store = KeyStore.getInstance("PKCS12");
    store.load(new ByteArrayInputStream(blob), new char[0]);
    if (!store.aliases().nextElement().equals("test"))
        throw new Exception("test alias not found");
    KeyStore.PrivateKeyEntry e =
        (KeyStore.PrivateKeyEntry) store.getEntry("test",
                new KeyStore.PasswordProtection(new char[0]));
    X509Certificate cert = (X509Certificate) e.getCertificateChain()[0];
    if (!cert.getSubjectDN().toString().equals("CN=Test Key"))
        throw new Exception("invalid certificate subject DN");
    RSAPrivateCrtKey key = (RSAPrivateCrtKey) e.getPrivateKey();
    if (!key.getPublicExponent().equals(BigInteger.valueOf(65537)))
        throw new Exception("invalid public exponent");
}
 
Example #11
Source File: Bug6415637.java    From dragonwell8_jdk with GNU General Public License v2.0 6 votes vote down vote up
private static void check(String encodedBlob) throws Exception {
    byte[] blob = new byte[encodedBlob.length() * 2];
    for (int i = 0; i < blob.length; ) {
        final char ch = encodedBlob.charAt(i / 2);
        blob[i++] = (byte) (ch >> 8);
        blob[i++] = (byte) ch;
    }
    KeyStore store = KeyStore.getInstance("PKCS12");
    store.load(new ByteArrayInputStream(blob), new char[0]);
    if (!store.aliases().nextElement().equals("test"))
        throw new Exception("test alias not found");
    KeyStore.PrivateKeyEntry e =
        (KeyStore.PrivateKeyEntry) store.getEntry("test",
                new KeyStore.PasswordProtection(new char[0]));
    X509Certificate cert = (X509Certificate) e.getCertificateChain()[0];
    if (!cert.getSubjectDN().toString().equals("CN=Test Key"))
        throw new Exception("invalid certificate subject DN");
    RSAPrivateCrtKey key = (RSAPrivateCrtKey) e.getPrivateKey();
    if (!key.getPublicExponent().equals(BigInteger.valueOf(65537)))
        throw new Exception("invalid public exponent");
}
 
Example #12
Source File: Bug6415637.java    From jdk8u-dev-jdk with GNU General Public License v2.0 6 votes vote down vote up
private static void check(String encodedBlob) throws Exception {
    byte[] blob = new byte[encodedBlob.length() * 2];
    for (int i = 0; i < blob.length; ) {
        final char ch = encodedBlob.charAt(i / 2);
        blob[i++] = (byte) (ch >> 8);
        blob[i++] = (byte) ch;
    }
    KeyStore store = KeyStore.getInstance("PKCS12");
    store.load(new ByteArrayInputStream(blob), new char[0]);
    if (!store.aliases().nextElement().equals("test"))
        throw new Exception("test alias not found");
    KeyStore.PrivateKeyEntry e =
        (KeyStore.PrivateKeyEntry) store.getEntry("test",
                new KeyStore.PasswordProtection(new char[0]));
    X509Certificate cert = (X509Certificate) e.getCertificateChain()[0];
    if (!cert.getSubjectDN().toString().equals("CN=Test Key"))
        throw new Exception("invalid certificate subject DN");
    RSAPrivateCrtKey key = (RSAPrivateCrtKey) e.getPrivateKey();
    if (!key.getPublicExponent().equals(BigInteger.valueOf(65537)))
        throw new Exception("invalid public exponent");
}
 
Example #13
Source File: KeyStore.java    From jdk8u60 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Sets the private key for the keystore entry.
 */
void setPrivateKey(RSAPrivateCrtKey key)
    throws InvalidKeyException, KeyStoreException
{
    byte[] modulusBytes = key.getModulus().toByteArray();

    // Adjust key length due to sign bit
    int keyBitLength = (modulusBytes[0] == 0)
        ? (modulusBytes.length - 1) * 8
        : modulusBytes.length * 8;

    byte[] keyBlob = generatePrivateKeyBlob(
        keyBitLength,
        modulusBytes,
        key.getPublicExponent().toByteArray(),
        key.getPrivateExponent().toByteArray(),
        key.getPrimeP().toByteArray(),
        key.getPrimeQ().toByteArray(),
        key.getPrimeExponentP().toByteArray(),
        key.getPrimeExponentQ().toByteArray(),
        key.getCrtCoefficient().toByteArray());

    privateKey = storePrivateKey(Objects.requireNonNull(keyBlob),
        "{" + UUID.randomUUID().toString() + "}", keyBitLength);
}
 
Example #14
Source File: KeyFactorySpi.java    From RipplePower with Apache License 2.0 6 votes vote down vote up
protected Key engineTranslateKey(
    Key key)
    throws InvalidKeyException
{
    if (key instanceof RSAPublicKey)
    {
        return new BCRSAPublicKey((RSAPublicKey)key);
    }
    else if (key instanceof RSAPrivateCrtKey)
    {
        return new BCRSAPrivateCrtKey((RSAPrivateCrtKey)key);
    }
    else if (key instanceof java.security.interfaces.RSAPrivateKey)
    {
        return new BCRSAPrivateKey((java.security.interfaces.RSAPrivateKey)key);
    }

    throw new InvalidKeyException("key type unknown");
}
 
Example #15
Source File: Bug6415637.java    From openjdk-8-source with GNU General Public License v2.0 6 votes vote down vote up
private static void check(String encodedBlob) throws Exception {
    byte[] blob = new byte[encodedBlob.length() * 2];
    for (int i = 0; i < blob.length; ) {
        final char ch = encodedBlob.charAt(i / 2);
        blob[i++] = (byte) (ch >> 8);
        blob[i++] = (byte) ch;
    }
    KeyStore store = KeyStore.getInstance("PKCS12");
    store.load(new ByteArrayInputStream(blob), new char[0]);
    if (!store.aliases().nextElement().equals("test"))
        throw new Exception("test alias not found");
    KeyStore.PrivateKeyEntry e =
        (KeyStore.PrivateKeyEntry) store.getEntry("test",
                new KeyStore.PasswordProtection(new char[0]));
    X509Certificate cert = (X509Certificate) e.getCertificateChain()[0];
    if (!cert.getSubjectDN().toString().equals("CN=Test Key"))
        throw new Exception("invalid certificate subject DN");
    RSAPrivateCrtKey key = (RSAPrivateCrtKey) e.getPrivateKey();
    if (!key.getPublicExponent().equals(BigInteger.valueOf(65537)))
        throw new Exception("invalid public exponent");
}
 
Example #16
Source File: KeyStore.java    From openjdk-8-source with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Sets the private key for the keystore entry.
 */
void setPrivateKey(RSAPrivateCrtKey key)
    throws InvalidKeyException, KeyStoreException
{
    byte[] modulusBytes = key.getModulus().toByteArray();

    // Adjust key length due to sign bit
    int keyBitLength = (modulusBytes[0] == 0)
        ? (modulusBytes.length - 1) * 8
        : modulusBytes.length * 8;

    byte[] keyBlob = generatePrivateKeyBlob(
        keyBitLength,
        modulusBytes,
        key.getPublicExponent().toByteArray(),
        key.getPrivateExponent().toByteArray(),
        key.getPrimeP().toByteArray(),
        key.getPrimeQ().toByteArray(),
        key.getPrimeExponentP().toByteArray(),
        key.getPrimeExponentQ().toByteArray(),
        key.getCrtCoefficient().toByteArray());

    privateKey = storePrivateKey(keyBlob,
        "{" + UUID.randomUUID().toString() + "}", keyBitLength);
}
 
Example #17
Source File: ExportKeyPairPrivateKeyAction.java    From keystore-explorer with GNU General Public License v3.0 6 votes vote down vote up
private byte[] getPvkEncodedPrivateKey(PrivateKey privateKey, int keyType, Password password,
		boolean strongEncryption) throws CryptoException, IOException {
	byte[] encoded = null;

	if (password != null) {
		if (privateKey instanceof RSAPrivateCrtKey) {
			encoded = MsPvkUtil.getEncrypted((RSAPrivateCrtKey) privateKey, keyType, password, strongEncryption);
		} else {
			encoded = MsPvkUtil.getEncrypted((DSAPrivateKey) privateKey, password, strongEncryption);
		}
	} else {
		if (privateKey instanceof RSAPrivateCrtKey) {
			encoded = MsPvkUtil.get((RSAPrivateCrtKey) privateKey, keyType);
		} else {
			encoded = MsPvkUtil.get((DSAPrivateKey) privateKey);
		}
	}

	return encoded;
}
 
Example #18
Source File: SignatureUtil.java    From jam-collaboration-sample with Apache License 2.0 6 votes vote down vote up
/**
 * Returns XML suitable for use in .NET code with the RSACryptoServiceProvider.FromXmlString method.
 * This RSACryptoServiceProvider object can be used in the .NET version of the OAuth libraries in the areas
 * where we use a PrivateKey object in the Java libraries. 
 * An explanation of the XML used for key formats is here: http://msdn.microsoft.com/en-us/library/system.security.cryptography.rsa.toxmlstring.aspx
 * Thanks to http://www.jensign.com/JavaScience/PvkConvert/ for pointing out that leading zeros must be trimmed for .NET.
 */
public static String privateKeyToDotNetXml(PrivateKey privateKey) {
    try{
        StringBuilder sb = new StringBuilder();
        RSAPrivateCrtKey rsaPrivateKey = (RSAPrivateCrtKey)privateKey;
        sb.append("<RSAKeyValue>") ;
        sb.append("<Modulus>" + Base64Util.encode(removeLeadingZeros(rsaPrivateKey.getModulus().toByteArray())) + "</Modulus>");
        sb.append("<Exponent>" + Base64Util.encode(removeLeadingZeros(rsaPrivateKey.getPublicExponent().toByteArray())) + "</Exponent>");
        sb.append("<P>" + Base64Util.encode(removeLeadingZeros(rsaPrivateKey.getPrimeP().toByteArray())) + "</P>");
        sb.append("<Q>" + Base64Util.encode(removeLeadingZeros(rsaPrivateKey.getPrimeQ().toByteArray())) + "</Q>");
        sb.append("<DP>" +Base64Util.encode(removeLeadingZeros(rsaPrivateKey.getPrimeExponentP().toByteArray())) + "</DP>");
        sb.append("<DQ>" + Base64Util.encode(removeLeadingZeros(rsaPrivateKey.getPrimeExponentQ().toByteArray())) + "</DQ>");
        sb.append("<InverseQ>" + Base64Util.encode(removeLeadingZeros(rsaPrivateKey.getCrtCoefficient().toByteArray())) + "</InverseQ>");
        sb.append("<D>" + Base64Util.encode(removeLeadingZeros(rsaPrivateKey.getPrivateExponent().toByteArray())) + "</D>");
        sb.append("</RSAKeyValue>") ;
        return sb.toString();
    } catch(Exception e) {
        throw new IllegalArgumentException("Could not convert PrivateKey to Dot Net XML.", e);
    }   
}
 
Example #19
Source File: Bug6415637.java    From openjdk-jdk8u with GNU General Public License v2.0 6 votes vote down vote up
private static void check(String encodedBlob) throws Exception {
    byte[] blob = new byte[encodedBlob.length() * 2];
    for (int i = 0; i < blob.length; ) {
        final char ch = encodedBlob.charAt(i / 2);
        blob[i++] = (byte) (ch >> 8);
        blob[i++] = (byte) ch;
    }
    KeyStore store = KeyStore.getInstance("PKCS12");
    store.load(new ByteArrayInputStream(blob), new char[0]);
    if (!store.aliases().nextElement().equals("test"))
        throw new Exception("test alias not found");
    KeyStore.PrivateKeyEntry e =
        (KeyStore.PrivateKeyEntry) store.getEntry("test",
                new KeyStore.PasswordProtection(new char[0]));
    X509Certificate cert = (X509Certificate) e.getCertificateChain()[0];
    if (!cert.getSubjectDN().toString().equals("CN=Test Key"))
        throw new Exception("invalid certificate subject DN");
    RSAPrivateCrtKey key = (RSAPrivateCrtKey) e.getPrivateKey();
    if (!key.getPublicExponent().equals(BigInteger.valueOf(65537)))
        throw new Exception("invalid public exponent");
}
 
Example #20
Source File: MsPvkUtil.java    From keystore-explorer with GNU General Public License v3.0 6 votes vote down vote up
private static void writePrivateKeyBlobHeader(ByteBuffer bb, long keyType, PrivateKey privateKey)
		throws IOException {
	// Write Key blob type - private key
	UnsignedUtil.putByte(bb, PRIVATE_KEY_BLOB);

	// Write Blob version
	UnsignedUtil.putByte(bb, CUR_BLOB_VERSION);

	// Write Reserved value
	UnsignedUtil.putShort(bb, BLOB_RESERVED);

	// Write Algorithm ID - differs depending on key type and key pair type
	if (keyType == PVK_KEY_SIGNATURE) {
		if (privateKey instanceof RSAPrivateCrtKey) {
			UnsignedUtil.putInt(bb, CALG_RSA_SIGN); // RSA signature
		} else {
			UnsignedUtil.putInt(bb, CALG_DSS_SIGN); // DSA signature
		}
	} else {
		UnsignedUtil.putInt(bb, CALG_RSA_KEYX); // Key exchange - RSA only
	}
}
 
Example #21
Source File: Bug6415637.java    From hottub with GNU General Public License v2.0 6 votes vote down vote up
private static void check(String encodedBlob) throws Exception {
    byte[] blob = new byte[encodedBlob.length() * 2];
    for (int i = 0; i < blob.length; ) {
        final char ch = encodedBlob.charAt(i / 2);
        blob[i++] = (byte) (ch >> 8);
        blob[i++] = (byte) ch;
    }
    KeyStore store = KeyStore.getInstance("PKCS12");
    store.load(new ByteArrayInputStream(blob), new char[0]);
    if (!store.aliases().nextElement().equals("test"))
        throw new Exception("test alias not found");
    KeyStore.PrivateKeyEntry e =
        (KeyStore.PrivateKeyEntry) store.getEntry("test",
                new KeyStore.PasswordProtection(new char[0]));
    X509Certificate cert = (X509Certificate) e.getCertificateChain()[0];
    if (!cert.getSubjectDN().toString().equals("CN=Test Key"))
        throw new Exception("invalid certificate subject DN");
    RSAPrivateCrtKey key = (RSAPrivateCrtKey) e.getPrivateKey();
    if (!key.getPublicExponent().equals(BigInteger.valueOf(65537)))
        throw new Exception("invalid public exponent");
}
 
Example #22
Source File: JsonWebKey.java    From azure-keyvault-java with MIT License 6 votes vote down vote up
/**
 * Converts RSA key pair to JSON web key.
 * 
 * @param keyPair
 *            RSA key pair
 * @return the JSON web key, converted from RSA key pair.
 */
public static JsonWebKey fromRSA(KeyPair keyPair) {

    RSAPrivateCrtKey privateKey = (RSAPrivateCrtKey) keyPair.getPrivate();
    JsonWebKey key = null;

    if (privateKey != null) {

        key = new JsonWebKey().withKty(JsonWebKeyType.RSA).withN(toByteArray(privateKey.getModulus()))
                .withE(toByteArray(privateKey.getPublicExponent()))
                .withD(toByteArray(privateKey.getPrivateExponent())).withP(toByteArray(privateKey.getPrimeP()))
                .withQ(toByteArray(privateKey.getPrimeQ())).withDp(toByteArray(privateKey.getPrimeExponentP()))
                .withDq(toByteArray(privateKey.getPrimeExponentQ()))
                .withQi(toByteArray(privateKey.getCrtCoefficient()));
    } else {

        RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();

        key = new JsonWebKey().withKty(JsonWebKeyType.RSA).withN(toByteArray(publicKey.getModulus()))
                .withE(toByteArray(publicKey.getPublicExponent())).withD(null).withP(null).withQ(null).withDp(null)
                .withDq(null).withQi(null);
    }

    return key;
}
 
Example #23
Source File: Bug6415637.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 6 votes vote down vote up
private static void check(String encodedBlob) throws Exception {
    byte[] blob = new byte[encodedBlob.length() * 2];
    for (int i = 0; i < blob.length; ) {
        final char ch = encodedBlob.charAt(i / 2);
        blob[i++] = (byte) (ch >> 8);
        blob[i++] = (byte) ch;
    }
    KeyStore store = KeyStore.getInstance("PKCS12");
    store.load(new ByteArrayInputStream(blob), new char[0]);
    if (!store.aliases().nextElement().equals("test"))
        throw new Exception("test alias not found");
    KeyStore.PrivateKeyEntry e =
        (KeyStore.PrivateKeyEntry) store.getEntry("test",
                new KeyStore.PasswordProtection(new char[0]));
    X509Certificate cert = (X509Certificate) e.getCertificateChain()[0];
    if (!cert.getSubjectDN().toString().equals("CN=Test Key"))
        throw new Exception("invalid certificate subject DN");
    RSAPrivateCrtKey key = (RSAPrivateCrtKey) e.getPrivateKey();
    if (!key.getPublicExponent().equals(BigInteger.valueOf(65537)))
        throw new Exception("invalid public exponent");
}
 
Example #24
Source File: KeyStore.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Sets the private key for the keystore entry.
 */
void setPrivateKey(RSAPrivateCrtKey key)
    throws InvalidKeyException, KeyStoreException
{
    byte[] modulusBytes = key.getModulus().toByteArray();

    // Adjust key length due to sign bit
    int keyBitLength = (modulusBytes[0] == 0)
        ? (modulusBytes.length - 1) * 8
        : modulusBytes.length * 8;

    byte[] keyBlob = generatePrivateKeyBlob(
        keyBitLength,
        modulusBytes,
        key.getPublicExponent().toByteArray(),
        key.getPrivateExponent().toByteArray(),
        key.getPrimeP().toByteArray(),
        key.getPrimeQ().toByteArray(),
        key.getPrimeExponentP().toByteArray(),
        key.getPrimeExponentQ().toByteArray(),
        key.getCrtCoefficient().toByteArray());

    privateKey = storePrivateKey(Objects.requireNonNull(keyBlob),
        "{" + UUID.randomUUID().toString() + "}", keyBitLength);
}
 
Example #25
Source File: JCERSAPrivateCrtKey.java    From RipplePower with Apache License 2.0 6 votes vote down vote up
public boolean equals(Object o)
{
    if (o == this)
    {
        return true;
    }

    if (!(o instanceof RSAPrivateCrtKey))
    {
        return false;
    }

    RSAPrivateCrtKey key = (RSAPrivateCrtKey)o;

    return this.getModulus().equals(key.getModulus())
     && this.getPublicExponent().equals(key.getPublicExponent())
     && this.getPrivateExponent().equals(key.getPrivateExponent())
     && this.getPrimeP().equals(key.getPrimeP())
     && this.getPrimeQ().equals(key.getPrimeQ())
     && this.getPrimeExponentP().equals(key.getPrimeExponentP())
     && this.getPrimeExponentQ().equals(key.getPrimeExponentQ())
     && this.getCrtCoefficient().equals(key.getCrtCoefficient());
}
 
Example #26
Source File: Bug6415637.java    From jdk8u-jdk with GNU General Public License v2.0 6 votes vote down vote up
private static void check(String encodedBlob) throws Exception {
    byte[] blob = new byte[encodedBlob.length() * 2];
    for (int i = 0; i < blob.length; ) {
        final char ch = encodedBlob.charAt(i / 2);
        blob[i++] = (byte) (ch >> 8);
        blob[i++] = (byte) ch;
    }
    KeyStore store = KeyStore.getInstance("PKCS12");
    store.load(new ByteArrayInputStream(blob), new char[0]);
    if (!store.aliases().nextElement().equals("test"))
        throw new Exception("test alias not found");
    KeyStore.PrivateKeyEntry e =
        (KeyStore.PrivateKeyEntry) store.getEntry("test",
                new KeyStore.PasswordProtection(new char[0]));
    X509Certificate cert = (X509Certificate) e.getCertificateChain()[0];
    if (!cert.getSubjectDN().toString().equals("CN=Test Key"))
        throw new Exception("invalid certificate subject DN");
    RSAPrivateCrtKey key = (RSAPrivateCrtKey) e.getPrivateKey();
    if (!key.getPublicExponent().equals(BigInteger.valueOf(65537)))
        throw new Exception("invalid public exponent");
}
 
Example #27
Source File: OpenSslPvkUtil.java    From keystore-explorer with GNU General Public License v3.0 6 votes vote down vote up
/**
 * OpenSSL encode a private key and PEM the encoding.
 *
 * @return The PEM'd encoding
 * @param privateKey
 *            The private key
 * @throws CryptoException
 *             Problem encountered while getting the encoded private key
 */
public static String getPem(PrivateKey privateKey) throws CryptoException {
	byte[] openSsl = get(privateKey);

	String pemType = null;

	if (privateKey instanceof RSAPrivateCrtKey) {
		pemType = OPENSSL_RSA_PVK_PEM_TYPE;
	} else if (privateKey instanceof ECPrivateKey) {
		pemType = OPENSSL_EC_PVK_PEM_TYPE;
	} else {
		pemType = OPENSSL_DSA_PVK_PEM_TYPE;
	}

	PemInfo pemInfo = new PemInfo(pemType, null, openSsl);
	String openSslPem = PemUtil.encode(pemInfo);

	return openSslPem;
}
 
Example #28
Source File: RsaJsonWebKey.java    From Jose4j with Apache License 2.0 6 votes vote down vote up
protected void fillPrivateTypeSpecificParams(Map<String,Object> params)
{
    RSAPrivateKey rsaPrivateKey = getRsaPrivateKey();
    
    if (rsaPrivateKey != null) 
    {
        putBigIntAsBase64UrlEncodedParam(params, PRIVATE_EXPONENT_MEMBER_NAME, rsaPrivateKey.getPrivateExponent());

     if (rsaPrivateKey instanceof RSAPrivateCrtKey)
     {
         RSAPrivateCrtKey crt = (RSAPrivateCrtKey) rsaPrivateKey;
         putBigIntAsBase64UrlEncodedParam(params, FIRST_PRIME_FACTOR_MEMBER_NAME, crt.getPrimeP());
         putBigIntAsBase64UrlEncodedParam(params, SECOND_PRIME_FACTOR_MEMBER_NAME, crt.getPrimeQ());
         putBigIntAsBase64UrlEncodedParam(params, FIRST_FACTOR_CRT_EXPONENT_MEMBER_NAME, crt.getPrimeExponentP());
         putBigIntAsBase64UrlEncodedParam(params, SECOND_FACTOR_CRT_EXPONENT_MEMBER_NAME, crt.getPrimeExponentQ());
         putBigIntAsBase64UrlEncodedParam(params, FIRST_CRT_COEFFICIENT_MEMBER_NAME, crt.getCrtCoefficient());
     }
    }
}
 
Example #29
Source File: RsaPrivateKeyDef.java    From swim with Apache License 2.0 5 votes vote down vote up
public static RsaPrivateKeyDef from(RSAPrivateKey key) {
  if (key instanceof RSAMultiPrimePrivateCrtKey) {
    return from((RSAMultiPrimePrivateCrtKey) key);
  } else if (key instanceof RSAPrivateCrtKey) {
    return from((RSAPrivateCrtKey) key);
  } else {
    return new RsaPrivateKeyDef(key.getModulus(), key.getPrivateExponent(), key);
  }
}
 
Example #30
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());
  }
}