java.security.interfaces.RSAPrivateKey Java Examples

The following examples show how to use java.security.interfaces.RSAPrivateKey. 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: CryptoUtils.java    From cxf with Apache License 2.0 6 votes vote down vote up
public static RSAPrivateKey getRSAPrivateKey(String encodedModulus,
                                             String encodedPublicExponent,
                                             String encodedPrivateExponent,
                                             String encodedPrimeP,
                                             String encodedPrimeQ,
                                             String encodedPrimeExpP,
                                             String encodedPrimeExpQ,
                                             String encodedCrtCoefficient) {
//CHECKSTYLE:ON
    try {
        return getRSAPrivateKey(CryptoUtils.decodeSequence(encodedModulus),
                                CryptoUtils.decodeSequence(encodedPublicExponent),
                                CryptoUtils.decodeSequence(encodedPrivateExponent),
                                CryptoUtils.decodeSequence(encodedPrimeP),
                                CryptoUtils.decodeSequence(encodedPrimeQ),
                                CryptoUtils.decodeSequence(encodedPrimeExpP),
                                CryptoUtils.decodeSequence(encodedPrimeExpQ),
                                CryptoUtils.decodeSequence(encodedCrtCoefficient));
    } catch (Exception ex) {
        throw new SecurityException(ex);
    }
}
 
Example #2
Source File: TokenCreator.java    From cf-java-logging-support with Apache License 2.0 6 votes vote down vote up
public static String createToken(KeyPair keyPair, String issuer, Date issuedAt, Date expiresAt, String level)
                                                                                                              throws NoSuchAlgorithmException,
                                                                                                              NoSuchProviderException,
                                                                                                              DynamicLogLevelException {
    Algorithm rsa256 = Algorithm.RSA256((RSAPublicKey) keyPair.getPublic(), (RSAPrivateKey) keyPair.getPrivate());
    if (ALLOWED_DYNAMIC_LOGLEVELS.contains(level)) {
        return JWT.create().withIssuer(issuer).//
                  withIssuedAt(issuedAt). //
                  withExpiresAt(expiresAt).//
                  withClaim("level", level).sign(rsa256);
    } else {
        throw new DynamicLogLevelException("Dynamic Log-Level [" + level +
                                           "] provided in header is not valid. Allowed Values are " +
                                           ALLOWED_DYNAMIC_LOGLEVELS.toString());
    }
}
 
Example #3
Source File: MessageStatusCli.java    From protect with MIT License 6 votes vote down vote up
public static PaillierKeyPair convertToPaillier(final KeyPair rsaKeyPair)
		throws InvalidKeySpecException, NoSuchAlgorithmException {
	// Get keys
	final RSAPrivateKey rsaPrivateKey = (RSAPrivateKey) rsaKeyPair.getPrivate();
	final RSAPublicKey rsaPublicKey = (RSAPublicKey) rsaKeyPair.getPublic();

	// Get fields
	final BigInteger n = rsaPublicKey.getModulus(); // treat as 'n'
	final BigInteger g = rsaPublicKey.getPublicExponent(); // treat as 'g'
	final BigInteger lambda = rsaPrivateKey.getPrivateExponent(); // treat as 'lambda'

	// Convert them back to Paillier keys
	final PaillierPrivateKey privKey = new PaillierPrivateKey(lambda, n);
	final PaillierPublicKey pubKey = new PaillierPublicKey(n, g);

	// Convert to key pair
	return new PaillierKeyPair(pubKey, privKey);
}
 
Example #4
Source File: JWTCreatorTest.java    From java-jwt with MIT License 6 votes vote down vote up
@Test
public void shouldNotOverwriteKeyIdIfAddedFromRSAAlgorithms() throws Exception {
    RSAPrivateKey privateKey = (RSAPrivateKey) PemUtils.readPrivateKeyFromFile(PRIVATE_KEY_FILE_RSA, "RSA");
    RSAKeyProvider provider = mock(RSAKeyProvider.class);
    when(provider.getPrivateKeyId()).thenReturn("my-key-id");
    when(provider.getPrivateKey()).thenReturn(privateKey);

    String signed = JWTCreator.init()
            .withKeyId("real-key-id")
            .sign(Algorithm.RSA256(provider));

    assertThat(signed, is(notNullValue()));
    String[] parts = signed.split("\\.");
    String headerJson = new String(Base64.decodeBase64(parts[0]), StandardCharsets.UTF_8);
    assertThat(headerJson, JsonMatcher.hasEntry("kid", "my-key-id"));
}
 
