Java 类java.security.interfaces.RSAPrivateKey 实例源码

项目:jeesupport    文件:RSAUtils.java   
/**
 * 初始化密钥
 * 
 * @param byte[]
 *            _arg 种子
 * @return
 * @throws Exception
 */
public static Map< String , Key > s_genkeys_map( byte[] _arg ) throws Exception {
    // 实例化密钥对生成器
    KeyPairGenerator key_pair_generator = KeyPairGenerator.getInstance( KEY_ALGORITHM_RSA );

    // 初始化密钥对生成器
    key_pair_generator.initialize( KEY_SIZE , new SecureRandom( _arg ) );

    // 生成密钥对
    KeyPair key_pair = key_pair_generator.generateKeyPair();

    // 公钥
    RSAPublicKey public_key = (RSAPublicKey) key_pair.getPublic();

    // 私钥
    RSAPrivateKey private_key = (RSAPrivateKey) key_pair.getPrivate();

    // 封装密钥
    Map< String , Key > key_map = new HashMap< String , Key >( 2 );

    key_map.put( RSA_PUBLIC_KEY , public_key );
    key_map.put( RSA_PRIVATE_KEY , private_key );

    return key_map;
}
项目:L2jBrasil    文件:LoginController.java   
private LoginController() throws GeneralSecurityException
{
    _log.info("Loading LoginContoller...");

    _hackProtection = new HashMap<>();

    _keyPairs = new ScrambledKeyPair[10];

    KeyPairGenerator keygen = null;

    keygen = KeyPairGenerator.getInstance("RSA");
    RSAKeyGenParameterSpec spec = new RSAKeyGenParameterSpec(1024, RSAKeyGenParameterSpec.F4);
    keygen.initialize(spec);

    //generate the initial set of keys
    for (int i = 0; i < 10; i++)
    {
        _keyPairs[i] = new ScrambledKeyPair(keygen.generateKeyPair());
    }
    _log.info("Cached 10 KeyPairs for RSA communication");

    testCipher((RSAPrivateKey) _keyPairs[0]._pair.getPrivate());

    // Store keys for blowfish communication
    generateBlowFishKeys();
}
项目:L2jBrasil    文件:GameServerThread.java   
public GameServerThread(Socket con)
{
    _connection = con;
    _connectionIp = con.getInetAddress().getHostAddress();
    try
    {
        _in = _connection.getInputStream();
        _out = new BufferedOutputStream(_connection.getOutputStream());
    }
    catch (IOException e)
    {
        e.printStackTrace();
    }
    KeyPair pair = GameServerTable.getInstance().getKeyPair();
    _privateKey = (RSAPrivateKey) pair.getPrivate();
    _publicKey = (RSAPublicKey) pair.getPublic();
    _blowfish = new NewCrypt("_;v.]05-31!|+-%xT!^[$\00");
    start();
}
项目:javaOIDCMsg    文件:RSAAlgorithmTest.java   
@Test
public void shouldThrowOnSignWhenSignatureAlgorithmDoesNotExists() throws Exception {
    exception.expect(SignatureGenerationException.class);
    exception.expectMessage("The Token's Signature couldn't be generated when signing using the Algorithm: some-algorithm");
    exception.expectCause(isA(NoSuchAlgorithmException.class));

    CryptoHelper crypto = mock(CryptoHelper.class);
    when(crypto.createSignatureFor(anyString(), any(PrivateKey.class), any(byte[].class)))
            .thenThrow(NoSuchAlgorithmException.class);

    RSAPublicKey publicKey = mock(RSAPublicKey.class);
    RSAPrivateKey privateKey = mock(RSAPrivateKey.class);
    RSAKeyProvider provider = RSAAlgorithm.providerForKeys(publicKey, privateKey);
    Algorithm algorithm = new RSAAlgorithm(crypto, "some-alg", "some-algorithm", provider);
    algorithm.sign(RS256Header.getBytes(StandardCharsets.UTF_8));
}
项目:javaOIDCMsg    文件:RSAAlgorithmTest.java   
@Test
public void shouldDoRSA256SigningWithProvidedPrivateKey() throws Exception {
    RSAKeyProvider provider = mock(RSAKeyProvider.class);
    PrivateKey privateKey = readPrivateKeyFromFile(PRIVATE_KEY_FILE, "RSA");
    PublicKey publicKey = readPublicKeyFromFile(PUBLIC_KEY_FILE, "RSA");
    when(provider.getPrivateKey()).thenReturn((RSAPrivateKey) privateKey);
    when(provider.getPublicKeyById(null)).thenReturn((RSAPublicKey) publicKey);
    Algorithm algorithm = Algorithm.RSA256(provider);
    String jwtContent = String.format("%s.%s", RS256Header, auth0IssPayload);
    byte[] contentBytes = jwtContent.getBytes(StandardCharsets.UTF_8);
    byte[] signatureBytes = algorithm.sign(contentBytes);
    String jwtSignature = Base64.encodeBase64URLSafeString(signatureBytes);
    String token = String.format("%s.%s", jwtContent, jwtSignature);

    assertThat(signatureBytes, is(notNullValue()));
    JWT jwt = JWT.require(algorithm).withIssuer("auth0").build();
    DecodedJWT decoded = jwt.decode(token);
    algorithm.verify(decoded, EncodeType.Base64);
}
项目:javaOIDCMsg    文件:RSAAlgorithmTest.java   
@Test
public void shouldThrowWhenMacAlgorithmDoesNotExists() throws Exception {
    exception.expect(AlgorithmMismatchException.class);
    exception.expectMessage("The provided Algorithm doesn't match the one defined in the JWT's Header.");

    CryptoHelper crypto = mock(CryptoHelper.class);
    when(crypto.verifySignatureFor(anyString(), any(PublicKey.class), any(byte[].class), any(byte[].class)))
            .thenThrow(NoSuchAlgorithmException.class);

    RSAPublicKey publicKey = mock(RSAPublicKey.class);
    RSAPrivateKey privateKey = mock(RSAPrivateKey.class);
    RSAKeyProvider provider = RSAAlgorithm.providerForKeys(publicKey, privateKey);
    Algorithm algorithm = new RSAAlgorithm(crypto, "some-alg", "some-algorithm", provider);
    String token = "eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJhdXRoMCJ9.dxXF3MdsyW-AuvwJpaQtrZ33fAde9xWxpLIg9cO2tMLH2GSRNuLAe61KsJusZhqZB9Iy7DvflcmRz-9OZndm6cj_ThGeJH2LLc90K83UEvvRPo8l85RrQb8PcanxCgIs2RcZOLygERizB3pr5icGkzR7R2y6zgNCjKJ5_NJ6EiZsGN6_nc2PRK_DbyY-Wn0QDxIxKoA5YgQJ9qafe7IN980pXvQv2Z62c3XR8dYuaXBqhthBj-AbaFHEpZapN-V-TmuLNzR2MCB6Xr7BYMuCaqWf_XU8og4XNe8f_8w9Wv5vvgqMM1KhqVpG5VdMJv4o_L4NoCROHhtUQSLRh2M9cA";
    JWT jwt = JWT.require(algorithm).withIssuer("auth0").build();
    DecodedJWT decoded = jwt.decode(token);
    algorithm.verify(decoded, EncodeType.Base64);
}
项目:javaOIDCMsg    文件:RSAAlgorithmTest.java   
@Test
public void shouldThrowWhenThePublicKeyIsInvalid() throws Exception {
    exception.expect(AlgorithmMismatchException.class);
    exception.expectMessage("The provided Algorithm doesn't match the one defined in the JWT's Header.");

    CryptoHelper crypto = mock(CryptoHelper.class);
    when(crypto.verifySignatureFor(anyString(), any(PublicKey.class), any(byte[].class), any(byte[].class)))
            .thenThrow(InvalidKeyException.class);

    RSAPublicKey publicKey = mock(RSAPublicKey.class);
    RSAPrivateKey privateKey = mock(RSAPrivateKey.class);
    RSAKeyProvider provider = RSAAlgorithm.providerForKeys(publicKey, privateKey);
    Algorithm algorithm = new RSAAlgorithm(crypto, "some-alg", "some-algorithm", provider);
    String token = "eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJhdXRoMCJ9.dxXF3MdsyW-AuvwJpaQtrZ33fAde9xWxpLIg9cO2tMLH2GSRNuLAe61KsJusZhqZB9Iy7DvflcmRz-9OZndm6cj_ThGeJH2LLc90K83UEvvRPo8l85RrQb8PcanxCgIs2RcZOLygERizB3pr5icGkzR7R2y6zgNCjKJ5_NJ6EiZsGN6_nc2PRK_DbyY-Wn0QDxIxKoA5YgQJ9qafe7IN980pXvQv2Z62c3XR8dYuaXBqhthBj-AbaFHEpZapN-V-TmuLNzR2MCB6Xr7BYMuCaqWf_XU8og4XNe8f_8w9Wv5vvgqMM1KhqVpG5VdMJv4o_L4NoCROHhtUQSLRh2M9cA";
    JWT jwt = JWT.require(algorithm).withIssuer("auth0").build();
    DecodedJWT decoded = jwt.decode(token);
    algorithm.verify(decoded, EncodeType.Base64);
}
项目:iBase4J-Common    文件:RSACoder.java   
/**
 * 初始化密钥
 * 
 * @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;
}
项目:springboot-training    文件:RSACoder.java   
/**
 * 初始化密钥
 * 
 * @return
 * @throws Exception
 */
