java.security.interfaces.RSAPublicKey Java Examples

The following examples show how to use java.security.interfaces.RSAPublicKey. 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: 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 #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: CachingOpenIdMetadata.java    From botbuilder-java with MIT License 6 votes vote down vote up
@SuppressWarnings("unchecked")
private OpenIdMetadataKey findKey(String keyId) {
    if (!keyCache.containsKey(keyId)) {
        LOGGER.warn("findKey: keyId " + keyId + " doesn't exist.");
        return null;
    }

    try {
        Jwk jwk = keyCache.get(keyId);
        OpenIdMetadataKey key = new OpenIdMetadataKey();
        key.key = (RSAPublicKey) jwk.getPublicKey();
        key.endorsements = (List<String>) jwk.getAdditionalAttributes().get("endorsements");
        key.certificateChain = jwk.getCertificateChain();
        return key;
    } catch (JwkException e) {
        String errorDescription = String.format("Failed to load keys: %s", e.getMessage());
        LOGGER.warn(errorDescription);
    }
    return null;
}
 
Example #4
Source File: JWKSResponseBuilder.java    From cellery-security with Apache License 2.0 6 votes vote down vote up
/**
 * Builds the JSON response of JWKS.
 *
 * @param publicKey   Public Key which should be included in the jwks response.
 * @param certificate Certificate which should be in the jwks response.
 * @return JSON JWKS response.
 * @throws CertificateException
 * @throws NoSuchAlgorithmException
 * @throws ParseException
 */
public static String buildResponse(PublicKey publicKey, Certificate certificate) throws CertificateException,
        NoSuchAlgorithmException, ParseException {

    JSONArray jwksArray = new JSONArray();
    JSONObject jwksJson = new JSONObject();

    if (publicKey instanceof RSAPublicKey) {
        RSAKey.Builder jwk = new RSAKey.Builder((RSAPublicKey) publicKey);
        jwk.keyID(CertificateUtils.getThumbPrint(certificate));
        jwk.algorithm(JWSAlgorithm.RS256);
        jwk.keyUse(KeyUse.parse("sig"));
        jwksArray.put(jwk.build().toJSONObject());
        jwksJson.put("keys", jwksArray);
        log.debug(jwksJson.toString());
    }
    return jwksJson.toString();
}
 
Example #5
Source File: BaseTestSupport.java    From termd with Apache License 2.0 6 votes vote down vote up
public static <T extends Key> void assertKeyEquals(String message, T expected, T actual) {
    if (expected == actual) {
        return;
    }

    assertEquals(message + "[algorithm]", expected.getAlgorithm(), actual.getAlgorithm());

    if (expected instanceof RSAPublicKey) {
        assertRSAPublicKeyEquals(message, RSAPublicKey.class.cast(expected), RSAPublicKey.class.cast(actual));
    } else if (expected instanceof DSAPublicKey) {
        assertDSAPublicKeyEquals(message, DSAPublicKey.class.cast(expected), DSAPublicKey.class.cast(actual));
    } else if (expected instanceof ECPublicKey) {
        assertECPublicKeyEquals(message, ECPublicKey.class.cast(expected), ECPublicKey.class.cast(actual));
    } else if (expected instanceof RSAPrivateKey) {
        assertRSAPrivateKeyEquals(message, RSAPrivateKey.class.cast(expected), RSAPrivateKey.class.cast(actual));
    } else if (expected instanceof ECPrivateKey) {
        assertECPrivateKeyEquals(message, ECPrivateKey.class.cast(expected), ECPrivateKey.class.cast(actual));
    }
    assertArrayEquals(message + "[encdoded-data]", expected.getEncoded(), actual.getEncoded());
}
 
Example #6
Source File: AbstractJWTFilter.java    From ambari-logsearch with Apache License 2.0 6 votes vote down vote up
private RSAPublicKey parseRSAPublicKey(String pem) throws ServletException {
  String fullPem = PEM_HEADER + pem + PEM_FOOTER;
  try {
    CertificateFactory fact = CertificateFactory.getInstance("X.509");
    ByteArrayInputStream is = new ByteArrayInputStream(fullPem.getBytes("UTF8"));

    X509Certificate cer = (X509Certificate) fact.generateCertificate(is);
    return (RSAPublicKey) cer.getPublicKey();
  } catch (CertificateException ce) {
    String message;
    if (pem.startsWith(PEM_HEADER)) {
      message = "CertificateException - be sure not to include PEM header "
        + "and footer in the PEM configuration element.";
    } else {
      message = "CertificateException - PEM may be corrupt";
    }
    throw new ServletException(message, ce);
  } catch (UnsupportedEncodingException uee) {
    throw new ServletException(uee);
  }
}
 