Example #5
Source File: JweCompactReaderWriterTest.java    From cxf with Apache License 2.0 6 votes vote down vote up
@Test
public void testEncryptDecryptRSA15WrapA128CBCHS256() throws Exception {
    final String specPlainText = "Live long and prosper.";

    RSAPublicKey publicKey = CryptoUtils.getRSAPublicKey(RSA_MODULUS_ENCODED_A1,
                                                         RSA_PUBLIC_EXPONENT_ENCODED_A1);

    KeyEncryptionProvider keyEncryption = new RSAKeyEncryptionAlgorithm(publicKey,
                                                                         KeyAlgorithm.RSA1_5);

    JweEncryptionProvider encryption = new AesCbcHmacJweEncryption(ContentAlgorithm.A128CBC_HS256,
                                                       CONTENT_ENCRYPTION_KEY_A3,
                                                       INIT_VECTOR_A3,
                                                       keyEncryption);
    String jweContent = encryption.encrypt(specPlainText.getBytes(StandardCharsets.UTF_8), null);

    RSAPrivateKey privateKey = CryptoUtils.getRSAPrivateKey(RSA_MODULUS_ENCODED_A1,
                                                            RSA_PRIVATE_EXPONENT_ENCODED_A1);
    KeyDecryptionProvider keyDecryption = new RSAKeyDecryptionAlgorithm(privateKey,
                                                                         KeyAlgorithm.RSA1_5);
    JweDecryptionProvider decryption = new AesCbcHmacJweDecryption(keyDecryption);
    String decryptedText = decryption.decrypt(jweContent).getContentText();
    assertEquals(specPlainText, decryptedText);
}
 
Example #6
Source File: OAuthService.java    From edison-microservice with Apache License 2.0 6 votes vote down vote up
public Jwt getExampleJWTToken() {
    final ZonedDateTime soon = ZonedDateTime.now().plusDays(365);
    final String jwtToken = "{\n" +
            "  \"aud\": [\n" +
            "    \"https://api.otto.de/api-authorization\"\n" +
            "  ],\n" +
            "  \"exp\": " + soon.toInstant().getEpochSecond() + ",\n" +
            "  \"user_name\": \"3d44bbc24614e28edd094bc54ef0497809717af5\",\n" +
            "  \"jti\": \"3cee521d-96a7-4d82-b726-7e02355f3a55\",\n" +
            "  \"client_id\": \"fe0661e5a99e4d43bd3496cc6c58025f\",\n" +
            "  \"scope\": [\n" +
            "    \"hello.read\"\n" +
            "  ]\n" +
            "}";
    final RsaSigner rsaSigner = new RsaSigner((RSAPrivateKey) keyPair.getPrivate());

    return JwtHelper.encode(jwtToken, rsaSigner);
}
 
Example #7
Source File: KnoxServiceTest.java    From nifi with Apache License 2.0 6 votes vote down vote up
@Test(expected = InvalidAuthenticationException.class)
public void testInvalidAudience() throws Exception {
    final String subject = "user-1";
    final Date expiration = new Date(System.currentTimeMillis() + TimeUnit.MILLISECONDS.convert(5, TimeUnit.SECONDS));

    final KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
    final KeyPair pair = keyGen.generateKeyPair();
    final RSAPrivateKey privateKey = (RSAPrivateKey) pair.getPrivate();
    final RSAPublicKey publicKey = (RSAPublicKey) pair.getPublic();

    final JWTAuthenticationClaimsSet claimsSet = getAuthenticationClaimsSet(subject, "incorrect-audience", expiration);
    final PrivateKeyJWT privateKeyJWT = new PrivateKeyJWT(claimsSet, JWSAlgorithm.RS256, privateKey, null, null);

    final KnoxConfiguration configuration = getConfiguration(publicKey);
    final KnoxService service = new KnoxService(configuration);

    Assert.assertEquals(subject, service.getAuthenticationFromToken(privateKeyJWT.getClientAssertion().serialize()));
}
 
