Search in sources :

Example 21 with RSAKey

use of com.nimbusds.jose.jwk.RSAKey in project tomee by apache.

the class KeyGeneratorUtil method generateKeyPair.

public static void generateKeyPair(String keyAlgorithm, int keySize) throws NoSuchAlgorithmException {
    // RSA
    KeyPairGenerator kpg = KeyPairGenerator.getInstance(keyAlgorithm);
    // 2048
    kpg.initialize(keySize);
    KeyPair kp = kpg.generateKeyPair();
    System.out.println("-----BEGIN PRIVATE KEY-----");
    System.out.println(Base64.getMimeEncoder().encodeToString(kp.getPrivate().getEncoded()));
    System.out.println("-----END PRIVATE KEY-----");
    System.out.println("-----BEGIN PUBLIC KEY-----");
    System.out.println(Base64.getMimeEncoder().encodeToString(kp.getPublic().getEncoded()));
    System.out.println("-----END PUBLIC KEY-----");
    RSAPublicKey publicKey = (RSAPublicKey) kp.getPublic();
    RSAKey jwk = new RSAKey.Builder(publicKey).privateKey((RSAPrivateKey) kp.getPrivate()).keyUse(KeyUse.SIGNATURE).keyID(UUID.randomUUID().toString()).build();
    System.out.println(jwk.toJSONObject().toJSONString());
}
Also used : KeyPair(java.security.KeyPair) RSAKey(com.nimbusds.jose.jwk.RSAKey) RSAPublicKey(java.security.interfaces.RSAPublicKey) KeyPairGenerator(java.security.KeyPairGenerator) RSAPrivateKey(java.security.interfaces.RSAPrivateKey)

Example 22 with RSAKey

use of com.nimbusds.jose.jwk.RSAKey in project SEPA by arces-wot.

the class SecurityManagerTest method generateToken.

private SignedJWT generateToken(DigitalIdentity identity, String password) throws ParseException, KeyStoreException, NoSuchAlgorithmException, CertificateException, FileNotFoundException, IOException, JOSEException, SEPASecurityException {
    // Prepare JWT with claims set
    JWTClaimsSet.Builder claimsSetBuilder = new JWTClaimsSet.Builder();
    // Define validity period
    Date now = new Date();
    long exp = 0;
    if (identity.getClass().equals(DeviceIdentity.class)) {
        exp = auth.getDeviceExpiringPeriod();
    } else if (identity.getClass().equals(ApplicationIdentity.class)) {
        exp = auth.getApplicationExpiringPeriod();
    } else
        exp = auth.getDefaultExpiringPeriod();
    Date expires = new Date(now.getTime() + exp * 1000);
    claimsSetBuilder.issuer("http://issuer");
    claimsSetBuilder.subject("http://subject");
    ArrayList<String> audience = new ArrayList<String>();
    audience.add("https://audience");
    audience.add("wss://audience");
    claimsSetBuilder.audience(audience);
    claimsSetBuilder.expirationTime(expires);
    claimsSetBuilder.issueTime(now);
    claimsSetBuilder.jwtID(identity.getUid() + ":" + password + ":" + UUID.randomUUID());
    JWTClaimsSet jwtClaims = claimsSetBuilder.build();
    // ******************************
    // Sign JWT with private RSA key
    // ******************************
    SignedJWT signedJWT;
    signedJWT = new SignedJWT(new JWSHeader(JWSAlgorithm.RS256), JWTClaimsSet.parse(jwtClaims.toString()));
    // // Load the key from the key store
    // KeyStore keystore = KeyStore.getInstance("JKS");
    // 
    // keystore.load(new FileInputStream(jksFile), storePass.toCharArray());
    // RSAKey jwk = RSAKey.load(keystore, alias, keyPass.toCharArray());
    RSAKey jwk = configurationProvider.getRsaKey();
    // Get the private and public keys to sign and verify
    RSAPrivateKey privateKey = jwk.toRSAPrivateKey();
    // Create RSA-signer with the private key
    JWSSigner signer = new RSASSASigner(privateKey);
    signedJWT.sign(signer);
    return signedJWT;
}
Also used : RSAKey(com.nimbusds.jose.jwk.RSAKey) ApplicationIdentity(it.unibo.arces.wot.sepa.engine.dependability.authorization.identities.ApplicationIdentity) ArrayList(java.util.ArrayList) SignedJWT(com.nimbusds.jwt.SignedJWT) Date(java.util.Date) JWTClaimsSet(com.nimbusds.jwt.JWTClaimsSet) RSASSASigner(com.nimbusds.jose.crypto.RSASSASigner) RSAPrivateKey(java.security.interfaces.RSAPrivateKey) JWSSigner(com.nimbusds.jose.JWSSigner) JWSHeader(com.nimbusds.jose.JWSHeader)

