java.security.spec.RSAPrivateKeySpec Java Examples

The following examples show how to use java.security.spec.RSAPrivateKeySpec. 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: Encryption.java    From Wurst7 with GNU General Public License v3.0 7 votes vote down vote up
private KeyPair loadRsaKeys(Path publicFile, Path privateFile)
	throws GeneralSecurityException, ReflectiveOperationException,
	IOException
{
	KeyFactory factory = KeyFactory.getInstance("RSA");
	
	// load public key
	PublicKey publicKey;
	try(ObjectInputStream in =
		new ObjectInputStream(Files.newInputStream(publicFile)))
	{
		publicKey = factory.generatePublic(new RSAPublicKeySpec(
			(BigInteger)in.readObject(), (BigInteger)in.readObject()));
	}
	
	// load private key
	PrivateKey privateKey;
	try(ObjectInputStream in =
		new ObjectInputStream(Files.newInputStream(privateFile)))
	{
		privateKey = factory.generatePrivate(new RSAPrivateKeySpec(
			(BigInteger)in.readObject(), (BigInteger)in.readObject()));
	}
	
	return new KeyPair(publicKey, privateKey);
}
 
Example #2
Source File: KeyPairGen.java    From heisenberg with Apache License 2.0 6 votes vote down vote up
public static String decrypt(PublicKey publicKey, String cipherText)
  throws Exception
{
  Cipher cipher = Cipher.getInstance("RSA");
  try {
    cipher.init(2, publicKey);
  }
  catch (InvalidKeyException e)
  {
    RSAPublicKey rsaPublicKey = (RSAPublicKey)publicKey;
    RSAPrivateKeySpec spec = new RSAPrivateKeySpec(rsaPublicKey.getModulus(), rsaPublicKey.getPublicExponent());
    Key fakePrivateKey = KeyFactory.getInstance("RSA").generatePrivate(spec);
    cipher = Cipher.getInstance("RSA");
    cipher.init(2, fakePrivateKey);
  }

  if ((cipherText == null) || (cipherText.length() == 0)) {
    return cipherText;
  }

  byte[] cipherBytes = Base64.decodeBase64(cipherText);
  byte[] plainBytes = cipher.doFinal(cipherBytes);

  return new String(plainBytes);
}
 
Example #3
Source File: rsasign.java    From JrebelBrainsLicenseServerforJava with Apache License 2.0 6 votes vote down vote up
public static String Sign(byte[] content, String privateKey) {
try {
	byte[] keybyte = Base64.decode(privateKey.toString());
	ASN1InputStream in = new ASN1InputStream(keybyte);
	ASN1Primitive obj = in.readObject();
	RSAPrivateKeyStructure pStruct = RSAPrivateKeyStructure.getInstance(obj);
	RSAPrivateKeySpec spec = new RSAPrivateKeySpec(pStruct.getModulus(), pStruct.getPrivateExponent());
	KeyFactory keyFactory = KeyFactory.getInstance("RSA");
	PrivateKey priKey = keyFactory.generatePrivate(spec);
	java.security.Signature signature = java.security.Signature.getInstance("MD5WithRSA");
	signature.initSign(priKey);
	signature.update(content);
	byte[] signed = signature.sign();
	return Hex.bytesToHexString(signed);
       }
       catch (Exception e) {
           e.printStackTrace();
       }
       return null;
   }
 
Example #4
Source File: KeyGeneratorCli.java    From protect with MIT License 6 votes vote down vote up
public static KeyPair convertFromPaillier(final PaillierKeyPair paillierKeyPair)
		throws InvalidKeySpecException, NoSuchAlgorithmException {
	// Get keys
	final PaillierPrivateKey paillierPrivateKey = paillierKeyPair.getPrivateKey();
	final PaillierPublicKey paillierPublicKey = paillierKeyPair.getPublicKey();

	// Get fields
	final BigInteger n = paillierPublicKey.getN(); // treat as 'N'
	final BigInteger e = paillierPublicKey.getG(); // treat as 'e'
	final BigInteger d = paillierPrivateKey.getLambda(); // treat as 'd'

	// Represent them as RSA keys
	final RSAPrivateKeySpec privKeySpec = new RSAPrivateKeySpec(n, d);
	final RSAPublicKeySpec pubKeySpec = new RSAPublicKeySpec(n, e);

	// Convert to key pair
	final KeyFactory keyFactory = KeyFactory.getInstance("RSA");
	final PublicKey rsaPublic = keyFactory.generatePublic(pubKeySpec);
	final PrivateKey rsaPrivate = keyFactory.generatePrivate(privKeySpec);

	return new KeyPair(rsaPublic, rsaPrivate);
}
 
