Example usage for java.security Key getClass

List of usage examples for java.security Key getClass

Introduction

In this page you can find the example usage for java.security Key getClass.

Prototype

@HotSpotIntrinsicCandidate
public final native Class<?> getClass();

Source Link

Document

Returns the runtime class of this Object .

Usage

From source file:Main.java

/**
 * Returns the type of digital signature used with the specified signing key.
 *
 * @param signingKey private key that will be used to sign a certificate (or something else)
 * @return a string representing the digital signature type (ECDSA, RSA, etc.)
 *//* www. j  av a2s. co m*/
public static String getDigitalSignatureType(Key signingKey) {
    if (signingKey instanceof ECKey) {
        return "ECDSA";
    } else if (signingKey instanceof RSAKey) {
        return "RSA";
    } else if (signingKey instanceof DSAKey) {
        return "DSA";
    } else {
        throw new IllegalArgumentException(
                "Cannot determine digital signature encryption type for unknown key type: "
                        + signingKey.getClass().getCanonicalName());
    }

}

From source file:com.vmware.o11n.plugin.crypto.service.CryptoRSAService.java

/**
 * RSA Decryption/*from   w ww.  jav  a  2 s  .c  om*/
 *
 * @param pemKey RSA Private Key
 * @param encryptedB64 RSA Encrypted data encoded with Base64
 * @return Original data Base64 Encoded
 * @throws IOException
 * @throws NoSuchAlgorithmException
 * @throws InvalidKeySpecException
 * @throws NoSuchPaddingException
 * @throws InvalidKeyException
 * @throws IllegalBlockSizeException
 * @throws BadPaddingException
 */
public String decrypt(String pemKey, String encryptedB64)
        throws IOException, NoSuchAlgorithmException, InvalidKeySpecException, NoSuchPaddingException,
        InvalidKeyException, IllegalBlockSizeException, BadPaddingException {
    String dataB64 = null;
    PrivateKey privateKey = null;
    Key key = null;
    try {
        key = CryptoUtil.getKey(pemKey);
    } catch (IOException e) {
        //try to fix key:
        key = CryptoUtil.getKey(CryptoUtil.fixPemString(pemKey));
    }
    if (key instanceof PrivateKey) {
        privateKey = (PrivateKey) key;
    } else {
        throw new IllegalArgumentException("Invalid key object type: " + key.getClass().getName());
    }

    Cipher cipher = Cipher.getInstance(CIPHER_TRANSFORMATION);
    cipher.init(Cipher.DECRYPT_MODE, privateKey);
    dataB64 = Base64.encodeBase64String(cipher.doFinal(Base64.decodeBase64(encryptedB64)));
    return dataB64;
}

From source file:com.vmware.o11n.plugin.crypto.service.CryptoRSAService.java

/**
 * Creates an RSA Signature// ww  w  . jav a 2  s  .  c  o m
 *
 * @param pemKey RSA Private Key
 * @param dataB64 Base64 encoded data to sign
 * @return Base64 encoded signature
 * @throws NoSuchAlgorithmException
 * @throws InvalidKeySpecException
 * @throws IOException
 * @throws InvalidKeyException
 * @throws SignatureException
 */
public String sign(String pemKey, String dataB64) throws NoSuchAlgorithmException, InvalidKeySpecException,
        IOException, InvalidKeyException, SignatureException {
    String signatureB64 = null;
    PrivateKey privateKey = null;

    Key key = null;
    try {
        key = CryptoUtil.getKey(pemKey);
    } catch (IOException e) {
        //try to fix key:
        key = CryptoUtil.getKey(CryptoUtil.fixPemString(pemKey));
    }
    if (key instanceof PrivateKey) {
        privateKey = (PrivateKey) key;
    } else {
        throw new IllegalArgumentException("Invalid key object type: " + key.getClass().getName());
    }

    Signature signer = Signature.getInstance(SIGNATURE_ALGORITHM);
    signer.initSign(privateKey);
    signer.update(Base64.decodeBase64(dataB64));
    byte[] sigBytes = signer.sign();
    signatureB64 = Base64.encodeBase64String(sigBytes);

    return signatureB64;
}

From source file:com.vmware.o11n.plugin.crypto.service.CryptoRSAService.java