Example 23 with RSAKey

use of com.nimbusds.jose.jwk.RSAKey in project mycore by MyCoRe-Org.

the class MCRJSONWebTokenUtil method retrievePublicKeyFromLoginToken.

/**
 * retrieves the client public key from Login Token
 *
 * @param token - the serialized JSON Web Token from login
 * @return the public key as JWK object
 */
public static JWK retrievePublicKeyFromLoginToken(String token) {
    JWK result = null;
    JWEObject jweObject;
    try {
        jweObject = JWEObject.parse(token);
        // Decrypt with shared key
        jweObject.decrypt(new RSADecrypter(RSA_KEYS.getPrivate()));
        // Extract payload
        SignedJWT signedJWT = jweObject.getPayload().toSignedJWT();
        result = signedJWT.getHeader().getJWK();
        RSAKey publicKey = RSAKey.parse(result.toJSONObject());
        if (signedJWT.verify(new RSASSAVerifier(publicKey))) {
            return result;
        }
    } catch (ParseException | JOSEException e) {
        LOGGER.error(e);
    }
    return null;
}
Also used : RSAKey(com.nimbusds.jose.jwk.RSAKey) JWEObject(com.nimbusds.jose.JWEObject) RSASSAVerifier(com.nimbusds.jose.crypto.RSASSAVerifier) SignedJWT(com.nimbusds.jwt.SignedJWT) ParseException(java.text.ParseException) JOSEException(com.nimbusds.jose.JOSEException) JWK(com.nimbusds.jose.jwk.JWK) RSADecrypter(com.nimbusds.jose.crypto.RSADecrypter)

Example 24 with RSAKey

use of com.nimbusds.jose.jwk.RSAKey in project mycore by MyCoRe-Org.

the class MCRJSONWebTokenUtil method retrieveUsernamePasswordFromLoginToken.

/**
 * retrieves username and password from JSON web tocken
 *
 * @param token - the serialized JSON web token from login
 * @return username and password (combined by ":")
 */
public static String retrieveUsernamePasswordFromLoginToken(String token) {
    JWEObject jweObject;
    try {
        jweObject = JWEObject.parse(token);
        // Decrypt with shared key
        jweObject.decrypt(new RSADecrypter(RSA_KEYS.getPrivate()));
        // Extract payload
        SignedJWT signedJWT = jweObject.getPayload().toSignedJWT();
        RSAKey serverPublicKey = RSAKey.parse(signedJWT.getHeader().getJWK().toJSONObject());
        if (signedJWT.verify(new RSASSAVerifier(serverPublicKey))) {
            // Token is valid
            String username = signedJWT.getJWTClaimsSet().getSubject();
            String password = signedJWT.getJWTClaimsSet().getStringClaim("password");
            return username + ":" + password;
        }
    } catch (ParseException | JOSEException e) {
        LOGGER.error(e);
    }
    return null;
}
Also used : RSAKey(com.nimbusds.jose.jwk.RSAKey) JWEObject(com.nimbusds.jose.JWEObject) RSASSAVerifier(com.nimbusds.jose.crypto.RSASSAVerifier) SignedJWT(com.nimbusds.jwt.SignedJWT) ParseException(java.text.ParseException) JOSEException(com.nimbusds.jose.JOSEException) RSADecrypter(com.nimbusds.jose.crypto.RSADecrypter)