Example #5
Source File: IosRSAKeyFactory.java    From j2objc with Apache License 2.0 6 votes vote down vote up
@Override
 protected PrivateKey engineGeneratePrivate(KeySpec keySpec)
     throws InvalidKeySpecException {
  //The KeySpec for Private Key is PKCS8
if (keySpec instanceof PKCS8EncodedKeySpec ) {
  return new IosRSAKey.IosRSAPrivateKey(((PKCS8EncodedKeySpec) keySpec).getEncoded());  
}
   if (keySpec instanceof X509EncodedKeySpec) {
     X509EncodedKeySpec x509Spec = (X509EncodedKeySpec) keySpec;
     return new IosRSAKey.IosRSAPrivateKey(x509Spec.getEncoded());
   } else if (keySpec instanceof RSAPrivateKeySpec) {
     return new IosRSAKey.IosRSAPrivateKey((RSAPrivateKeySpec) keySpec);
   }
   throw new InvalidKeySpecException(
       "Must use PKCS8EncodedKeySpec, X509EncodedKeySpec or RSAPrivateKeySpec; was "
           + keySpec.getClass().getName());
 }
 
Example #6
Source File: RsaKeyPairGen.java    From sc2gears with Apache License 2.0 6 votes vote down vote up
public static void main( final String[] args ) throws Exception {
	final KeyPairGenerator kpGen = KeyPairGenerator.getInstance( "RSA" );
	kpGen.initialize( KEY_SIZE_BITS );
	final KeyPair kp = kpGen.generateKeyPair();
	
	final PublicKey  pubKey  = kp.getPublic();
	final PrivateKey privKey = kp.getPrivate();
    
	if ( DEBUG ) {
   		System.out.println( pubKey .getAlgorithm() + " " + pubKey .getFormat() + " " + pubKey .getEncoded().length );
   		System.out.println( privKey.getAlgorithm() + " " + privKey.getFormat() + " " + privKey.getEncoded().length );
	}
	
	final KeyFactory kf = KeyFactory.getInstance( "RSA" );
	final RSAPublicKeySpec  pubKeySpec  = kf.getKeySpec( pubKey , RSAPublicKeySpec .class );
	final RSAPrivateKeySpec privKeySpec = kf.getKeySpec( privKey, RSAPrivateKeySpec.class );
	
	if ( DEBUG ) {
		System.out.println( pubKeySpec .getModulus() + " " + pubKeySpec .getPublicExponent() );
		System.out.println( privKeySpec.getModulus() + " " + privKeySpec.getPrivateExponent() );
	}
	
	saveKey( pubKeySpec .getModulus(), pubKeySpec .getPublicExponent (), "w:/pubkey.rsa"  );
	saveKey( privKeySpec.getModulus(), privKeySpec.getPrivateExponent(), "w:/privkey.rsa" );
}
 
Example #7
Source File: ConfigTools.java    From MultimediaDesktop with Apache License 2.0 6 votes vote down vote up
public static String decrypt(PublicKey publicKey, String cipherText)
		throws Exception {
	Cipher cipher = Cipher.getInstance("RSA");
	try {
		cipher.init(Cipher.DECRYPT_MODE, publicKey);
	} catch (InvalidKeyException e) {
           // 因为 IBM JDK 不支持私钥加密, 公钥解密, 所以要反转公私钥
           // 也就是说对于解密, 可以通过公钥的参数伪造一个私钥对象欺骗 IBM JDK
           RSAPublicKey rsaPublicKey = (RSAPublicKey) publicKey;
           RSAPrivateKeySpec spec = new RSAPrivateKeySpec(rsaPublicKey.getModulus(), rsaPublicKey.getPublicExponent());
           Key fakePrivateKey = KeyFactory.getInstance("RSA").generatePrivate(spec);
           cipher = Cipher.getInstance("RSA"); //It is a stateful object. so we need to get new one.
           cipher.init(Cipher.DECRYPT_MODE, fakePrivateKey);
	}
	
	if (cipherText == null || cipherText.length() == 0) {
		return cipherText;
	}

	byte[] cipherBytes = Base64.base64ToByteArray(cipherText);
	byte[] plainBytes = cipher.doFinal(cipherBytes);

	return new String(plainBytes);
}
 