public static Map<String, Key> initKey() {
    try {
        KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance(KEY_ALGORITHM);
        keyPairGen.initialize(1024);

        KeyPair keyPair = keyPairGen.generateKeyPair();

        // 公钥
        RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();

        // 私钥
        RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();

        Map<String, Key> keyMap = new HashMap<String, Key>(2);

        keyMap.put(PUBLIC_KEY, publicKey);
        keyMap.put(PRIVATE_KEY, privateKey);
        return keyMap;
    } catch (NoSuchAlgorithmException e) {
        throw new RuntimeException("初始化密钥出错 " + e.getMessage());
    }
}
项目:automat    文件:RSACoder.java   
/**
 * 初始化密钥
 * 
 * @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;
}
项目:atbash-octopus    文件:RSAKeyFactory.java   
public RSAKey makeRSA(Integer keySize, KeyUse keyUse, Algorithm keyAlg, String kid) {

        try {
            KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA");
            generator.initialize(keySize);
            KeyPair kp = generator.generateKeyPair();

            RSAPublicKey pub = (RSAPublicKey) kp.getPublic();
            RSAPrivateKey priv = (RSAPrivateKey) kp.getPrivate();

            return new RSAKey.Builder(pub)
                    .privateKey(priv)
                    .keyUse(keyUse)
                    .algorithm(keyAlg)
                    .keyID(kid)
                    .build();
        } catch (NoSuchAlgorithmException e) {
            // FIXME Auto-generated catch block
            e.printStackTrace();
            return null;
        }
    }
项目:OAuth-2.0-Cookbook    文件:JwkKeyPairManager.java   
public String getSignedContent(String content) {
    Payload contentPayload = new Payload(content);

    try {
        RSASSASigner rsa = new RSASSASigner((RSAPrivateKey) clientJwk);
        JWSAlgorithm alg = JWSAlgorithm.RS256;
        JWSHeader header = new JWSHeader.Builder(alg)
            .keyID(clientJwk.getKeyID())
            .build();
        JWSObject jws = new JWSObject(header, contentPayload);
        jws.sign(rsa);
        return jws.serialize();
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
项目:javaOIDCMsg    文件:RSAAlgorithmTest.java   
@Test
public void shouldThrowOnSignWhenTheSignatureIsNotPrepared() throws Exception {
    exception.expect(SignatureGenerationException.class);
    exception.expectMessage("The Token's Signature couldn't be generated when signing using the Algorithm: some-algorithm");
    exception.expectCause(isA(SignatureException.class));

    CryptoHelper crypto = mock(CryptoHelper.class);
    when(crypto.createSignatureFor(anyString(), any(PrivateKey.class), any(byte[].class)))
            .thenThrow(SignatureException.class);

    RSAPublicKey publicKey = mock(RSAPublicKey.class);
    RSAPrivateKey privateKey = mock(RSAPrivateKey.class);
    RSAKeyProvider provider = RSAAlgorithm.providerForKeys(publicKey, privateKey);
    Algorithm algorithm = new RSAAlgorithm(crypto, "some-alg", "some-algorithm", provider);
    algorithm.sign(RS256Header.getBytes(StandardCharsets.UTF_8));
}
项目:spring-cloud-samples    文件:RSAUtils.java   
public static HashMap<String, String> getKeys() {
    try {
        HashMap<String, String> map = new HashMap<>();
        KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance(SIGN_ALGORITHM);
        keyPairGen.initialize(1024);
        KeyPair keyPair = keyPairGen.generateKeyPair();
        RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
        RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();
        map.put(PUBLIC_KEY, new String(Base64Utils.encode(publicKey.getEncoded())));
        map.put(PRIVATE_KEY, new String(Base64Utils.encode(privateKey.getEncoded())));
        return map;
    } catch (Exception e) {
        e.printStackTrace();
        throw new CustomException("生成秘钥对失败");
    }
}
项目:BiglyBT    文件:JDKDigestSignature.java   
@Override
  protected void engineInitSign(
      PrivateKey  privateKey)
      throws InvalidKeyException
  {
if ( !(privateKey instanceof RSAPrivateKey) )
{
    throw new InvalidKeyException("Supplied key is not a RSAPrivateKey instance");
}

      CipherParameters    param = RSAUtil.generatePrivateKeyParameter((RSAPrivateKey)privateKey);

      digest.reset();

      cipher.init(true, param);
  }
项目:mumu    文件:RSACoder.java   
/**
 * 初始化密钥
 * 
 * @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;
}
项目:iBase4J    文件:RSACoder.java   
/**
 * 初始化密钥
 * 
 * @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;
}
项目:quilt    文件:RsaSha256SignatureTest.java   
/**
 * This test ensures that the supplied private key signs a message correctly.
 */