Example #8
Source File: RsaEncryptProvider.java    From mPaaS with Apache License 2.0 6 votes vote down vote up
/**
 * RSA私钥解密
 *
 * @param decryptStr Base64 编码的加密字符串
 * @return 明文
 */
@Override
public String decrypt(String decryptStr){
    String outStr = null;
    try {
        //64位解码加密后的字符串
        byte[] inputByte = Base64.getDecoder().decode(decryptStr.getBytes(CHARSET_NAME));
        //私钥
        RSAPrivateKey priKey = (RSAPrivateKey) KeyFactory.getInstance(RSA).generatePrivate(new PKCS8EncodedKeySpec(privateCodeByte));
        //RSA解密
        Cipher cipher = Cipher.getInstance(RSA);
        cipher.init(Cipher.DECRYPT_MODE, priKey);
        outStr = new String(cipher.doFinal(inputByte));
    } catch (Exception e) {
       log.error("RSA解密失败",e);
    }
    return outStr;
}
 
Example #9
Source File: RsaEncryptProvider.java    From mPaaS with Apache License 2.0 6 votes vote down vote up
/**
 * 随机生成密钥对
 * @throws NoSuchAlgorithmException
 */
public static void genKeyPair() throws NoSuchAlgorithmException {
    // KeyPairGenerator类用于生成公钥和私钥对,基于RSA算法生成对象
    KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance("RSA");
    // 初始化密钥对生成器,密钥大小为96-1024位
    keyPairGen.initialize(1024,new SecureRandom());
    // 生成一个密钥对,保存在keyPair中
    KeyPair keyPair = keyPairGen.generateKeyPair();
    RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();   // 得到私钥
    RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();  // 得到公钥
    String publicKeyString = new String(Hex.encode(publicKey.getEncoded()));
    // 得到私钥字符串
    String privateKeyString = new String(Hex.encode((privateKey.getEncoded())));
    // 将公钥和私钥保存到Map
    //0表示公钥
    System.out.println("公钥 16进制:"+publicKeyString);
    //1表示私钥
    System.out.println("私钥 16进制:"+privateKeyString);
}
 
Example #10
Source File: RSAUtils.java    From mpush with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) throws Exception {
    int keySize = RAS_KEY_SIZE;
    if (args.length > 0) keySize = Integer.parseInt(args[0]);
    if (keySize < RAS_KEY_SIZE) keySize = RAS_KEY_SIZE;
    Pair<RSAPublicKey, RSAPrivateKey> pair = RSAUtils.genKeyPair(keySize);
    //生成公钥和私钥
    RSAPublicKey publicKey = pair.key;
    RSAPrivateKey privateKey = pair.value;

    System.out.println("key generate success!");

    System.out.println("privateKey=" + RSAUtils.encodeBase64(privateKey));
    System.out.println("publicKey=" + RSAUtils.encodeBase64(publicKey));

    //明文
    byte[] ming = "这是一段测试文字。。。。".getBytes(Constants.UTF_8);
    System.out.println("明文:" + new String(ming, Constants.UTF_8));

    //加密后的密文
    byte[] mi = RSAUtils.encryptByPublicKey(ming, publicKey);
    System.out.println("密文:" + new String(mi, Constants.UTF_8));
    //解密后的明文
    ming = RSAUtils.decryptByPrivateKey(mi, privateKey);
    System.out.println("解密:" + new String(ming, Constants.UTF_8));
}
 