Example #7
Source File: LittleAuthRequestTest.java    From littleca with Apache License 2.0 6 votes vote down vote up
@Test
public void rsaAuthRefreshRequestBuildTest() throws Exception {
    String p12Password = "123456";
    String signAlg = "SHA256WITHRSA";
    String refreshToken = "xxxxx";
    KeyStore keyStore = CertUtil.readKeyStore("d:/cert/p12/rsa/client/client.p12", p12Password);
    PrivateKey privateKey = CertUtil.getPrivateKey(keyStore, p12Password, null);
    PublicKey publicKey = CertUtil.getPublicKey(keyStore, null);
    RSAPublicKey serverPublicKey = (RSAPublicKey) CertUtil.readPublicKeyPem("d:/cert/p12/rsa/server/server_pub.pem");
    ISign rsaSign = new RsaSign((RSAPublicKey) publicKey, (RSAPrivateKey) privateKey, signAlg);
    AuthRefreshRequestDTO authRefreshRequestDTO = newAuthRefreshRequest(rsaSign, refreshToken);
    byte[] data = JSONUtil.toJsonBytes(authRefreshRequestDTO);
    EncodeRequestDTO encodeRequestDTO = new EncodeRequestDTO();
    RSA rsa = new RSA();
    encodeRequestDTO.setData(Base64.encodeBase64URLSafeString(rsa.encrypt(data, serverPublicKey)));
    System.out.println(JSONUtil.toJsonString(encodeRequestDTO));
}
 
Example #8
Source File: RsaUtil.java    From bootshiro with MIT License 6 votes vote down vote up
public static String rsaEncode(String data, String publicKey) {

        try {

            //将字符串形式解析成类
            KeyFactory keyFactory = KeyFactory.getInstance(RSA_ALGORITHM);
            X509EncodedKeySpec keySpec = new X509EncodedKeySpec(Base64.decodeBase64(publicKey));
            RSAPublicKey rsaPublicKey = (RSAPublicKey) keyFactory.generatePublic(keySpec);

            Cipher cipher = Cipher.getInstance(RSA_ALGORITHM);
            cipher.init(Cipher.ENCRYPT_MODE, rsaPublicKey);

            return Base64.encodeBase64URLSafeString(cipher.doFinal(data.getBytes(StandardCharsets.UTF_8)));

        } catch (Exception e) {
           logger.warn(e.getMessage());
           return null;
        }
    }
 
Example #9
Source File: SpecTest.java    From dragonwell8_jdk with GNU General Public License v2.0 6 votes vote down vote up
/**
 *
 * @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.out.println("priv.getModulus() = " + priv.getModulus());
            System.out.println("pub.getModulus() = " + pub.getModulus());
            passed = false;
        }

        if (!pubExponent.equals(pub.getPublicExponent())) {
            System.out.println("pubExponent = " + pubExponent);
            System.out.println("pub.getPublicExponent() = "
                    + pub.getPublicExponent());
            passed = false;
        }
    }
    return passed;
}
 
Example #10
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 #11
Source File: NewSize7.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
public static void main(String[] args) throws Exception {
    String FILE = "newsize7-ks";
    new File(FILE).delete();
    sun.security.tools.keytool.Main.main(("-debug -genkeypair -keystore " +
            FILE +
            " -alias a -dname cn=c -storepass changeit" +
            " -keypass changeit -keyalg rsa").split(" "));
    KeyStore ks = KeyStore.getInstance("JKS");
    try (FileInputStream fin = new FileInputStream(FILE)) {
        ks.load(fin, "changeit".toCharArray());
    }
    Files.delete(Paths.get(FILE));
    RSAPublicKey r = (RSAPublicKey)ks.getCertificate("a").getPublicKey();
    if (r.getModulus().bitLength() != 2048) {
        throw new Exception("Bad keysize");
    }
    X509Certificate x = (X509Certificate)ks.getCertificate("a");
    if (!x.getSigAlgName().equals("SHA256withRSA")) {
        throw new Exception("Bad sigalg");
    }
}
 
Example #12
Source File: DefaultTokenAuthorityService.java    From knox with Apache License 2.0 6 votes vote down vote up
@Override
public boolean verifyToken(JWT token, RSAPublicKey publicKey)
    throws TokenServiceException {
  boolean rc;
  PublicKey key;
  try {
    if (publicKey == null) {
      key = ks.getSigningKeystore().getCertificate(getSigningKeyAlias()).getPublicKey();
    }
    else {
      key = publicKey;
    }
    JWSVerifier verifier = new RSASSAVerifier((RSAPublicKey) key);
    // TODO: interrogate the token for issuer claim in order to determine the public key to use for verification
    // consider jwk for specifying the key too
    rc = token.verify(verifier);
  } catch (KeyStoreException | KeystoreServiceException e) {
    throw new TokenServiceException("Cannot verify token.", e);
  }
  return rc;
}
 
Example #13
Source File: RSAProvider.java    From android-rsa with Apache License 2.0 6 votes vote down vote up
/**
 *
 * 生成KeyPair
 * @return
 * @throws Exception
 */
