Example usage for java.security Signature getInstance

List of usage examples for java.security Signature getInstance

Introduction

In this page you can find the example usage for java.security Signature getInstance.

Prototype

public static Signature getInstance(String algorithm) throws NoSuchAlgorithmException 

Source Link

Document

Returns a Signature object that implements the specified signature algorithm.

Usage

From source file:RGSDigestTools.SignatureTool.java

public boolean verify(String dataToVerify, byte[] signature)
        throws NoSuchAlgorithmException, SignatureException, InvalidKeyException, UnsupportedEncodingException {
    Signature signer = Signature.getInstance(signAlg);
    signer.initVerify(verifyKey);//from w w  w  .  j av  a  2  s.  co m
    signer.update(dataToVerify.getBytes());
    return signer.verify(signature);

}

From source file:org.talend.components.common.oauth.X509Key.java

/**
 * sign data with private key using algo
 *///from   w  w w .  ja v a  2s  .c o  m
public byte[] sign(String data, Algorithm algo) {

    try {
        // Sign the JWT Header + "." + JWT Claims Object
        Signature signature = Signature.getInstance(algo.name());
        signature.initSign(privateKey);
        signature.update(data.getBytes(charSetUtf8));
        return signature.sign();

    } catch (IOException | NoSuchAlgorithmException | InvalidKeyException | SignatureException e) {
        throw new RuntimeException(e);
    }
}

From source file:cl.niclabs.tscrypto.common.encryption.KeyChain.java

public byte[] sign(String rsaKeyAlias, byte[] data) throws UnrecoverableEntryException,
        NoSuchAlgorithmException, KeyStoreException, InvalidKeyException, SignatureException {
    Signature sign = Signature.getInstance("SHA1WithRsa");
    sign.initSign(getPrivateKey(rsaKeyAlias));
    sign.update(data);/*from w  w w . java2 s  .  c om*/

    byte[] signature = sign.sign();
    return signature;
}

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

/**
 * Constructor SignatureRSA//from  ww  w . java  2  s  . c  om
 *
 * @throws XMLSignatureException
 */