Example #11
Source File: RSAUtils.java    From JavaLib with MIT License 6 votes vote down vote up
private static String[] commonKey(int size) throws NoSuchAlgorithmException {
    String [] keys = new String[2];

    KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(RSA);
    keyPairGenerator.initialize(size);
    KeyPair keyPair = keyPairGenerator.generateKeyPair();
    RSAPrivateKey rsaPrivateKey = (RSAPrivateKey) keyPair.getPrivate();
    RSAPublicKey rsaPublicKey = (RSAPublicKey) keyPair.getPublic();

    // 私钥
    keys[0] = Base64.byteArrayToBase64(rsaPrivateKey.getEncoded());
    // 公钥
    keys[1] = Base64.byteArrayToBase64(rsaPublicKey.getEncoded());

    return keys;
}
 
Example #12
Source File: JwkUtilsTest.java    From cxf with Apache License 2.0 6 votes vote down vote up
@Test
public void testToPrivateRsaKeyWithoutE() throws Exception {
    RSAPrivateKey privateKey1 =
        (RSAPrivateKey)KeyManagementUtils.loadPrivateKey("org/apache/cxf/rs/security/jose/jws/alice.jks",
                                          "password",
                                          "alice",
                                          "password",
                                          null);
    JsonWebKey jwk1 = JwkUtils.fromRSAPrivateKey(privateKey1, KeyAlgorithm.RSA_OAEP_256.getJwaName());
    assertNotNull(jwk1.getProperty(JsonWebKey.RSA_PUBLIC_EXP));
    jwk1.asMap().remove(JsonWebKey.RSA_PUBLIC_EXP);
    try {
        JwkUtils.toRSAPrivateKey(jwk1);
        fail("JWK without the public exponent can not be converted to RSAPrivateKey");
    } catch (JoseException ex) {
        // expected
    }
}
 
Example #13
Source File: JwtAuthenticationProviderTest.java    From auth0-spring-security-api with MIT License 6 votes vote down vote up
@SuppressWarnings("unchecked")
@Test
public void shouldFailToAuthenticateUsingJWKIfKeyIdDoesNotMatch() throws Exception {
    JwkProvider jwkProvider = mock(JwkProvider.class);

    KeyPair keyPair = RSAKeyPair();
    when(jwkProvider.get(eq("key-id"))).thenThrow(SigningKeyNotFoundException.class);
    JwtAuthenticationProvider provider = new JwtAuthenticationProvider(jwkProvider, "test-issuer", "test-audience");
    Map<String, Object> keyIdHeader = Collections.singletonMap("kid", (Object) "key-id");
    String token = JWT.create()
            .withAudience("test-audience")
            .withIssuer("test-issuer")
            .withHeader(keyIdHeader)
            .sign(Algorithm.RSA256(null, (RSAPrivateKey) keyPair.getPrivate()));

    Authentication authentication = PreAuthenticatedAuthenticationJsonWebToken.usingToken(token);

    exception.expect(AuthenticationServiceException.class);
    exception.expectMessage("Could not retrieve jwks from issuer");
    exception.expectCause(Matchers.<Throwable>instanceOf(SigningKeyNotFoundException.class));
    provider.authenticate(authentication);
}
 
Example #14
Source File: DecryptUtil.java    From dble with GNU General Public License v2.0 6 votes vote down vote up
private static String encrypt(byte[] keyBytes, String plainText)
        throws Exception {
    PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(keyBytes);
    KeyFactory factory = KeyFactory.getInstance("RSA");
    PrivateKey privateKey = factory.generatePrivate(spec);
    Cipher cipher = Cipher.getInstance("RSA");
    try {
        cipher.init(Cipher.ENCRYPT_MODE, privateKey);
    } catch (InvalidKeyException e) {
        //For IBM JDK
        RSAPrivateKey rsaPrivateKey = (RSAPrivateKey) privateKey;
        RSAPublicKeySpec publicKeySpec = new RSAPublicKeySpec(rsaPrivateKey.getModulus(), rsaPrivateKey.getPrivateExponent());
        Key fakePublicKey = KeyFactory.getInstance("RSA").generatePublic(publicKeySpec);
        cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.ENCRYPT_MODE, fakePublicKey);
    }

    byte[] encryptedBytes = cipher.doFinal(plainText.getBytes("UTF-8"));
    return Base64.byteArrayToBase64(encryptedBytes);
}
 
Example #15
Source File: RSACoder.java    From mumu with Apache License 2.0 6 votes vote down vote up
/**
 * 初始化密钥
 * 
 * @return Map 密钥对儿 Map
 * @throws Exception
 */