public static Map<String, Object> generateKeyPair() throws Exception {
    KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance(KEY_ALGORITHM);
    keyPairGen.initialize(KEYSIZE);
    KeyPair keyPair = keyPairGen.generateKeyPair();

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

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

    Map<String, Object> keys = new HashMap<String, Object>(3);
    keys.put(PUBLIC_KEY, publicKey);
    keys.put(PRIVATE_KEY, privateKey);
    keys.put(MODULES, modules);
    return keys;
}
 
Example #14
Source File: LittleAuthRequestTest.java    From littleca with Apache License 2.0 6 votes vote down vote up
@Test
public void rsaAuthRequestBuildTest() throws Exception {
    String apiAccount = "dushitaoyuan-rsa";
    String p12Password = "123456";
    String signAlg = "SHA256WITHRSA";
    KeyStore keyStore = CertUtil.readKeyStore("d:/cert/p12/rsa/client/client.p12", p12Password);
    RSAPrivateKey privateKey = (RSAPrivateKey) CertUtil.getPrivateKey(keyStore, p12Password, null);
    RSAPublicKey publicKey = (RSAPublicKey) CertUtil.getPublicKey(keyStore, null);
    RSAPublicKey serverPublicKey = (RSAPublicKey) CertUtil.readPublicKeyPem("d:/cert/p12/rsa/server/server_pub.pem");
    ISign rsaSign = new RsaSign(publicKey, privateKey, signAlg);
    AuthRequestDTO authRequestDTO = newAuthRequest(rsaSign, apiAccount);
    byte[] data = JSONUtil.toJsonBytes(authRequestDTO);
    EncodeRequestDTO encodeRequestDTO = new EncodeRequestDTO();
    RSA rsa = new RSA();
    encodeRequestDTO.setData(Base64.encodeBase64URLSafeString(rsa.encrypt(data, serverPublicKey)));
    System.out.println(JSONUtil.toJsonString(encodeRequestDTO));
}
 
Example #15
Source File: ConstantTokenProviderTest.java    From dcos-commons with Apache License 2.0 6 votes vote down vote up
private String createToken() throws NoSuchAlgorithmException {
    KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
    keyPairGenerator.initialize(2048);

    KeyPair keyPair = keyPairGenerator.generateKeyPair();
    Algorithm algorithm = Algorithm.RSA256((
            RSAPublicKey) keyPair.getPublic(), (RSAPrivateKey) keyPair.getPrivate());

    return JWT.create()
            .withExpiresAt(Date.from(Instant.now().plusSeconds(120)))
            .withClaim("uid", "test")
            .sign(algorithm);
}
 