Example #8
Source File: MessageStatusCli.java    From protect with MIT License 6 votes vote down vote up
public static KeyPair convertFromPaillier(final PaillierKeyPair paillierKeyPair)
		throws InvalidKeySpecException, NoSuchAlgorithmException {
	// Get keys
	final PaillierPrivateKey paillierPrivateKey = paillierKeyPair.getPrivateKey();
	final PaillierPublicKey paillierPublicKey = paillierKeyPair.getPublicKey();

	// Get fields
	final BigInteger n = paillierPublicKey.getN(); // treat as 'N'
	final BigInteger e = paillierPublicKey.getG(); // treat as 'e'
	final BigInteger d = paillierPrivateKey.getLambda(); // treat as 'd'

	// Represent them as RSA keys
	final RSAPrivateKeySpec privKeySpec = new RSAPrivateKeySpec(n, d);
	final RSAPublicKeySpec pubKeySpec = new RSAPublicKeySpec(n, e);

	// Convert to key pair
	final KeyFactory keyFactory = KeyFactory.getInstance("RSA");
	final PublicKey rsaPublic = keyFactory.generatePublic(pubKeySpec);
	final PrivateKey rsaPrivate = keyFactory.generatePrivate(privKeySpec);

	return new KeyPair(rsaPublic, rsaPrivate);
}
 
Example #9
Source File: SimpleTokenUtils.java    From microprofile-jwt-auth with Apache License 2.0 6 votes vote down vote up
/**
 * Decode a JWK(S) encoded private key string to an RSA PrivateKey
 * @param jwksValue - JWKS string value
 * @return PrivateKey from RSAPrivateKeySpec
 */
public static PrivateKey decodeJWKSPrivateKey(String jwksValue) throws Exception {
    JsonObject jwks = Json.createReader(new StringReader(jwksValue)).readObject();
    JsonArray keys = jwks.getJsonArray("keys");
    JsonObject jwk;
    if(keys != null) {
        jwk = keys.getJsonObject(0);
    }
    else {
        jwk = jwks;
    }
    String d = jwk.getString("d");
    String n = jwk.getString("n");

    byte[] dbytes = Base64.getUrlDecoder().decode(d);
    BigInteger privateExponent = new BigInteger(1, dbytes);
    byte[] nbytes = Base64.getUrlDecoder().decode(n);
    BigInteger modulus = new BigInteger(1, nbytes);
    KeyFactory kf = KeyFactory.getInstance("RSA");
    RSAPrivateKeySpec rsaPrivateKeySpec = new RSAPrivateKeySpec(modulus, privateExponent);
    return kf.generatePrivate(rsaPrivateKeySpec);
}
 
Example #10
Source File: DecryptUtil.java    From Mycat2 with GNU General Public License v3.0 6 votes vote down vote up
public static String decrypt(PublicKey publicKey, String cipherText)
		throws Exception {
	Cipher cipher = Cipher.getInstance("RSA");
	try {
		cipher.init(Cipher.DECRYPT_MODE, publicKey);
	} catch (InvalidKeyException e) {
           // 因为 IBM JDK 不支持私钥加密, 公钥解密, 所以要反转公私钥
           // 也就是说对于解密, 可以通过公钥的参数伪造一个私钥对象欺骗 IBM JDK
           RSAPublicKey rsaPublicKey = (RSAPublicKey) publicKey;
           RSAPrivateKeySpec spec = new RSAPrivateKeySpec(rsaPublicKey.getModulus(), rsaPublicKey.getPublicExponent());
           Key fakePrivateKey = KeyFactory.getInstance("RSA").generatePrivate(spec);
           cipher = Cipher.getInstance("RSA"); //It is a stateful object. so we need to get new one.
           cipher.init(Cipher.DECRYPT_MODE, fakePrivateKey);
	}
	
	if (cipherText == null || cipherText.length() == 0) {
		return cipherText;
	}

	byte[] cipherBytes = Base64.base64ToByteArray(cipherText);
	byte[] plainBytes = cipher.doFinal(cipherBytes);

	return new String(plainBytes);
}
 