/**
 * RSA Encryption// w  w  w.  ja v  a  2 s  .  co m
 *
 * @param pemKey RSA Key (Public or Private, Public will be derived from Private)
 * @param dataB64 Data encoded with Base64 to encrypt
 * @return Encrypted data Base64 encoded
 * @throws IOException
 * @throws NoSuchAlgorithmException
 * @throws InvalidKeySpecException
 * @throws NoSuchPaddingException
 * @throws InvalidKeyException
 * @throws IllegalBlockSizeException
 * @throws BadPaddingException
 */
public String encrypt(String pemKey, String dataB64)
        throws IOException, NoSuchAlgorithmException, InvalidKeySpecException, NoSuchPaddingException,
        InvalidKeyException, IllegalBlockSizeException, BadPaddingException {
    String encryptedB64 = null;
    PublicKey publicKey = null;

    Key key = null;
    try {
        key = CryptoUtil.getKey(pemKey); //can be private or public
    } catch (IOException e) {
        //try to fix key:
        key = CryptoUtil.getKey(CryptoUtil.fixPemString(pemKey));
    }
    if (key instanceof RSAPublicKey) {
        publicKey = (RSAPublicKey) key;
    } else if (key instanceof RSAPrivateCrtKey) {
        RSAPrivateCrtKey privateKey = (RSAPrivateCrtKey) key;
        publicKey = CryptoUtil.getPublicFromPrivate(privateKey);
    } else {
        throw new IllegalArgumentException("Unknown key object type: " + key.getClass().getName());
    }

    Cipher cipher = Cipher.getInstance(CIPHER_TRANSFORMATION);
    cipher.init(Cipher.ENCRYPT_MODE, publicKey);
    encryptedB64 = Base64.encodeBase64String(cipher.doFinal(Base64.decodeBase64(dataB64)));
    return encryptedB64;
}

From source file:com.vmware.o11n.plugin.crypto.service.CryptoRSAService.java

/**
 * Verify a RSA Signature with a RSA Public Key
 *
 * @param pemKey RSA Key (Public or Private, Public will be derived from Private)
 * @param dataB64 Base64 encoded data the signature was created from
 * @param signatureB64 Base64 Encoded RSA Signature to verify
 * @return/*from w ww  .  ja v  a2  s  .c  om*/
 * @throws NoSuchAlgorithmException
 * @throws InvalidKeySpecException
 * @throws IOException
 * @throws InvalidKeyException
 * @throws SignatureException
 */
public boolean verifySignature(String pemKey, String dataB64, String signatureB64)
        throws NoSuchAlgorithmException, InvalidKeySpecException, IOException, InvalidKeyException,
        SignatureException {
    boolean valid = false;
    PublicKey publicKey = null;

    Key key = null;
    try {
        key = CryptoUtil.getKey(pemKey); //can be private or public
    } catch (IOException e) {
        //try to fix key:
        key = CryptoUtil.getKey(CryptoUtil.fixPemString(pemKey));
    }

    if (key instanceof RSAPublicKey) {
        publicKey = (RSAPublicKey) key;
    } else if (key instanceof RSAPrivateCrtKey) {
        RSAPrivateCrtKey privateKey = (RSAPrivateCrtKey) key;
        publicKey = CryptoUtil.getPublicFromPrivate(privateKey);
    } else {
        throw new IllegalArgumentException("Unknown key object type: " + key.getClass().getName());
    }

    Signature signer = Signature.getInstance(SIGNATURE_ALGORITHM);
    signer.initVerify(publicKey);
    signer.update(Base64.decodeBase64(dataB64));
    valid = signer.verify(Base64.decodeBase64(signatureB64));

    return valid;
}

From source file:it.scoppelletti.programmerpower.security.CryptoUtils.java