Example #16
Source File: RSAKeyExchange.java    From openjsse with GNU General Public License v2.0 6 votes vote down vote up
@Override
public SSLPossession createPossession(HandshakeContext context) {
    try {
        EphemeralKeyManager ekm =
                context.sslContext.getEphemeralKeyManager();
        KeyPair kp = ekm.getRSAKeyPair(
                true, context.sslContext.getSecureRandom());
        if (kp != null) {
            return new EphemeralRSAPossession(
                    kp.getPrivate(), (RSAPublicKey)kp.getPublic());
        } else {
            // Could not generate the ephemeral key, ignore.
            return null;
        }
    } catch (RuntimeException rte) {
        // Could not determine keylength, ignore.
        return null;
    }
}
 
Example #17
Source File: CaClientExample.java    From xipki with Apache License 2.0 5 votes vote down vote up
protected static MyKeypair generateRsaKeypair() throws Exception {
  KeyPairGenerator kpGen = KeyPairGenerator.getInstance("RSA");
  kpGen.initialize(2048);

  KeyPair kp = kpGen.generateKeyPair();
  RSAPublicKey pubKey = (RSAPublicKey) kp.getPublic();

  SubjectPublicKeyInfo subjectPublicKeyInfo = new SubjectPublicKeyInfo(
      new AlgorithmIdentifier(PKCSObjectIdentifiers.rsaEncryption, DERNull.INSTANCE),
      new org.bouncycastle.asn1.pkcs.RSAPublicKey(pubKey.getModulus(),
          pubKey.getPublicExponent()));
  return new MyKeypair(kp.getPrivate(), subjectPublicKeyInfo);
}
 
Example #18
Source File: TestJsonWebToken.java    From smallrye-jwt with Apache License 2.0 5 votes vote down vote up
@Test(expectedExceptions = { ParseException.class }, description = "Illustrate validation of signer")
public void testNimbusFailSignature() throws Exception {
    HashSet<TokenUtils.InvalidClaims> invalidFields = new HashSet<>();
    invalidFields.add(TokenUtils.InvalidClaims.SIGNER);
    String token = TokenUtils.generateTokenString("/Token1.json", invalidFields);
    RSAPublicKey publicKey = (RSAPublicKey) TokenUtils.readPublicKey("/publicKey.pem");
    JWTAuthContextInfo contextInfo = new JWTAuthContextInfo(publicKey, "https://server.example.com");
    contextInfo.setExpGracePeriodSecs(60);
    JsonWebToken jwt = validateToken(token, contextInfo);
}
 
Example #19
Source File: RsaSharing.java    From protect with MIT License 5 votes vote down vote up
public RsaSharing(int n, int t, RSAPublicKey publicKey, RSAPrivateKey privateKey, ShamirShare[] shares,
		BigInteger v, BigInteger[] verificationKeys) {
	super();
	this.n = n;
	this.t = t;
	this.publicKey = publicKey;
	this.privateKey = privateKey;
	this.shares = shares;
	this.v = v;
	this.verificationKeys = verificationKeys;
}
 
Example #20
Source File: CaEmulator.java    From xipki with Apache License 2.0 5 votes vote down vote up
private static AsymmetricKeyParameter generatePublicKeyParameter(PublicKey key)
    throws InvalidKeyException {
  Args.notNull(key, "key");

  if (key instanceof RSAPublicKey) {
    RSAPublicKey rsaKey = (RSAPublicKey) key;
    return new RSAKeyParameters(false, rsaKey.getModulus(), rsaKey.getPublicExponent());
  } else if (key instanceof ECPublicKey) {
    return ECUtil.generatePublicKeyParameter(key);
  } else if (key instanceof DSAPublicKey) {
    return DSAUtil.generatePublicKeyParameter(key);
  } else {
    throw new InvalidKeyException("unknown key " + key.getClass().getName());
  }
}
 
Example #21
Source File: RSAEncryption.java    From Image-Cipher with Apache License 2.0 5 votes vote down vote up
private byte[] RSATypeEncryption(@NotNull String text) throws Exception {
  byte[] encrypted;
  KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA");
  generator.initialize(2048, new SecureRandom());
  KeyPair pair = generator.generateKeyPair();
  pubkey = (RSAPublicKey) pair.getPublic();
  privkey = (RSAPrivateKey) pair.getPrivate();
  Cipher cipher = Cipher.getInstance("RSA");
  cipher.init(Cipher.ENCRYPT_MODE, pubkey);

  encrypted = cipher.doFinal(text.getBytes());
  return encrypted;
}
 