Example #11
Source File: DecryptUtil.java    From dble with GNU General Public License v2.0 6 votes vote down vote up
private static String decrypt(PublicKey publicKey, String cipherText)
        throws Exception {
    Cipher cipher = Cipher.getInstance("RSA");
    try {
        cipher.init(Cipher.DECRYPT_MODE, publicKey);
    } catch (InvalidKeyException e) {
        //  IBM JDK not support Private key encryption, public key decryption
        // so fake an PrivateKey for it
        RSAPublicKey rsaPublicKey = (RSAPublicKey) publicKey;
        RSAPrivateKeySpec spec = new RSAPrivateKeySpec(rsaPublicKey.getModulus(), rsaPublicKey.getPublicExponent());
        Key fakePrivateKey = KeyFactory.getInstance("RSA").generatePrivate(spec);
        cipher = Cipher.getInstance("RSA"); //It is a stateful object. so we need to get new one.
        cipher.init(Cipher.DECRYPT_MODE, fakePrivateKey);
    }

    if (cipherText == null || cipherText.length() == 0) {
        return cipherText;
    }

    byte[] cipherBytes = Base64.base64ToByteArray(cipherText);
    byte[] plainBytes = cipher.doFinal(cipherBytes);

    return new String(plainBytes);
}
 
Example #12
Source File: CryptoUtils.java    From cxf with Apache License 2.0 5 votes vote down vote up
public static RSAPrivateKey getRSAPrivateKey(byte[] modulusBytes,
                                             byte[] privateExponentBytes) {
    BigInteger modulus = toBigInteger(modulusBytes);
    BigInteger privateExponent = toBigInteger(privateExponentBytes);
    try {
        KeyFactory factory = KeyFactory.getInstance("RSA");
        return (RSAPrivateKey)factory.generatePrivate(
            new RSAPrivateKeySpec(modulus, privateExponent));
    } catch (Exception ex) {
        throw new SecurityException(ex);
    }
}
 
Example #13
Source File: RSAPrivateCrtKeySpecTest.java    From j2objc with Apache License 2.0 5 votes vote down vote up
/**
 * Test #2 for <code>RSAPrivateCrtKeySpec</code> constructor
 * Assertion: Constructs <code>RSAPrivateCrtKeySpec</code>
 * object using valid parameters
 */
public final void testRSAPrivateCrtKeySpec02() {
    KeySpec ks = new RSAPrivateCrtKeySpec(
            BigInteger.ONE,
            BigInteger.ONE,
            BigInteger.ONE,
            BigInteger.ONE,
            BigInteger.ONE,
            BigInteger.ONE,
            BigInteger.ONE,
            BigInteger.ONE);
    assertTrue(ks instanceof RSAPrivateKeySpec);
}
 
Example #14
Source File: RSAPrivateKeyTest.java    From j2objc with Apache License 2.0 5 votes vote down vote up
/**
 * java.security.interfaces.RSAPrivateKey
 * #getPrivateExponent()
 */
public void test_getPrivateExponent() throws Exception {
    KeyFactory gen = KeyFactory.getInstance("RSA");
    final BigInteger n = BigInteger.valueOf(3233);
    final BigInteger d = BigInteger.valueOf(2753);
    RSAPrivateKey key = (RSAPrivateKey) gen.generatePrivate(new RSAPrivateKeySpec(
            n, d));
    assertEquals("invalid private exponent", d, key.getPrivateExponent());
}
 