public static Map<String, Object> initKey() throws Exception {
	// 实例化密钥对儿生成器
	KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance(KEY_ALGORITHM);
	// 初始化密钥对儿生成器
	keyPairGen.initialize(KEY_SIZE);
	// 生成密钥对儿
	KeyPair keyPair = keyPairGen.generateKeyPair();
	// 公钥
	RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
	// 私钥
	RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();
	// 封装密钥
	Map<String, Object> keyMap = new HashMap<String, Object>(2);
	keyMap.put(PUBLIC_KEY, publicKey);
	keyMap.put(PRIVATE_KEY, privateKey);
	return keyMap;
}
 
Example #16
Source File: SignatureTest2.java    From openjdk-jdk8u with GNU General Public License v2.0 6 votes vote down vote up
private static Key[] manipulateKey(int type, Key key)
        throws NoSuchAlgorithmException, InvalidKeySpecException, NoSuchProviderException {
    KeyFactory kf = KeyFactory.getInstance(KEYALG, PROVIDER);

    switch (type) {
        case PUBLIC_KEY:
            return new Key[]{
                kf.generatePublic(kf.getKeySpec(key, RSAPublicKeySpec.class)),
                kf.generatePublic(new X509EncodedKeySpec(key.getEncoded())),
                kf.generatePublic(new RSAPublicKeySpec(
                ((RSAPublicKey) key).getModulus(),
                ((RSAPublicKey) key).getPublicExponent()))
            };
        case PRIVATE_KEY:
            return new Key[]{
                kf.generatePrivate(kf.getKeySpec(key,
                RSAPrivateKeySpec.class)),
                kf.generatePrivate(new PKCS8EncodedKeySpec(
                key.getEncoded())),
                kf.generatePrivate(new RSAPrivateKeySpec(((RSAPrivateKey) key).getModulus(),
                ((RSAPrivateKey) key).getPrivateExponent()))
            };
    }
    throw new RuntimeException("We shouldn't reach here");
}
 
Example #17
Source File: TokenUtil.java    From peer-os with Apache License 2.0 6 votes vote down vote up
public static String createTokenRSA( PrivateKey privateKey, String claimJson )
{
    try
    {
        JWSSigner signer = new RSASSASigner( ( RSAPrivateKey ) privateKey );

        Payload pl = new Payload( claimJson );
        JWSObject jwsObject = new JWSObject( new JWSHeader( JWSAlgorithm.RS256 ), pl );

        jwsObject.sign( signer );

        return jwsObject.serialize();
    }
    catch ( Exception e )
    {
        LOG.error( "Error creating RSA token", e.getMessage() );

        return "";
    }
}
 
Example #18
Source File: JwtAuthenticationProviderTest.java    From auth0-spring-security-api with MIT License 6 votes vote down vote up
@SuppressWarnings("unchecked")
@Test
public void shouldFailToAuthenticateUsingJWKIfPublicKeyIsInvalid() throws Exception {
    Jwk jwk = mock(Jwk.class);
    JwkProvider jwkProvider = mock(JwkProvider.class);

    KeyPair keyPair = RSAKeyPair();
    when(jwkProvider.get(eq("key-id"))).thenReturn(jwk);
    when(jwk.getPublicKey()).thenThrow(InvalidPublicKeyException.class);
    JwtAuthenticationProvider provider = new JwtAuthenticationProvider(jwkProvider, "test-issuer", "test-audience");
    Map<String, Object> keyIdHeader = Collections.singletonMap("kid", (Object) "key-id");
    String token = JWT.create()
            .withAudience("test-audience")
            .withIssuer("test-issuer")
            .withHeader(keyIdHeader)
            .sign(Algorithm.RSA256(null, (RSAPrivateKey) keyPair.getPrivate()));

    Authentication authentication = PreAuthenticatedAuthenticationJsonWebToken.usingToken(token);

    exception.expect(AuthenticationServiceException.class);
    exception.expectMessage("Could not retrieve public key from issuer");
    exception.expectCause(Matchers.<Throwable>instanceOf(InvalidPublicKeyException.class));
    provider.authenticate(authentication);
}
 