Example #22
Source File: EncryptionManager.java    From minecraft-world-downloader with GNU General Public License v3.0 5 votes vote down vote up
/**
 * When the server sends the client an encryption request, this method will be called to get the server's given
 * public key and call the replacement request sender.
 * @param encoded  the encoded public key in X509
 * @param token    the server's verification token
 * @param serverId the server's id (not actually used)
 */
public void setServerEncryptionRequest(byte[] encoded, byte[] token, String serverId) {
    attempt(() -> {
        serverVerifyToken = token;
        this.serverId = serverId;

        KeyFactory kf = KeyFactory.getInstance("RSA");
        serverRealPublicKey = (RSAPublicKey) kf.generatePublic(new X509EncodedKeySpec(encoded));

        sendReplacementEncryptionRequest();
    });
}
 
Example #23
Source File: RSAUtils.java    From NutzSite with Apache License 2.0 5 votes vote down vote up
/**
 * RSA公钥加密
 *
 * @param str       加密字符串
 * @param publicKey 公钥
 * @return 密文
 * @throws Exception 加密过程中的异常信息
 */
public static String encrypt(String str, String publicKey) throws Exception {
    //base64编码的公钥
    byte[] decoded = Base64.getDecoder().decode(publicKey);
    RSAPublicKey pubKey = (RSAPublicKey) KeyFactory.getInstance(KEY_ALGORITHM).generatePublic(new X509EncodedKeySpec(decoded));
    //RSA加密
    Cipher cipher = Cipher.getInstance(KEY_ALGORITHM);
    cipher.init(Cipher.ENCRYPT_MODE, pubKey);
    String outStr = Base64.getEncoder().encodeToString(cipher.doFinal(str.getBytes("UTF-8")));
    return outStr;
}
 
Example #24
Source File: RSATool.java    From maintain with MIT License 5 votes vote down vote up
/**
 * 公钥加密
 * 
 * @param data
 * @param publicKey
 * @return
 * @throws Exception
 */
public static String encryptByPublicKey(String data, RSAPublicKey publicKey) throws Exception {
	Cipher cipher = Cipher.getInstance("RSA");
	cipher.init(Cipher.ENCRYPT_MODE, publicKey);
	// 模长
	int key_len = publicKey.getModulus().bitLength() / 8;
	// 加密数据长度 <= 模长-11
	String[] datas = splitString(data, key_len - 11);
	String mi = "";
	// 如果明文长度大于模长-11则要分组加密
	for (String s : datas) {
		mi += bcd2Str(cipher.doFinal(s.getBytes()));
	}
	return mi;
}
 
Example #25
Source File: Certs.java    From daq with Apache License 2.0 5 votes vote down vote up
private CertificateStatus validateCertificates(Certificate[] certificates) {
  for (Certificate certificate : certificates) {

    if (certificate instanceof X509Certificate) {
      try {
        certificateReport += "Certificate:\n" + certificate + "\n";
        // Check the expiration date
        X509Certificate x509Certificate = (X509Certificate) certificate;
        x509Certificate.checkValidity();
        certificateReport += "Certificate is active for current date.\n\n";
        // Check the public key bit length is at least 2048
        PublicKey key = x509Certificate.getPublicKey();
        int keyLength = 0;
        if (key instanceof RSAPublicKey) {
          keyLength = ((RSAPublicKey) key).getModulus().bitLength();
        } else if (key instanceof DSAPublicKey) {
          keyLength = ((DSAPublicKey) key).getParams().getP().bitLength();
        }
        if (keyLength >= 2048) {
          certificateReport += "Certificate has valid public key length: " + keyLength + "\n\n";
          return CertificateStatus.CERTIFICATE_VALID;
        }
        return CertificateStatus.PUBLIC_KEY_INVALID_LENGTH;
      } catch (CertificateExpiredException cee) {
        certificateReport += "Certificate is expired.\n";
        return CertificateStatus.CERTIFICATE_EXPIRED;
      } catch (CertificateNotYetValidException e) {
        certificateReport += "Certificate not yet valid.\n";
        return CertificateStatus.CERTIFICATE_NOT_YET_VALID;
      }
    } else {
      certificateReport += "Unsupported certificate type.\n";
      return CertificateStatus.CERTIFICATE_TYPE_UNSUPPORTED;
    }
  }
  return CertificateStatus.CERTIFICATE_INVALID;
}
 