Example #15
Source File: Ssh2RsaPrivateKey.java    From j2ssh-maverick with GNU Lesser General Public License v3.0 5 votes vote down vote up
public Ssh2RsaPrivateKey(BigInteger modulus, BigInteger privateExponent)
		throws NoSuchAlgorithmException, InvalidKeySpecException {

	KeyFactory keyFactory = JCEProvider
			.getProviderForAlgorithm(JCEAlgorithms.JCE_RSA) == null ? KeyFactory
			.getInstance(JCEAlgorithms.JCE_RSA) : KeyFactory.getInstance(
			JCEAlgorithms.JCE_RSA,
			JCEProvider.getProviderForAlgorithm(JCEAlgorithms.JCE_RSA));
	RSAPrivateKeySpec spec = new RSAPrivateKeySpec(modulus, privateExponent);
	prv = (RSAPrivateKey) keyFactory.generatePrivate(spec);

}
 
Example #16
Source File: RSAPrivateKeySpecTest.java    From j2objc with Apache License 2.0 5 votes vote down vote up
/**
 * Test for <code>getModulus()</code> method<br>
 * Assertion: returns modulus
 */
public final void testGetModulus() {
    RSAPrivateKeySpec rpks =
        new RSAPrivateKeySpec(BigInteger.valueOf(1234567890L),
                              BigInteger.valueOf(3L));
    assertEquals(1234567890L, rpks.getModulus().longValue());
}
 
Example #17
Source File: PcfAuthentication.java    From spring-vault with Apache License 2.0 5 votes vote down vote up
private static String doSign(byte[] message, String instanceKeyPem) throws CryptoException {

		RSAPrivateKeySpec privateKey = PemObject.fromKey(instanceKeyPem).getRSAKeySpec();
		PSSSigner signer = new PSSSigner(new RSAEngine(), new SHA256Digest(), SALT_LENGTH);

		signer.init(true, new RSAKeyParameters(true, privateKey.getModulus(), privateKey.getPrivateExponent()));
		signer.update(message, 0, message.length);

		byte[] signature = signer.generateSignature();
		return Base64Utils.encodeToUrlSafeString(signature);
	}
 
Example #18
Source File: RSAUtils.java    From mpush with Apache License 2.0 5 votes vote down vote up
/**
 * 使用模和指数生成RSA私钥
 * 注意:【此代码用了默认补位方式,为RSA/None/PKCS1Padding,
 * 不同JDK默认的补位方式可能不同,如Android默认是RSA
 * /None/NoPadding】
 *
 * @param modulus  模
 * @param exponent 指数
 * @return 私钥
 */
public static RSAPrivateKey getPrivateKey(String modulus, String exponent) {
    try {
        BigInteger b1 = new BigInteger(modulus);
        BigInteger b2 = new BigInteger(exponent);
        KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
        RSAPrivateKeySpec keySpec = new RSAPrivateKeySpec(b1, b2);
        return (RSAPrivateKey) keyFactory.generatePrivate(keySpec);
    } catch (Exception e) {
        LOGGER.error("getPrivateKey ex modulus={}, exponent={}", modulus, exponent, e);
        throw new CryptoException("Get PrivateKey ex", e);
    }
}
 
Example #19
Source File: RSAKeyValueType.java    From keycloak with Apache License 2.0 5 votes vote down vote up
/**
 * Convert to the JDK representation of a RSA Private Key
 *
 * @return
 *
 * @throws ProcessingException
 */
public RSAPrivateKey convertToPrivateKey() throws ProcessingException {
    BigInteger bigModulus = new BigInteger(1, massage(Base64.decode(new String(modulus))));
    BigInteger bigEx = new BigInteger(1, massage(Base64.decode(new String(exponent))));

    try {
        KeyFactory rsaKeyFactory = KeyFactory.getInstance("rsa");
        RSAPrivateKeySpec kspec = new RSAPrivateKeySpec(bigModulus, bigEx);
        return (RSAPrivateKey) rsaKeyFactory.generatePrivate(kspec);
    } catch (Exception e) {
        throw new ProcessingException(e);
    }
}
 
Example #20
Source File: RSAPrivateKeySpecTest.java    From j2objc with Apache License 2.0 5 votes vote down vote up
/**
 * Test for <code>getPrivateExponent()</code> method<br>
 * Assertion: returns private exponent
 */