Example #19
Source File: CrossEncryptionTest.java    From oxAuth with MIT License 6 votes vote down vote up
public boolean testDecryptWithGluuDecrypter(String jwe) {

        try {
            JWK jwk = JWK.parse(recipientJwkJson);
            RSAPrivateKey rsaPrivateKey = ((RSAKey) jwk).toRSAPrivateKey();

            JweDecrypterImpl decrypter = new JweDecrypterImpl(rsaPrivateKey);

            decrypter.setKeyEncryptionAlgorithm(KeyEncryptionAlgorithm.RSA_OAEP);
            decrypter.setBlockEncryptionAlgorithm(BlockEncryptionAlgorithm.A128GCM);
            final String decryptedPayload = decrypter.decrypt(jwe).getClaims().toJsonString().toString();
            System.out.println("Gluu decrypt succeed: " + decryptedPayload);
            if (isJsonEqual(decryptedPayload, PAYLOAD)) {
                return true;
            }
        } catch (Exception e) {
            System.out.println("Gluu decrypt failed: " + e.getMessage());
            e.printStackTrace();
        }
        return false;
    }
 
Example #20
Source File: ClientAssertionServiceTest.java    From graviteeio-access-management with Apache License 2.0 5 votes vote down vote up
@Test
public void testRsaJwt_withClientJwks_invalidClientAuthMethod() throws NoSuchAlgorithmException, JOSEException{
    KeyPair rsaKey = generateRsaKeyPair();

    RSAPublicKey publicKey = (RSAPublicKey) rsaKey.getPublic();
    RSAPrivateKey privateKey = (RSAPrivateKey) rsaKey.getPrivate();

    RSAKey key = new RSAKey();
    key.setKty("RSA");
    key.setKid(KID);
    key.setE(Base64.getUrlEncoder().encodeToString(publicKey.getPublicExponent().toByteArray()));
    key.setN(Base64.getUrlEncoder().encodeToString(publicKey.getModulus().toByteArray()));

    Client client = generateClient(key);
    client.setTokenEndpointAuthMethod(ClientAuthenticationMethod.CLIENT_SECRET_JWT);
    String assertion = generateJWT(privateKey);
    OpenIDProviderMetadata openIDProviderMetadata = Mockito.mock(OpenIDProviderMetadata.class);
    String basePath="/";

    when(clientSyncService.findByClientId(any())).thenReturn(Maybe.just(client));
    when(openIDProviderMetadata.getTokenEndpoint()).thenReturn(AUDIENCE);
    when(openIDDiscoveryService.getConfiguration(basePath)).thenReturn(openIDProviderMetadata);

    TestObserver testObserver = clientAssertionService.assertClient(JWT_BEARER_TYPE,assertion,basePath).test();

    testObserver.assertError(InvalidClientException.class);
    testObserver.assertNotComplete();
}
 
Example #21
Source File: RSAUtil.java    From anyline with Apache License 2.0 5 votes vote down vote up
/** 
 * 私钥加密 
 *  
 * @param data  data
 * @param privateKey  privateKey
 * @return return
 * @throws Exception Exception
 */ 

public static String privateEncrypt(String data, RSAPrivateKey privateKey)  throws Exception{
	try { 
		Cipher cipher = Cipher.getInstance(RSA_ALGORITHM); 
		cipher.init(Cipher.ENCRYPT_MODE, privateKey); 
		return Base64.encodeBase64URLSafeString(rsaSplitCodec(cipher, Cipher.ENCRYPT_MODE, data.getBytes(CHARSET), privateKey.getModulus().bitLength())); 
	} catch (Exception e) { 
		throw new Exception("[私钥加密异常][加密数据:" + data + "]", e);
	} 
}
 
Example #22
Source File: JwkKeyPairManager.java    From OAuth-2.0-Cookbook with MIT License 5 votes vote down vote up
public JwkKeyPairManager() {
    KeyPair keyPair = createRSA256KeyPair();
    RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
    RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();
    RandomValueStringGenerator random = new RandomValueStringGenerator();
    RSAKey.Builder builder = new RSAKey.Builder(publicKey);
    builder.keyID(random.generate());
    builder.privateKey(privateKey);
    this.clientJwk = builder.build();
}
 