public SignatureBaseRSA() throws XMLSignatureException {
    String algorithmID = JCEMapper.translateURItoJCEID(this.engineGetURI());

    if (log.isDebugEnabled()) {
        log.debug("Created SignatureRSA using " + algorithmID);
    }
    String provider = JCEMapper.getProviderId();
    try {
        if (provider == null) {
            this.signatureAlgorithm = Signature.getInstance(algorithmID);
        } else {
            this.signatureAlgorithm = Signature.getInstance(algorithmID, provider);
        }
    } catch (java.security.NoSuchAlgorithmException ex) {
        Object[] exArgs = { algorithmID, ex.getLocalizedMessage() };

        throw new XMLSignatureException("algorithms.NoSuchAlgorithm", exArgs);
    } catch (NoSuchProviderException ex) {
        Object[] exArgs = { algorithmID, ex.getLocalizedMessage() };

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

From source file:org.dasein.security.joyent.SignatureHttpAuth.java

@Override
public void addPreemptiveAuth(@Nonnull HttpRequest request) throws CloudException, InternalException {
    if (provider.getContext() == null) {
        throw new CloudException("No context was defined for this request");
    }// w w  w .  j  a v a2  s  . com
    Date date = Calendar.getInstance(TimeZone.getTimeZone("UTC")).getTime();
    String now = RFC1123_DATE_FORMAT.format(date);
    request.setHeader("Date", now);
    try {
        Security.addProvider(new BouncyCastleProvider());
        Signature signature = Signature.getInstance(SIGN_ALGORITHM);

        List<ContextRequirements.Field> fields = provider.getContextRequirements().getConfigurableValues();
        String keyName = "";
        String privateKey = "";
        char[] keyPassword = null;
        for (ContextRequirements.Field f : fields) {
            if (f.type.equals(ContextRequirements.FieldType.KEYPAIR)) {
                byte[][] keyPair = (byte[][]) provider.getContext().getConfigurationValue(f);
                keyName = new String(keyPair[0], "utf-8");
                privateKey = new String(keyPair[1], "utf-8");
            } else if (f.type.equals(ContextRequirements.FieldType.PASSWORD)) {
                byte[] password = (byte[]) provider.getContext().getConfigurationValue(f);
                if (password != null) {
                    keyPassword = new String(password, "utf-8").toCharArray();
                }
            }
        }

        signature.initSign(getKeyPair(privateKey, keyPassword).getPrivate());
        String signingString = String.format(AUTH_SIGN, now);
        signature.update(signingString.getBytes("UTF-8"));
        byte[] signedDate = signature.sign();
        byte[] encodedSignedDate = Base64.encode(signedDate);

        request.addHeader("Authorization", String.format(AUTH_HEADER, provider.getContext().getAccountNumber(),
                keyName, new String(encodedSignedDate)));

    } catch (NoSuchAlgorithmException e) {
        throw new InternalException(e);
    } catch (UnsupportedEncodingException e) {
        throw new InternalException(e);
    } catch (SignatureException e) {
        throw new InternalException(e);
    } catch (InvalidKeyException e) {
        throw new InternalException(e);
    } catch (IOException e) {
        throw new InternalException(e);
    }
}

From source file:org.diorite.impl.auth.properties.PropertyImpl.java

@Override
public boolean isSignatureValid(final PublicKey publicKey) {
    try {/*from w  w w.  j a va 2s.c o m*/
        final Signature signature = Signature.getInstance("SHA1withRSA");
        signature.initVerify(publicKey);
        signature.update(this.value.getBytes());
        return signature.verify(Base64.decodeBase64(this.signature));
    } catch (final NoSuchAlgorithmException | SignatureException | InvalidKeyException e) {
        e.printStackTrace();
    }
    return false;
}

From source file:com.streamsets.lib.security.util.DataSignature.java

public Signer getSigner(final PrivateKey privateKey) {
    return new Signer() {
        @Override/*from  ww w  . java 2 s  .c om*/
        public byte[] sign(byte[] data) throws GeneralSecurityException {
            Signature signer = Signature.getInstance("SHA1withDSA");
            signer.initSign(privateKey);
            signer.update(data);
            return signer.sign();
        }
    };
}

From source file:ai.susi.tools.JsonSignature.java

/**
 * Verfies if the signature of a JSONObject is valid
 * @param obj the JSONObject// w  w w . j a v a 2 s  .  c om
 * @param key the public key of the signature issuer
 * @return true if the signature is valid
 * @throws SignatureException if the JSONObject does not have a signature or something with the JSONObject is bogus
 * @throws InvalidKeyException if the key is not valid (for example not RSA)
 */
public static boolean verify(JSONObject obj, PublicKey key) throws SignatureException, InvalidKeyException {

    if (!obj.has(signatureString))
        throw new SignatureException("No signature supplied");

    Signature signature;
    try {
        signature = Signature.getInstance("SHA256withRSA");
    } catch (NoSuchAlgorithmException e) {
        return false; //does not happen
    }

    String sigString = obj.getString(signatureString);
    byte[] sig = Base64.getDecoder().decode(sigString);
    obj.remove(signatureString);

    signature.initVerify(key);
    signature.update(obj.toString().getBytes(StandardCharsets.UTF_8));
    boolean res = signature.verify(sig);

    obj.put(signatureString, sigString);

    return res;
}

From source file:org.orbeon.oxf.processor.SignatureVerifierProcessor.java

public ProcessorOutput createOutput(String name) {
    final ProcessorOutput output = new ProcessorOutputImpl(SignatureVerifierProcessor.this, name) {
        public void readImpl(PipelineContext context, final XMLReceiver xmlReceiver) {
            try {
                final Document pubDoc = readCacheInputAsDOM4J(context, INPUT_PUBLIC_KEY);
                final String pubString = XPathUtils.selectStringValueNormalize(pubDoc, "/public-key");
                final byte[] pubBytes = Base64.decode(pubString);
                final X509EncodedKeySpec pubKeySpec = new X509EncodedKeySpec(pubBytes);
                final KeyFactory keyFactory = KeyFactory.getInstance("DSA");
                final PublicKey pubKey = keyFactory.generatePublic(pubKeySpec);

                final Signature dsa = Signature.getInstance("SHA1withDSA");
                dsa.initVerify(pubKey);//from   w  w  w  . jav  a 2 s.  c  o m

                final Document data = readInputAsDOM4J(context, INPUT_DATA);
                final Node sigDataNode = data.selectSingleNode("/signed-data/data/*");
                final String sig = StringUtils
                        .trimToEmpty(XPathUtils.selectStringValue(data, "/signed-data/signature"));

                sigDataNode.detach();
                final Document sigData = new NonLazyUserDataDocument();
                sigData.add(sigDataNode);

                dsa.update(Dom4jUtils.domToString(sigData).getBytes("utf-8"));

                // Verify signature and throw in case of failure
                try {
                    if (!dsa.verify(Base64.decode(sig)))
                        throw new OXFException("Signature verification failed");
                } catch (SignatureException e) {
                    throw e;
                } catch (Exception e) {
                    // A number of things can fail above, including Base64 decoding
                    // NOTE: We don't pas the cause so that we can match on SignatureException as root Exception
                    throw new SignatureException("Signature verification failed");
                }

                // Signature verification passed
                final LocationSAXWriter saw = new LocationSAXWriter();
                saw.setContentHandler(xmlReceiver);
                saw.write(sigData);
            } catch (Exception e) {
                throw new OXFException(e);
            }
        }
    };
    addOutput(name, output);
    return output;
}

From source file:com.easarrive.aws.plugins.common.util.SNSUtil.java

public static boolean isMessageSignatureValid(SNSMessage msg) {
    try {//from   w ww.j a  v a  2  s. c  om
        URL url = new URL(msg.getSigningCertURL());
        InputStream inStream = url.openStream();
        CertificateFactory cf = CertificateFactory.getInstance("X.509");
        X509Certificate cert = (X509Certificate) cf.generateCertificate(inStream);
        inStream.close();

        Signature sig = Signature.getInstance("SHA1withRSA");
        sig.initVerify(cert.getPublicKey());
        sig.update(getMessageBytesToSign(msg));
        return sig.verify(Base64.decodeBase64(msg.getSignature()));
    } catch (Exception e) {
        throw new SecurityException("Verify method failed.", e);
    }
}