public final void testGetPrivateExponent() {
    RSAPrivateKeySpec rpks =
        new RSAPrivateKeySpec(BigInteger.valueOf(1234567890L),
                              BigInteger.valueOf(3L));
    assertEquals(3L, rpks.getPrivateExponent().longValue());
}
 
Example #21
Source File: JwksAuthenticatorTest.java    From trellis with Apache License 2.0 5 votes vote down vote up
@Test
void testAuthenticateJwksInvalidKeyLocation() throws Exception {
    final String webid = "https://people.apache.org/~acoburn/#i";

    final Key key = KeyFactory.getInstance("RSA").generatePrivate(new RSAPrivateKeySpec(modulus, exponent));
    final String token = Jwts.builder().setHeaderParam(JwsHeader.KEY_ID, keyid).setSubject(webid)
        .signWith(key).compact();

    final Authenticator authenticator = new JwksAuthenticator("https://www.trellisldp.org/tests/non-existent");

    assertThrows(SecurityException.class, () -> authenticator.authenticate(token), "Unexpected principal!");
}
 
Example #22
Source File: JwksAuthenticatorTest.java    From trellis with Apache License 2.0 5 votes vote down vote up
@Test
void testAuthenticateJwksNoKeyid() throws Exception {
    final String webid = "https://people.apache.org/~acoburn/#i";

    final Key key = KeyFactory.getInstance("RSA").generatePrivate(new RSAPrivateKeySpec(modulus, exponent));
    final String token = Jwts.builder().setSubject(webid).signWith(key).compact();

    final Authenticator authenticator = new JwksAuthenticator(url);

    assertThrows(JwtException.class, () -> authenticator.authenticate(token), "Unexpected principal!");
}
 
Example #23
Source File: JwksAuthenticatorTest.java    From trellis with Apache License 2.0 5 votes vote down vote up
@Test
void testAuthenticateJwksWrongKeyid() throws Exception {
    final String webid = "https://people.apache.org/~acoburn/#i";

    final Key key = KeyFactory.getInstance("RSA").generatePrivate(new RSAPrivateKeySpec(modulus, exponent));
    final String token = Jwts.builder().setHeaderParam(JwsHeader.KEY_ID, "non-existent")
        .setSubject(webid).signWith(key).compact();

    final Authenticator authenticator = new JwksAuthenticator(url);

    assertThrows(SecurityException.class, () -> authenticator.authenticate(token), "Unexpected principal!");
}
 
Example #24
Source File: JwksAuthenticatorTest.java    From trellis with Apache License 2.0 5 votes vote down vote up
@Test
void testAuthenticateJwksExpired() throws Exception {
    final String webid = "https://people.apache.org/~acoburn/#i";

    final Key key = KeyFactory.getInstance("RSA").generatePrivate(new RSAPrivateKeySpec(modulus, exponent));
    final String token = Jwts.builder().setHeaderParam(JwsHeader.KEY_ID, keyid).claim("webid", webid)
        .setExpiration(from(now().minusSeconds(10))).signWith(key).compact();

    final Authenticator authenticator = new JwksAuthenticator(url);

    assertThrows(ExpiredJwtException.class, () -> authenticator.authenticate(token), "Unexpected principal!");
}
 
Example #25
Source File: JwksAuthenticatorTest.java    From trellis with Apache License 2.0 5 votes vote down vote up
@Test
void testAuthenticateJwksAsWebid() throws Exception {
    final String webid = "https://people.apache.org/~acoburn/#i";

    final Key key = KeyFactory.getInstance("RSA").generatePrivate(new RSAPrivateKeySpec(modulus, exponent));
    final String token = Jwts.builder().setHeaderParam(JwsHeader.KEY_ID, keyid)
        .claim("webid", webid).signWith(key).compact();

    final Authenticator authenticator = new JwksAuthenticator(url);

    final Principal p = authenticator.authenticate(token);
    assertNotNull(p, "Missing principal!");
    assertEquals("https://people.apache.org/~acoburn/#i", p.getName(), "Incorrect webid!");
}
 