Example 25 with RSAKey

use of com.nimbusds.jose.jwk.RSAKey in project oxAuth by GluuFederation.

the class CrossEncryptionTest method encryptWithGluuJweEncrypter.

private String encryptWithGluuJweEncrypter() {
    try {
        RSAKey recipientPublicJWK = (RSAKey) (JWK.parse(recipientJwkJson));
        BlockEncryptionAlgorithm blockEncryptionAlgorithm = BlockEncryptionAlgorithm.A128GCM;
        KeyEncryptionAlgorithm keyEncryptionAlgorithm = KeyEncryptionAlgorithm.RSA_OAEP;
        Jwe jwe = new Jwe();
        jwe.getHeader().setType(JwtType.JWT);
        jwe.getHeader().setAlgorithm(keyEncryptionAlgorithm);
        jwe.getHeader().setEncryptionMethod(blockEncryptionAlgorithm);
        jwe.getClaims().setIssuer("https:devgluu.saminet.local");
        jwe.getClaims().setSubjectIdentifier("testing");
        jwe.getHeader().setKeyId("1");
        JweEncrypterImpl encrypter = new JweEncrypterImpl(keyEncryptionAlgorithm, blockEncryptionAlgorithm, recipientPublicJWK.toPublicKey());
        jwe = encrypter.encrypt(jwe);
        // System.out.println("EncodedIntegrityValue: " + jwe.getEncodedIntegrityValue());
        return jwe.toString();
    } catch (Exception e) {
        System.out.println("Error encryption with Gluu JweEncrypter: " + e.getMessage());
        return null;
    }
}
Also used : RSAKey(com.nimbusds.jose.jwk.RSAKey) KeyEncryptionAlgorithm(org.gluu.oxauth.model.crypto.encryption.KeyEncryptionAlgorithm) Jwe(org.gluu.oxauth.model.jwe.Jwe) JweEncrypterImpl(org.gluu.oxauth.model.jwe.JweEncrypterImpl) JSONException(org.json.JSONException) ParseException(java.text.ParseException) InvalidJwtException(org.gluu.oxauth.model.exception.InvalidJwtException) IOException(java.io.IOException) InvalidJweException(org.gluu.oxauth.model.exception.InvalidJweException) BlockEncryptionAlgorithm(org.gluu.oxauth.model.crypto.encryption.BlockEncryptionAlgorithm)

Aggregations

RSAKey (com.nimbusds.jose.jwk.RSAKey)36 Test (org.junit.jupiter.api.Test)14 RSAPrivateKey (java.security.interfaces.RSAPrivateKey)10 SignedJWT (com.nimbusds.jwt.SignedJWT)9 ParseException (java.text.ParseException)9 RSASSAVerifier (com.nimbusds.jose.crypto.RSASSAVerifier)8 JWK (com.nimbusds.jose.jwk.JWK)8 IOException (java.io.IOException)6 JOSEException (com.nimbusds.jose.JOSEException)5 JWKSelector (com.nimbusds.jose.jwk.JWKSelector)5 SecurityContext (com.nimbusds.jose.proc.SecurityContext)5 InvalidJweException (org.gluu.oxauth.model.exception.InvalidJweException)5 InvalidJwtException (org.gluu.oxauth.model.exception.InvalidJwtException)5 JSONException (org.json.JSONException)5 RSADecrypter (com.nimbusds.jose.crypto.RSADecrypter)4 Base64URL (com.nimbusds.jose.util.Base64URL)4 RSAPublicKey (java.security.interfaces.RSAPublicKey)4 JWSAlgorithm (com.nimbusds.jose.JWSAlgorithm)3 JWSVerifier (com.nimbusds.jose.JWSVerifier)3 RSASSASigner (com.nimbusds.jose.crypto.RSASSASigner)3