/**
 * Restituisce i parametri per la ricostruzione di una chiave di
 * crittografia.//from   w  ww  . j  a v  a2 s. c o m
 * 
 * <P>Il metodo {@code toProperties} rileva i provider del servizio
 * {@code KeyToPropertySetProvider} disponibili e delega il calcolo dei
 * parametri al primo di questi che supporta la tipologia della chiave di
 * crittografia {@code key}; se nessuno dei provider supporta la specifica
 * tipologia di chiavi, restituisce i parametri che rappresentano la chiave
 * codificata come sequenza di byte nel formato Base64 come definito da RFC
 * 2045.</P>
 * 
 * @param  key     Chiave.
 * @param  encoded Indica se restituire i parametri che rappresentano la
 *                 chiave codificata come sequenza di byte senza rilevare
 *                 gli eventuali provider {@code KeyToPropertySetProvider}
 *                 disponibili.
 * @return         Propriet&agrave;. 
 * @see #getKey
 * @see it.scoppelletti.programmerpower.security.spi.CryptoKeyFactory
 * @see it.scoppelletti.programmerpower.security.spi.EncodedKeyFactory
 * @see it.scoppelletti.programmerpower.security.spi.KeyToPropertySetProvider
 * @see <A HREF="http://www.ietf.org/rfc/rfc2045.txt" TARGET="_blank">RFC
 *      2045: Multipurpose Internet Mail Extensions (MIME) Part One: Format
 *      of Internet Message Bodies</A> 
 */
public static Properties toProperties(Key key, boolean encoded) {
    byte[] data;
    KeyRep.Type keyType;
    Properties props;
    KeyToPropertySetService svc;
    SecurityResources res = new SecurityResources();

    if (key == null) {
        throw new ArgumentNullException("key");
    }

    if (!encoded) {
        svc = new KeyToPropertySetService(key);
        props = svc.query();
        if (props != null) {
            return props;
        }
    }

    if (key instanceof PublicKey) {
        keyType = KeyRep.Type.PUBLIC;
    } else if (key instanceof PrivateKey) {
        keyType = KeyRep.Type.PRIVATE;
    } else if (key instanceof SecretKey) {
        keyType = KeyRep.Type.SECRET;
    } else {
        throw new InvalidCastException(key.getClass().getName(), KeyRep.Type.class.getName());
    }

    data = key.getEncoded();
    if (data == null) {
        throw new SecurityException(res.getEncodedFormatNotSupportedException());
    }

    props = new Properties();
    if (keyType == KeyRep.Type.SECRET) {
        props.setProperty(CryptoUtils.PROP_KEYFACTORY, RawKeyFactory.class.getName());
    } else {
        props.setProperty(CryptoUtils.PROP_KEYFACTORY, EncodedKeyFactory.class.getName());
        props.setProperty(EncodedKeyFactory.PROP_KEYTYPE, keyType.name());
    }

    props.setProperty(RawKeyFactory.PROP_ALGORITHM, key.getAlgorithm());
    props.setProperty(RawKeyFactory.PROP_DATA, Base64.encodeBase64String(data));

    return props;
}

From source file:io.jsonwebtoken.impl.DefaultJwtParser.java