Example #26
Source File: RSAUtils.java    From Cangol-appcore with Apache License 2.0 5 votes vote down vote up
/**
 * 使用模和指数生成RSA私钥
 * 注意:【此代码用了默认补位方式,为RSA/None/PKCS1Padding,不同JDK默认的补位方式可能不同,如Android默认是RSA
 * /None/NoPadding】
 *
 * @param modulus  模
 * @param exponent 指数
 * @return
 */
public static RSAPrivateKey getPrivateKey(String modulus, String exponent) {
    try {
        final BigInteger b1 = new BigInteger(modulus);
        final BigInteger b2 = new BigInteger(exponent);
        final KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        final RSAPrivateKeySpec keySpec = new RSAPrivateKeySpec(b1, b2);
        return (RSAPrivateKey) keyFactory.generatePrivate(keySpec);
    } catch (Exception e) {
        return null;
    }
}
 
Example #27
Source File: JwksAuthenticatorTest.java    From trellis with Apache License 2.0 5 votes vote down vote up
@Test
void testAuthenticateJwks() throws Exception {
    final String webid = "https://people.apache.org/~acoburn/#i";

    final Key key = KeyFactory.getInstance("RSA").generatePrivate(new RSAPrivateKeySpec(modulus, exponent));
    final String token = Jwts.builder().setHeaderParam(JwsHeader.KEY_ID, keyid)
        .setSubject(webid).signWith(key).compact();

    final Authenticator authenticator = new JwksAuthenticator(url);

    final Principal p = authenticator.authenticate(token);
    assertNotNull(p, "Missing principal!");
    assertEquals("https://people.apache.org/~acoburn/#i", p.getName(), "Incorrect webid!");
}
 
Example #28
Source File: KeyFactorySpi.java    From ripple-lib-java with ISC License 5 votes vote down vote up
protected PrivateKey engineGeneratePrivate(
    KeySpec keySpec)
    throws InvalidKeySpecException
{
    if (keySpec instanceof PKCS8EncodedKeySpec)
    {
        try
        {
            return generatePrivate(PrivateKeyInfo.getInstance(((PKCS8EncodedKeySpec)keySpec).getEncoded()));
        }
        catch (Exception e)
        {
            //
            // in case it's just a RSAPrivateKey object... -- openSSL produces these
            //
            try
            {
                return new BCRSAPrivateCrtKey(
                    RSAPrivateKey.getInstance(((PKCS8EncodedKeySpec)keySpec).getEncoded()));
            }
            catch (Exception ex)
            {
                throw new ExtendedInvalidKeySpecException("unable to process key spec: " + e.toString(), e);
            }
        }
    }
    else if (keySpec instanceof RSAPrivateCrtKeySpec)
    {
        return new BCRSAPrivateCrtKey((RSAPrivateCrtKeySpec)keySpec);
    }
    else if (keySpec instanceof RSAPrivateKeySpec)
    {
        return new BCRSAPrivateKey((RSAPrivateKeySpec)keySpec);
    }

    throw new InvalidKeySpecException("Unknown KeySpec type: " + keySpec.getClass().getName());
}
 
Example #29
Source File: JsonWebKey.java    From azure-keyvault-java with MIT License 5 votes vote down vote up
/**
 * Get the RSA private key value.
 *
 * @param provider
 *            the Java security provider.
 * @return the RSA private key value
 */
private PrivateKey getRSAPrivateKey(Provider provider) {

    try {
        RSAPrivateKeySpec privateKeySpec = getRSAPrivateKeySpec();
        KeyFactory factory = provider != null ? KeyFactory.getInstance("RSA", provider)
                : KeyFactory.getInstance("RSA");

        return factory.generatePrivate(privateKeySpec);
    } catch (GeneralSecurityException e) {
        throw new IllegalStateException(e);
    }
}
 
Example #30
Source File: RsaSigner.java    From MaxKey with Apache License 2.0 5 votes vote down vote up
private static RSAPrivateKey createPrivateKey(BigInteger n, BigInteger d) {
	try {
		return (RSAPrivateKey) KeyFactory.getInstance("RSA").generatePrivate(new RSAPrivateKeySpec(n, d));
	}
	catch (Exception e) {
		throw new RuntimeException(e);
	}
}