@Test
public void testVerifiesCorrectly()
    throws Exception {

  final String privKeyPem = rsaJsonTestVector.getPrivateKey();
  final RSAPrivateKey privKey = this.buildRsaPrivKey(privKeyPem);

  rsaJsonTestVector.getCases().stream().forEach(_case -> {
    try {
      final byte[] saltHex = BaseEncoding.base16().decode(_case.getSalt().toUpperCase());
      rsaSigner.initSign(privKey, new FixedRandom(saltHex));
      rsaSigner.update(BaseEncoding.base16().decode(_case.getMessage().toUpperCase()));

      final byte[] expectedSignatureBytes = BaseEncoding.base16()
          .decode(_case.getSignature().toUpperCase());

      final byte[] actualSignatureByte = rsaSigner.sign();
      assertThat(actualSignatureByte, is(expectedSignatureBytes));

    } catch (Exception e) {
      throw new RuntimeException(e);
    }
  });
}
项目:bird-java    文件:RSACoder.java   
/**
 * 初始化密钥
 *
 * @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;
}
项目:javaOIDCMsg    文件:RSAAlgorithmTest.java   
@Test
public void shouldDoRSA384SigningWithProvidedPrivateKey() throws Exception {
    RSAKeyProvider provider = mock(RSAKeyProvider.class);
    PrivateKey privateKey = readPrivateKeyFromFile(PRIVATE_KEY_FILE, "RSA");
    PublicKey publicKey = readPublicKeyFromFile(PUBLIC_KEY_FILE, "RSA");
    when(provider.getPrivateKey()).thenReturn((RSAPrivateKey) privateKey);
    when(provider.getPublicKeyById(null)).thenReturn((RSAPublicKey) publicKey);
    Algorithm algorithm = Algorithm.RSA384(provider);
    String jwtContent = String.format("%s.%s", RS384Header, auth0IssPayload);
    byte[] contentBytes = jwtContent.getBytes(StandardCharsets.UTF_8);
    byte[] signatureBytes = algorithm.sign(contentBytes);
    String jwtSignature = Base64.encodeBase64URLSafeString(signatureBytes);
    String token = String.format("%s.%s", jwtContent, jwtSignature);

    assertThat(signatureBytes, is(notNullValue()));
    JWT jwt = JWT.require(algorithm).withIssuer("auth0").build();
    DecodedJWT decoded = jwt.decode(token);
    algorithm.verify(decoded, EncodeType.Base64);
}
项目:ISO9796SignerVerifier    文件:App.java   
private static byte[] sign() throws Exception {
    RSAEngine rsa = new RSAEngine();
    Digest dig = new SHA1Digest();

    RSAPrivateKey privateKey = (RSAPrivateKey) getPrivate(privateKeyFilename);
    BigInteger big = ((RSAKey) privateKey).getModulus();
    ISO9796d2Signer eng = new ISO9796d2Signer(rsa, dig, true);
    RSAKeyParameters rsaPriv = new RSAKeyParameters(true, big, privateKey.getPrivateExponent());
    eng.init(true, rsaPriv);
    eng.update(message[0]);
    eng.update(message, 1, message.length - 1);

    byte[] signature = eng.generateSignature();

    return signature;
}
项目:javaOIDCMsg    文件:RSAAlgorithmTest.java   
@Test
public void shouldDoRSA384SigningWithBothKeys() throws Exception {
    Algorithm algorithm = Algorithm.RSA384((RSAPublicKey) readPublicKeyFromFile(PUBLIC_KEY_FILE, "RSA"), (RSAPrivateKey) readPrivateKeyFromFile(PRIVATE_KEY_FILE, "RSA"));

    String jwtContent = String.format("%s.%s", RS384Header, auth0IssPayload);
    byte[] contentBytes = jwtContent.getBytes(StandardCharsets.UTF_8);
    byte[] signatureBytes = algorithm.sign(contentBytes);
    String jwtSignature = Base64.encodeBase64URLSafeString(signatureBytes);
    String token = String.format("%s.%s", jwtContent, jwtSignature);
    String expectedSignature = "Jx1PaTBnjd_U56MNjifFcY7w9ImDbseg0y8Ijr2pSiA1_wzQb_wy9undaWfzR5YqdIAXvjS8AGuZUAzIoTG4KMgOgdVyYDz3l2jzj6wI-lgqfR5hTy1w1ruMUQ4_wobpdxAiJ4fEbg8Mi_GljOiCO-P1HilxKnpiOJZidR8MQGwTInsf71tOUkK4x5UsdmUueuZbaU-CL5kPnRfXmJj9CcdxZbD9oMlbo23dwkP5BNMrS2LwGGzc9C_-ypxrBIOVilG3WZxcSmuG86LjcZbnL6LBEfph5NmKBgQav147uipb_7umBEr1m2dYiB_9u606n3bcoo3rnsYYK_Xfi1GAEQ";

    assertThat(signatureBytes, is(notNullValue()));
    assertThat(jwtSignature, is(expectedSignature));
    JWT jwt = JWT.require(algorithm).withIssuer("auth0").build();
    DecodedJWT decoded = jwt.decode(token);
    algorithm.verify(decoded, EncodeType.Base64);
}
项目:javaOIDCMsg    文件:RSAAlgorithmTest.java   
@Test
public void shouldDoRSA256SigningWithBothKeys() throws Exception {
    Algorithm algorithm = Algorithm.RSA256((RSAPublicKey) readPublicKeyFromFile(PUBLIC_KEY_FILE, "RSA"), (RSAPrivateKey) readPrivateKeyFromFile(PRIVATE_KEY_FILE, "RSA"));

    String jwtContent = String.format("%s.%s", RS256Header, auth0IssPayload);
    byte[] contentBytes = jwtContent.getBytes(StandardCharsets.UTF_8);
    byte[] signatureBytes = algorithm.sign(contentBytes);
    String jwtSignature = Base64.encodeBase64URLSafeString(signatureBytes);
    String token = String.format("%s.%s", jwtContent, jwtSignature);
    String expectedSignature = "ZB-Tr0vLtnf8I9fhSdSjU6HZei5xLYZQ6nZqM5O6Va0W9PgAqgRT7ShI9CjeYulRXPHvVmSl5EQuYuXdBzM0-H_3p_Nsl6tSMy4EyX2kkhEm6T0HhvarTh8CG0PCjn5p6FP5ZxWwhLcmRN70ItP6Z5MMO4CcJh1JrNxR4Fi4xQgt-CK2aVDMFXd-Br5yQiLVx1CX83w28OD9wssW3Rdltl5e66vCef0Ql6Q5I5e5F0nqGYT989a9fkNgLIx2F8k_az5x07BY59FV2SZg59nSiY7TZNjP8ot11Ew7HKRfPXOdh9eKRUVdhcxzqDePhyzKabU8TG5FP0SiWH5qVPfAgw";

    assertThat(signatureBytes, is(notNullValue()));
    assertThat(jwtSignature, is(expectedSignature));
    JWT jwt = JWT.require(algorithm).withIssuer("auth0").build();
    DecodedJWT decoded = jwt.decode(token);
    algorithm.verify(decoded, EncodeType.Base64);
}
项目:GroupControlDroidClient    文件:RSAUtil.java   
/**
 * 私钥解密
 * 
 * @param data
 * @param privateKey
 * @return
 * @throws Exception
 */