@Override
public Jwt parse(String jwt) throws ExpiredJwtException, MalformedJwtException, SignatureException {

    Assert.hasText(jwt, "JWT String argument cannot be null or empty.");

    String base64UrlEncodedHeader = null;
    String base64UrlEncodedPayload = null;
    String base64UrlEncodedDigest = null;

    int delimiterCount = 0;

    StringBuilder sb = new StringBuilder(128);

    for (char c : jwt.toCharArray()) {

        if (c == SEPARATOR_CHAR) {

            String token = Strings.clean(sb.toString());

            if (delimiterCount == 0) {
                base64UrlEncodedHeader = token;
            } else if (delimiterCount == 1) {
                base64UrlEncodedPayload = token;
            }/*from w  w w. j  a v  a2s.c om*/

            delimiterCount++;
            sb = new StringBuilder(128);
        } else {
            sb.append(c);
        }
    }

    if (delimiterCount != 2) {
        String msg = "JWT strings must contain exactly 2 period characters. Found: " + delimiterCount;
        throw new MalformedJwtException(msg);
    }
    if (sb.length() > 0) {
        base64UrlEncodedDigest = sb.toString();
    }

    if (base64UrlEncodedPayload == null) {
        throw new MalformedJwtException("JWT string '" + jwt + "' is missing a body/payload.");
    }

    // =============== Header =================
    Header header = null;

    CompressionCodec compressionCodec = null;

    if (base64UrlEncodedHeader != null) {
        String origValue = TextCodec.BASE64URL.decodeToString(base64UrlEncodedHeader);
        Map<String, Object> m = readValue(origValue);

        if (base64UrlEncodedDigest != null) {
            header = new DefaultJwsHeader(m);
        } else {
            header = new DefaultHeader(m);
        }

        compressionCodec = compressionCodecResolver.resolveCompressionCodec(header);
    }

    // =============== Body =================
    String payload;
    if (compressionCodec != null) {
        byte[] decompressed = compressionCodec.decompress(TextCodec.BASE64URL.decode(base64UrlEncodedPayload));
        payload = new String(decompressed, Strings.UTF_8);
    } else {
        payload = TextCodec.BASE64URL.decodeToString(base64UrlEncodedPayload);
    }

    Claims claims = null;

    if (payload.charAt(0) == '{' && payload.charAt(payload.length() - 1) == '}') { //likely to be json, parse it:
        Map<String, Object> claimsMap = readValue(payload);
        claims = new DefaultClaims(claimsMap);
    }

    // =============== Signature =================
    if (base64UrlEncodedDigest != null) { //it is signed - validate the signature

        JwsHeader jwsHeader = (JwsHeader) header;

        SignatureAlgorithm algorithm = null;

        if (header != null) {
            String alg = jwsHeader.getAlgorithm();
            if (Strings.hasText(alg)) {
                algorithm = SignatureAlgorithm.forName(alg);
            }
        }

        if (algorithm == null || algorithm == SignatureAlgorithm.NONE) {
            //it is plaintext, but it has a signature.  This is invalid:
            String msg = "JWT string has a digest/signature, but the header does not reference a valid signature "
                    + "algorithm.";
            throw new MalformedJwtException(msg);
        }

        if (key != null && keyBytes != null) {
            throw new IllegalStateException(
                    "A key object and key bytes cannot both be specified. Choose either.");
        } else if ((key != null || keyBytes != null) && signingKeyResolver != null) {
            String object = key != null ? "a key object" : "key bytes";
            throw new IllegalStateException(
                    "A signing key resolver and " + object + " cannot both be specified. Choose either.");
        }

        //digitally signed, let's assert the signature:
        Key key = this.key;

        if (key == null) { //fall back to keyBytes

            byte[] keyBytes = this.keyBytes;

            if (Objects.isEmpty(keyBytes) && signingKeyResolver != null) { //use the signingKeyResolver
                if (claims != null) {
                    key = signingKeyResolver.resolveSigningKey(jwsHeader, claims);
                } else {
                    key = signingKeyResolver.resolveSigningKey(jwsHeader, payload);
                }
            }

            if (!Objects.isEmpty(keyBytes)) {

                Assert.isTrue(!algorithm.isRsa(),
                        "Key bytes cannot be specified for RSA signatures.  Please specify a PublicKey or PrivateKey instance.");

                key = new SecretKeySpec(keyBytes, algorithm.getJcaName());
            }
        }

        Assert.notNull(key, "A signing key must be specified if the specified JWT is digitally signed.");

        //re-create the jwt part without the signature.  This is what needs to be signed for verification:
        String jwtWithoutSignature = base64UrlEncodedHeader + SEPARATOR_CHAR + base64UrlEncodedPayload;

        JwtSignatureValidator validator;
        try {
            validator = createSignatureValidator(algorithm, key);
        } catch (IllegalArgumentException e) {
            String algName = algorithm.getValue();
            String msg = "The parsed JWT indicates it was signed with the " + algName + " signature "
                    + "algorithm, but the specified signing key of type " + key.getClass().getName()
                    + " may not be used to validate " + algName + " signatures.  Because the specified "
                    + "signing key reflects a specific and expected algorithm, and the JWT does not reflect "
                    + "this algorithm, it is likely that the JWT was not expected and therefore should not be "
                    + "trusted.  Another possibility is that the parser was configured with the incorrect "
                    + "signing key, but this cannot be assumed for security reasons.";
            throw new UnsupportedJwtException(msg, e);
        }

        if (!validator.isValid(jwtWithoutSignature, base64UrlEncodedDigest)) {
            String msg = "JWT signature does not match locally computed signature. JWT validity cannot be "
                    + "asserted and should not be trusted.";
            throw new SignatureException(msg);
        }
    }

    //since 0.3:
    if (claims != null) {

        SimpleDateFormat sdf;

        final Date now = this.clock.now();

        //https://tools.ietf.org/html/draft-ietf-oauth-json-web-token-30#section-4.1.4
        //token MUST NOT be accepted on or after any specified exp time:
        Date exp = claims.getExpiration();
        if (exp != null) {

            if (now.equals(exp) || now.after(exp)) {
                sdf = new SimpleDateFormat(ISO_8601_FORMAT);
                String expVal = sdf.format(exp);
                String nowVal = sdf.format(now);

                String msg = "JWT expired at " + expVal + ". Current time: " + nowVal;
                throw new ExpiredJwtException(header, claims, msg);
            }
        }

        //https://tools.ietf.org/html/draft-ietf-oauth-json-web-token-30#section-4.1.5
        //token MUST NOT be accepted before any specified nbf time:
        Date nbf = claims.getNotBefore();
        if (nbf != null) {

            if (now.before(nbf)) {
                sdf = new SimpleDateFormat(ISO_8601_FORMAT);
                String nbfVal = sdf.format(nbf);
                String nowVal = sdf.format(now);

                String msg = "JWT must not be accepted before " + nbfVal + ". Current time: " + nowVal;
                throw new PrematureJwtException(header, claims, msg);
            }
        }

        validateExpectedClaims(header, claims);
    }

    Object body = claims != null ? claims : payload;

    if (base64UrlEncodedDigest != null) {
        return new DefaultJws<Object>((JwsHeader) header, body, base64UrlEncodedDigest);
    } else {
        return new DefaultJwt<Object>(header, body);
    }
}