Example #26
Source File: AlgorithmSuitePolicyValidator.java    From cxf with Apache License 2.0 5 votes vote down vote up
/**
 * Check the public key lengths
 */
private boolean checkPublicKeyLength(
    PublicKey publicKey,
    AlgorithmSuite algorithmPolicy,
    AssertionInfo ai
) {
    AlgorithmSuiteType algorithmSuiteType = algorithmPolicy.getAlgorithmSuiteType();
    if (publicKey instanceof RSAPublicKey) {
        int modulus = ((RSAPublicKey)publicKey).getModulus().bitLength();
        if (modulus < algorithmSuiteType.getMinimumAsymmetricKeyLength()
            || modulus > algorithmSuiteType.getMaximumAsymmetricKeyLength()) {
            ai.setNotAsserted(
                "The asymmetric key length does not match the requirement"
            );
            return false;
        }
    } else if (publicKey instanceof DSAPublicKey) {
        int length = ((DSAPublicKey)publicKey).getParams().getP().bitLength();
        if (length < algorithmSuiteType.getMinimumAsymmetricKeyLength()
            || length > algorithmSuiteType.getMaximumAsymmetricKeyLength()) {
            ai.setNotAsserted(
                "The asymmetric key length does not match the requirement"
            );
            return false;
        }
    } else {
        ai.setNotAsserted(
            "An unknown public key was provided"
        );
        return false;
    }

    return true;
}
 
Example #27
Source File: RSAUtils.java    From unimall with Apache License 2.0 5 votes vote down vote up
/**
 * 得到公钥
 * @param publicKey  密钥字符串(经过base64编码)
 * @throws Exception
 */
public static RSAPublicKey getPublicKey(String publicKey) throws NoSuchAlgorithmException, InvalidKeySpecException {
    // 通过X509编码的Key指令获得公钥对象
    KeyFactory keyFactory = KeyFactory.getInstance(RSA_ALGORITHM);
    X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(Base64.decodeBase64(publicKey));
    RSAPublicKey key = (RSAPublicKey) keyFactory.generatePublic(x509KeySpec);
    return key;
}
 
Example #28
Source File: ClientAssertionServiceTest.java    From graviteeio-access-management with Apache License 2.0 5 votes vote down vote up
@Test
public void testRsaJwt_withClientJwksUri() 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()));
    JWKSet jwkSet = new JWKSet();
    jwkSet.setKeys(Arrays.asList(key));

    Client client = new Client();
    client.setClientId(CLIENT_ID);
    client.setTokenEndpointAuthMethod(ClientAuthenticationMethod.PRIVATE_KEY_JWT);
    client.setJwksUri("http://fake/jwk/uri");
    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);
    when(jwkService.getKeys(anyString())).thenReturn(Maybe.just(jwkSet));
    when(jwkService.getKey(any(),any())).thenReturn(Maybe.just(key));
    when(jwsService.isValidSignature(any(),any())).thenReturn(true);

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

    testObserver.assertNoErrors();
    testObserver.assertValue(client);
}
 
Example #29
Source File: JsseJce.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 5 votes vote down vote up
static int getRSAKeyLength(PublicKey key) {
    BigInteger modulus;
    if (key instanceof RSAPublicKey) {
        modulus = ((RSAPublicKey)key).getModulus();
    } else {
        RSAPublicKeySpec spec = getRSAPublicKeySpec(key);
        modulus = spec.getModulus();
    }
    return modulus.bitLength();
}
 
Example #30
Source File: RSAEncryptCoder.java    From onetwo with Apache License 2.0 5 votes vote down vote up
public RSAEncryptCoder(int size, boolean generatedKeyPair){
	this.size = size;
	this.encryptSize = size/8-11;
	this.dencryptSize = size/8;
	
	if(generatedKeyPair){
		KeyPair kp = generatedKey();
		RSAPublicKey pubkey = (RSAPublicKey)kp.getPublic();
		publicKey = pubkey.getEncoded();
		
		RSAPrivateKey prikey = (RSAPrivateKey)kp.getPrivate();
		privateKey = prikey.getEncoded();
	}
}