public static String decryptByPrivateKey(String data,
        RSAPrivateKey privateKey) throws Exception {
    Cipher cipher = Cipher.getInstance("RSA");
    cipher.init(Cipher.DECRYPT_MODE, privateKey);
    // 模长
    int key_len = privateKey.getModulus().bitLength() / 8;
    byte[] bytes = data.getBytes();
    byte[] bcd = ASCII_To_BCD(bytes, bytes.length);
    System.err.println("bcd.length:"+bcd.length);
    // 如果密文长度大于模长则要分组解密
    String ming = "";
    byte[][] arrays = splitArray(bcd, key_len);
    for (byte[] arr : arrays) {
        ming += new String(cipher.doFinal(arr));
    }
    return ming;
}
项目:javaOIDCMsg    文件:RSAAlgorithmTest.java   
@Test
public void shouldThrowWhenTheSignatureIsNotPrepared() throws Exception {
    exception.expect(AlgorithmMismatchException.class);
    exception.expectMessage("The provided Algorithm doesn't match the one defined in the JWT's Header.");

    CryptoHelper crypto = mock(CryptoHelper.class);
    when(crypto.verifySignatureFor(anyString(), any(PublicKey.class), any(byte[].class), any(byte[].class)))
            .thenThrow(SignatureException.class);

    RSAPublicKey publicKey = mock(RSAPublicKey.class);
    RSAPrivateKey privateKey = mock(RSAPrivateKey.class);
    RSAKeyProvider provider = RSAAlgorithm.providerForKeys(publicKey, privateKey);
    Algorithm algorithm = new RSAAlgorithm(crypto, "some-alg", "some-algorithm", provider);
    String token = "eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJhdXRoMCJ9.dxXF3MdsyW-AuvwJpaQtrZ33fAde9xWxpLIg9cO2tMLH2GSRNuLAe61KsJusZhqZB9Iy7DvflcmRz-9OZndm6cj_ThGeJH2LLc90K83UEvvRPo8l85RrQb8PcanxCgIs2RcZOLygERizB3pr5icGkzR7R2y6zgNCjKJ5_NJ6EiZsGN6_nc2PRK_DbyY-Wn0QDxIxKoA5YgQJ9qafe7IN980pXvQv2Z62c3XR8dYuaXBqhthBj-AbaFHEpZapN-V-TmuLNzR2MCB6Xr7BYMuCaqWf_XU8og4XNe8f_8w9Wv5vvgqMM1KhqVpG5VdMJv4o_L4NoCROHhtUQSLRh2M9cA";
    JWT jwt = JWT.require(algorithm).withIssuer("auth0").build();
    DecodedJWT decoded = jwt.decode(token);
    algorithm.verify(decoded, EncodeType.Base64);
}
项目:jdk8u-jdk    文件:SpecTest.java   
/**
 *
 * @param kpair test key pair
 * @param pubExponent expected public exponent.
 * @return true if test passed. false if test failed.
 */