From source file:org.apache.felix.deploymentadmin.itest.util.DPSigner.java

public static String getSignatureAlgorithm(Key key) {
    if (key instanceof RSAKey) {
        return "SHA256withRSA";
    } else if (key instanceof DSAKey) {
        return "SHA1withDSA";
    } else if (key instanceof ECKey) {
        return "SHA256withECDSA";
    } else {/*www. ja v a 2 s . co m*/
        throw new IllegalArgumentException("Invalid/unsupported key: " + key.getClass().getName());
    }
}

From source file:org.apache.felix.deploymentadmin.itest.util.DPSigner.java

private static String getBlockFileExtension(Key key) {
    if (key instanceof RSAKey) {
        return ".RSA";
    } else if (key instanceof DSAKey) {
        return ".DSA";
    } else if (key instanceof ECKey) {
        return ".EC";
    } else {/*from ww w . j  a  v a 2 s . c  om*/
        throw new IllegalArgumentException("Invalid/unsupported key: " + key.getClass().getName());
    }
}

From source file:org.apache.xml.security.algorithms.implementations.IntegrityHmac.java

/**
 * Proxy method for {@link java.security.Signature#initVerify(java.security.PublicKey)}
 * which is executed on the internal {@link java.security.Signature} object.
 *
 * @param secretKey// w  w w  .  java  2  s. c om
 * @throws XMLSignatureException
 */
protected void engineInitVerify(Key secretKey) throws XMLSignatureException {
    if (!(secretKey instanceof SecretKey)) {
        String supplied = secretKey.getClass().getName();
        String needed = SecretKey.class.getName();
        Object exArgs[] = { supplied, needed };

        throw new XMLSignatureException("algorithms.WrongKeyForThisOperation", exArgs);
    }

    try {
        this.macAlgorithm.init(secretKey);
    } catch (InvalidKeyException ex) {
        // reinstantiate Mac object to work around bug in JDK
        // see: http://bugs.sun.com/view_bug.do?bug_id=4953555
        Mac mac = this.macAlgorithm;
        try {
            this.macAlgorithm = Mac.getInstance(macAlgorithm.getAlgorithm());
        } catch (Exception e) {
            // this shouldn't occur, but if it does, restore previous Mac
            if (log.isDebugEnabled()) {
                log.debug("Exception when reinstantiating Mac:" + e);
            }
            this.macAlgorithm = mac;
        }
        throw new XMLSignatureException("empty", ex);
    }
}