Example #23
Source File: KeyUtil.java    From iot-dc3 with Apache License 2.0 5 votes vote down vote up
/**
 * RSA 私钥解密
 *
 * @param str        String
 * @param privateKey Private Key
 * @return Decrypt Rsa
 * @throws Exception Exception
 */
public static String decryptRsa(String str, String privateKey) throws Exception {
    //base64编码的私钥
    byte[] keyBytes = Dc3Util.decode(privateKey);
    KeySpec keySpec = new PKCS8EncodedKeySpec(keyBytes);
    RSAPrivateKey priKey = (RSAPrivateKey) KeyFactory.getInstance(Common.KEY_ALGORITHM_RSA).generatePrivate(keySpec);
    //RSA解密
    Cipher cipher = Cipher.getInstance(Common.KEY_ALGORITHM_RSA);
    cipher.init(Cipher.DECRYPT_MODE, priKey);
    //64位解码加密后的字符串
    byte[] inputByte = Dc3Util.decode(str.getBytes(Charsets.UTF_8));
    return new String(cipher.doFinal(inputByte));
}
 
Example #24
Source File: RSAUtils.java    From unimall with Apache License 2.0 5 votes vote down vote up
/**
 * 私钥加密
 * @param data
 * @param privateKey
 * @return
 */

public static String privateEncrypt(String data, RSAPrivateKey privateKey) {
    try {
        Cipher cipher = Cipher.getInstance(RSA_ALGORITHM);
        //每个Cipher初始化方法使用一个模式参数opmod,并用此模式初始化Cipher对象。此外还有其他参数,包括密钥key、包含密钥的证书certificate、算法参数params和随机源random。
        cipher.init(Cipher.ENCRYPT_MODE, privateKey);
        return Base64.encodeBase64URLSafeString(rsaSplitCodec(cipher, Cipher.ENCRYPT_MODE, data.getBytes(CHARSET), privateKey.getModulus().bitLength()));
    } catch (Exception e) {
        throw new RuntimeException("加密字符串[" + data + "]时遇到异常", e);
    }
}
 
Example #25
Source File: RsaMessage.java    From MaxKey with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {
String str = "hello,�����ĵ����";
System.out.println("ԭ�ģ�" + str);

RsaMessage rsa = new RsaMessage();
RSAPrivateKey privateKey = (RSAPrivateKey) rsa.readFromFile("sk.dat");
RSAPublicKey publickKey = (RSAPublicKey) rsa.readFromFile("pk.dat");

byte[] encbyte = rsa.encrypt(str, privateKey);
System.out.println("˽Կ���ܺ�");
String encStr = toHexString(encbyte);
System.out.println(encStr);

byte[] signBytes = rsa.sign(str, privateKey);
System.out.println("ǩ��ֵ��");
String signStr = toHexString(signBytes);
System.out.println(signStr);

byte[] decByte = rsa.decrypt(encStr, publickKey);
System.out.println("��Կ���ܺ�");
String decStr = new String(decByte);
System.out.println(decStr);

if (rsa.verifySign(str, signStr, publickKey)) {
System.out.println("rsa sign check success");
} else {
System.out.println("rsa sign check failure");
}
}
 