private static boolean specTest(KeyPair kpair, BigInteger pubExponent) {
    boolean passed = true;
    RSAPrivateKey priv = (RSAPrivateKey) kpair.getPrivate();
    RSAPublicKey pub = (RSAPublicKey) kpair.getPublic();

    // test the getModulus method
    if ((priv instanceof RSAKey) && (pub instanceof RSAKey)) {
        if (!priv.getModulus().equals(pub.getModulus())) {
            System.err.println("priv.getModulus() = " + priv.getModulus());
            System.err.println("pub.getModulus() = " + pub.getModulus());
            passed = false;
        }

        if (!pubExponent.equals(pub.getPublicExponent())) {
            System.err.println("pubExponent = " + pubExponent);
            System.err.println("pub.getPublicExponent() = "
                    + pub.getPublicExponent());
            passed = false;
        }
    }
    return passed;
}
项目:dble    文件:DecryptUtil.java   
public 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"));
    String encryptedString = Base64.byteArrayToBase64(encryptedBytes);

    return encryptedString;
}
项目:javaOIDCMsg    文件:RSAAlgorithmTest.java   
@Test
public void shouldDoRSA512SigningWithBothKeys() throws Exception {
    Algorithm algorithm = Algorithm.RSA512((RSAPublicKey) readPublicKeyFromFile(PUBLIC_KEY_FILE, "RSA"), (RSAPrivateKey) readPrivateKeyFromFile(PRIVATE_KEY_FILE, "RSA"));

    String jwtContent = String.format("%s.%s", RS512Header, auth0IssPayload);
    byte[] contentBytes = jwtContent.getBytes(StandardCharsets.UTF_8);
    byte[] signatureBytes = algorithm.sign(contentBytes);
    String jwtSignature = Base64.encodeBase64URLSafeString(signatureBytes);
    String token = String.format("%s.%s", jwtContent, jwtSignature);
    String expectedSignature = "THIPVYzNZ1Yo_dm0k1UELqV0txs3SzyMopCyHcLXOOdgYXF4MlGvBqu0CFvgSga72Sp5LpuC1Oesj40v_QDsp2GTGDeWnvvcv_eo-b0LPSpmT2h1Ibrmu-z70u2rKf28pkN-AJiMFqi8sit2kMIp1bwIVOovPvMTQKGFmova4Xwb3G526y_PeLlflW1h69hQTIVcI67ACEkAC-byjDnnYIklA-B4GWcggEoFwQRTdRjAUpifA6HOlvnBbZZlUd6KXwEydxVS-eh1odwPjB2_sfbyy5HnLsvNdaniiZQwX7QbwLNT4F72LctYdHHM1QCrID6bgfgYp9Ij9CRX__XDEA";

    assertThat(signatureBytes, is(notNullValue()));
    assertThat(jwtSignature, is(expectedSignature));
    JWT jwt = JWT.require(algorithm).withIssuer("auth0").build();
    DecodedJWT decoded = jwt.decode(token);
    algorithm.verify(decoded, EncodeType.Base64);
}
项目:openjdk-jdk10    文件:CipherTestUtils.java   
private static KeyStore createServerKeyStore(String publicKey,
        String keySpecStr) throws KeyStoreException, IOException,
        NoSuchAlgorithmException, CertificateException,
        InvalidKeySpecException {

    KeyStore ks = KeyStore.getInstance("JKS");
    ks.load(null, null);
    if (publicKey == null || keySpecStr == null) {
        throw new IllegalArgumentException("publicKey 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(publicKey.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;
}
项目:L2jBrasil    文件:LoginController.java   
/**
 * This is mostly to force the initialization of the Crypto Implementation, avoiding it being done on runtime when its first needed.<BR>
 * In short it avoids the worst-case execution time on runtime by doing it on loading.
 * @param key Any private RSA Key just for testing purposes.
 * @throws GeneralSecurityException if a underlying exception was thrown by the Cipher
 */
private static void testCipher(RSAPrivateKey key) throws GeneralSecurityException
{
    // avoid worst-case execution, KenM
    Cipher rsaCipher = Cipher.getInstance("RSA/ECB/nopadding");
    rsaCipher.init(Cipher.DECRYPT_MODE, key);
}
项目:L2jBrasil    文件:BlowFishKey.java   
/**
 * @param decrypt
 */
public BlowFishKey(byte[] decrypt, RSAPrivateKey privateKey)
{
    super(decrypt);
    int size = readD();
    byte[] tempKey = readB(size);
    try
    {
        byte [] tempDecryptKey;
        Cipher rsaCipher = Cipher.getInstance("RSA/ECB/nopadding");
        rsaCipher.init(Cipher.DECRYPT_MODE, privateKey);
        tempDecryptKey = rsaCipher.doFinal(tempKey);
        // there are nulls before the key we must remove them
        int i = 0;
        int len = tempDecryptKey.length;
        for(; i < len; i++)
        {
            if(tempDecryptKey[i] != 0)
                break;
        }
        _key = new byte[len-i];
        System.arraycopy(tempDecryptKey,i,_key,0,len-i);
    }
    catch(GeneralSecurityException e)
    {
        _log.severe("Error While decrypting blowfish key (RSA)");
        e.printStackTrace();
    }
    /*catch(IOException ioe)
    {
        //TODO: manage
    }*/

}
项目:HerbertyyRepository    文件:RSAUtils.java   
public static void printPrivateKeyInfo(PrivateKey privateKey)
{
    RSAPrivateKey rsaPrivateKey = (RSAPrivateKey) privateKey;
    System.out.println("----------RSAPrivateKey ----------");
    System.out.println("Modulus.length=" + rsaPrivateKey.getModulus().bitLength());
    System.out.println("Modulus=" + rsaPrivateKey.getModulus().toString());
    System.out.println("PrivateExponent.length=" + rsaPrivateKey.getPrivateExponent().bitLength());
    System.out.println("PrivatecExponent=" + rsaPrivateKey.getPrivateExponent().toString());

}
项目:ipack    文件:PSSSignatureSpi.java   
protected void engineInitSign(
    PrivateKey privateKey,
    SecureRandom random)
    throws InvalidKeyException
{
    if (!(privateKey instanceof RSAPrivateKey))
    {
        throw new InvalidKeyException("Supplied key is not a RSAPrivateKey instance");
    }

    pss = new org.bouncycastle.crypto.signers.PSSSigner(signer, contentDigest, mgfDigest, saltLength, trailer);
    pss.init(true, new ParametersWithRandom(RSAUtil.generatePrivateKeyParameter((RSAPrivateKey)privateKey), random));
}
项目:ipack    文件:PSSSignatureSpi.java   
protected void engineInitSign(
    PrivateKey privateKey)
    throws InvalidKeyException
{
    if (!(privateKey instanceof RSAPrivateKey))
    {
        throw new InvalidKeyException("Supplied key is not a RSAPrivateKey instance");
    }

    pss = new org.bouncycastle.crypto.signers.PSSSigner(signer, contentDigest, mgfDigest, saltLength, trailer);
    pss.init(true, RSAUtil.generatePrivateKeyParameter((RSAPrivateKey)privateKey));
}
项目:ipack    文件:CMSSignedGenerator.java   
protected String getEncOID(
    PrivateKey key,
    String     digestOID)
{
    String encOID = null;

    if (key instanceof RSAPrivateKey || "RSA".equalsIgnoreCase(key.getAlgorithm()))
    {
        encOID = ENCRYPTION_RSA;
    }
    else if (key instanceof DSAPrivateKey || "DSA".equalsIgnoreCase(key.getAlgorithm()))
    {
        encOID = ENCRYPTION_DSA;
        if (!digestOID.equals(DIGEST_SHA1))
        {
            throw new IllegalArgumentException("can't mix DSA with anything but SHA1");
        }
    }
    else if ("ECDSA".equalsIgnoreCase(key.getAlgorithm()) || "EC".equalsIgnoreCase(key.getAlgorithm()))
    {
        encOID = (String)EC_ALGORITHMS.get(digestOID);
        if (encOID == null)
        {
            throw new IllegalArgumentException("can't mix ECDSA with anything but SHA family digests");
        }
    }
    else if (key instanceof GOST3410PrivateKey || "GOST3410".equalsIgnoreCase(key.getAlgorithm()))
    {
        encOID = ENCRYPTION_GOST3410;
    }
    else if ("ECGOST3410".equalsIgnoreCase(key.getAlgorithm()))
    {
        encOID = ENCRYPTION_ECGOST3410;
    }

    return encOID;
}
项目:19porn    文件:Codec.java   
/**
 * 初始化密钥
 *
 * @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;
}
项目:godlibrary    文件:RSAUtlis.java   
/**
 * 初始化密钥
 *
 * @return
 * @throws Exception
 */
public static Map<String, Object> initKey() throws Exception {
    KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(KEY_ALGORITHM);
    keyPairGenerator.initialize(512);
    KeyPair keyPair = keyPairGenerator.generateKeyPair();
    // 公钥
    RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
    // 私钥
    RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();

    Map<String, Object> keyMap = new HashMap<String, Object>(2);
    keyMap.put("PublicKey", publicKey);
    keyMap.put("PrivateKey", privateKey);
    return keyMap;
}
项目:Selector    文件:RSASecurityUtils.java   
/**
 * 使用模和指数生成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("RSA");
        RSAPrivateKeySpec keySpec = new RSAPrivateKeySpec(b1, b2);
        return (RSAPrivateKey) keyFactory.generatePrivate(keySpec);
    } catch (Exception e) {
        e.printStackTrace();
        return null;
    }
}
项目:opencron    文件:RSAUtils.java   
/**
 * <p>
 * 生成密钥对(公钥和私钥)
 * </p>
 *
 * @return
 * @throws Exception
 */
public static Map<String, Object> genKeyPair() throws Exception {
    KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance(KEY_ALGORITHM);
    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;
}
项目:encrypt    文件:RSAUtil.java   
/**
 * 随机获取密钥(公钥和私钥), 客户端公钥加密,服务器私钥解密
 *
 * @return 结果密钥对
 * @throws Exception 异常
 */
public static Map<String, Object> getKeyPair() throws Exception {
    KeyPairGenerator keyPairGen = getKeyPairGenerator();
    keyPairGen.initialize(1024);

    KeyPair keyPair = keyPairGen.generateKeyPair();
    RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
    RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();

    Map<String, Object> keyMap = new HashMap<>(2);
    keyMap.put("RSAPublicKey", publicKey);
    keyMap.put("RSAPrivateKey", privateKey);
    return keyMap;
}