Example #26
Source File: CipherTestUtils.java    From TencentKona-8 with GNU General Public License v2.0 5 votes vote down vote up
private static KeyStore createServerKeyStore(String publicKeyStr,
        String keySpecStr) throws KeyStoreException, IOException,
        NoSuchAlgorithmException, CertificateException,
        InvalidKeySpecException {

    KeyStore ks = KeyStore.getInstance("JKS");
    ks.load(null, null);
    if (publicKeyStr == null || keySpecStr == null) {
        throw new IllegalArgumentException("publicKeyStr or "
                + "keySpecStr cannot be null");
    }
    String strippedPrivateKey = keySpecStr.substring(
            keySpecStr.indexOf("\n"), keySpecStr.lastIndexOf("\n"));

    // generate the private key.
    PKCS8EncodedKeySpec priKeySpec = new PKCS8EncodedKeySpec(
            Base64.getMimeDecoder().decode(strippedPrivateKey));
    KeyFactory kf = KeyFactory.getInstance("RSA");
    RSAPrivateKey priKey
            = (RSAPrivateKey) kf.generatePrivate(priKeySpec);

    // generate certificate chain
    try (InputStream is =
            new ByteArrayInputStream(publicKeyStr.getBytes())) {
        // generate certificate from cert string
        CertificateFactory cf = CertificateFactory.getInstance("X.509");
        Certificate keyCert = cf.generateCertificate(is);
        Certificate[] chain = {keyCert};
        ks.setKeyEntry("TestEntry", priKey, PASSWORD, chain);
    }

    return ks;
}
 
Example #27
Source File: RsaSigner.java    From MaxKey with Apache License 2.0 5 votes vote down vote up
private static RSAPrivateKey loadPrivateKey(String key) {
	KeyPair kp = RsaKeyHelper.parseKeyPair(key);

	if (kp.getPrivate() == null) {
		throw new IllegalArgumentException("Not a private key");
	}

	return (RSAPrivateKey) kp.getPrivate();
}
 
Example #28
Source File: JwtAuthenticationProviderTest.java    From auth0-spring-security-api with MIT License 5 votes vote down vote up
@Test
public void shouldAuthenticateUsingJWKWithExpiredTokenAndLeeway() throws Exception {
    Calendar calendar = Calendar.getInstance();
    calendar.add(Calendar.SECOND, -10);
    Date tenSecondsAgo = calendar.getTime();

    Jwk jwk = mock(Jwk.class);
    JwkProvider jwkProvider = mock(JwkProvider.class);

    KeyPair keyPair = RSAKeyPair();
    when(jwkProvider.get(eq("key-id"))).thenReturn(jwk);
    when(jwk.getPublicKey()).thenReturn(keyPair.getPublic());
    JwtAuthenticationProvider provider = new JwtAuthenticationProvider(jwkProvider, "test-issuer", "test-audience")
            .withJwtVerifierLeeway(12);

    Map<String, Object> keyIdHeader = Collections.singletonMap("kid", (Object) "key-id");
    String token = JWT.create()
            .withAudience("test-audience")
            .withIssuer("test-issuer")
            .withHeader(keyIdHeader)
            .withExpiresAt(tenSecondsAgo)
            .sign(Algorithm.RSA256(null, (RSAPrivateKey) keyPair.getPrivate()));
    Authentication authentication = PreAuthenticatedAuthenticationJsonWebToken.usingToken(token);

    Authentication result = provider.authenticate(authentication);
    assertThat(result, is(notNullValue()));
    assertThat(result, is(not(equalTo(authentication))));
}
 
Example #29
Source File: Codec.java    From XDroidMvp with MIT License 5 votes vote down vote up
/**
 * 初始化密钥
 *
 * @return
 * @throws Exception
 */
public static Map<String, Object> initKey() throws Exception {
    KeyPairGenerator keyPairGen = KeyPairGenerator
            .getInstance(Algorithm.RSA.getType());
    keyPairGen.initialize(1024);

    KeyPair keyPair = keyPairGen.generateKeyPair();
    RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();    // 公钥
    RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();     // 私钥
    Map<String, Object> keyMap = new HashMap<String, Object>(2);

    keyMap.put(PUBLIC_KEY, publicKey);
    keyMap.put(PRIVATE_KEY, privateKey);
    return keyMap;
}
 
Example #30
Source File: CryptoUtils.java    From cxf with Apache License 2.0 5 votes vote down vote up
public static RSAPrivateKey getRSAPrivateKey(String encodedModulus,
                                             String encodedPrivateExponent) {
    try {
        return getRSAPrivateKey(CryptoUtils.decodeSequence(encodedModulus),
                                CryptoUtils.decodeSequence(encodedPrivateExponent));
    } catch (Exception ex) {
        throw new SecurityException(ex);
    }
}