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:hudson.cli.Connection.java

/**
 * Used in conjunction with {@link #verifyIdentity(byte[])} to prove
 * that we actually own the private key of the given key pair.
 *///from  w  w w  .  j a  v a2 s. co m
public void proveIdentity(byte[] sharedSecret, KeyPair key) throws IOException, GeneralSecurityException {
    String algorithm = detectKeyAlgorithm(key);
    writeUTF(algorithm);
    writeKey(key.getPublic());

    Signature sig = Signature.getInstance("SHA1with" + algorithm);
    sig.initSign(key.getPrivate());
    sig.update(key.getPublic().getEncoded());
    sig.update(sharedSecret);
    writeObject(sig.sign());
}

From source file:mx.bigdata.sat.cfdi.CFDv33.java

public void verificar(InputStream in) throws Exception {
    String certStr = document.getCertificado();
    Base64 b64 = new Base64();
    byte[] cbs = b64.decode(certStr);

    X509Certificate cert = KeyLoaderFactory
            .createInstance(KeyLoaderEnumeration.PUBLIC_KEY_LOADER, new ByteArrayInputStream(cbs)).getKey();

    String sigStr = document.getSello();
    byte[] signature = b64.decode(sigStr);
    byte[] bytes = getOriginalBytes(in);
    Signature sig = Signature.getInstance("SHA256withRSA");
    sig.initVerify(cert);/*from   ww  w  .j a  va2 s. com*/
    sig.update(bytes);
    boolean bool = sig.verify(signature);
    if (!bool) {
        throw new Exception("Invalid signature.");
    }
}

From source file:com.torresbueno.RSAEncryptionDecryptionUtil.java

/**
 * Sign a message./*from   ww  w. j  a  va2 s .  c  o m*/
 * @param data
 * @param pk
 * @return
 */
public byte[] sign(byte[] data, PrivateKey pk) throws Exception {
    Signature sig = Signature.getInstance("MD5WithRSA");
    sig.initSign(pk);
    sig.update(data);
    byte[] signatureBytes = sig.sign();
    return signatureBytes;
}

From source file:com.cws.esolutions.security.processors.impl.FileSecurityProcessorImpl.java

/**
 * @see com.cws.esolutions.security.processors.interfaces.IFileSecurityProcessor#verifyFile(com.cws.esolutions.security.processors.dto.FileSecurityRequest)
 *//*from w  ww.ja  v a 2s .  c om*/
public synchronized FileSecurityResponse verifyFile(final FileSecurityRequest request)
        throws FileSecurityException {
    final String methodName = IFileSecurityProcessor.CNAME
            + "#verifyFile(final FileSecurityRequest request) throws FileSecurityException";

    if (DEBUG) {
        DEBUGGER.debug(methodName);
        DEBUGGER.debug("FileSecurityRequest: {}", request);
    }

    FileSecurityResponse response = new FileSecurityResponse();

    final RequestHostInfo reqInfo = request.getHostInfo();
    final UserAccount userAccount = request.getUserAccount();
    final KeyManager keyManager = KeyManagementFactory.getKeyManager(keyConfig.getKeyManager());

    if (DEBUG) {
        DEBUGGER.debug("RequestHostInfo: {}", reqInfo);
        DEBUGGER.debug("UserAccount", userAccount);
        DEBUGGER.debug("KeyManager: {}", keyManager);
    }

    try {
        KeyPair keyPair = keyManager.returnKeys(userAccount.getGuid());

        if (keyPair != null) {
            // read in the file signature
            byte[] sigToVerify = IOUtils.toByteArray(new FileInputStream(request.getSignedFile()));

            if (DEBUG) {
                DEBUGGER.debug("sigToVerify: {}", sigToVerify);
            }

            Signature signature = Signature.getInstance(fileSecurityConfig.getSignatureAlgorithm());
            signature.initVerify(keyPair.getPublic());
            signature.update(IOUtils.toByteArray(new FileInputStream(request.getUnsignedFile())));

            if (DEBUG) {
                DEBUGGER.debug("Signature: {}", signature);
            }

            response.setRequestStatus(SecurityRequestStatus.SUCCESS);
            response.setIsSignatureValid(signature.verify(sigToVerify));
        } else {
            response.setRequestStatus(SecurityRequestStatus.FAILURE);
        }
    } catch (NoSuchAlgorithmException nsax) {
        ERROR_RECORDER.error(nsax.getMessage(), nsax);

        throw new FileSecurityException(nsax.getMessage(), nsax);
    } catch (FileNotFoundException fnfx) {
        ERROR_RECORDER.error(fnfx.getMessage(), fnfx);

        throw new FileSecurityException(fnfx.getMessage(), fnfx);
    } catch (InvalidKeyException ikx) {
        ERROR_RECORDER.error(ikx.getMessage(), ikx);

        throw new FileSecurityException(ikx.getMessage(), ikx);
    } catch (SignatureException sx) {
        ERROR_RECORDER.error(sx.getMessage(), sx);

        throw new FileSecurityException(sx.getMessage(), sx);
    } catch (IOException iox) {
        ERROR_RECORDER.error(iox.getMessage(), iox);

        throw new FileSecurityException(iox.getMessage(), iox);
    } catch (KeyManagementException kmx) {
        ERROR_RECORDER.error(kmx.getMessage(), kmx);

        throw new FileSecurityException(kmx.getMessage(), kmx);
    } finally {
        // audit
        try {
            AuditEntry auditEntry = new AuditEntry();
            auditEntry.setHostInfo(reqInfo);
            auditEntry.setAuditType(AuditType.VERIFYFILE);
            auditEntry.setUserAccount(userAccount);
            auditEntry.setAuthorized(Boolean.TRUE);
            auditEntry.setApplicationId(request.getApplicationId());
            auditEntry.setApplicationName(request.getAppName());

            if (DEBUG) {
                DEBUGGER.debug("AuditEntry: {}", auditEntry);
            }

            AuditRequest auditRequest = new AuditRequest();
            auditRequest.setAuditEntry(auditEntry);

            if (DEBUG) {
                DEBUGGER.debug("AuditRequest: {}", auditRequest);
            }

            auditor.auditRequest(auditRequest);
        } catch (AuditServiceException asx) {
            ERROR_RECORDER.error(asx.getMessage(), asx);
        }
    }

    return response;
}

From source file:org.bankinterface.util.Utils.java

/**
 * SHA1withRSA???/* ww  w  . ja  v  a2s . c o m*/
 * 
 * @param sourceData
 * @param signData
 * @param certFilePath
 * @param publicKeyAlias
 * @return
 * @throws NoSuchAlgorithmException
 * @throws InvalidKeyException
 * @throws UnsupportedEncodingException
 * @throws SignatureException
 */
public static boolean verifySHA1withRSA(String sourceData, String signData, String charset, String certFilePath,
        String publicKeyAlias)
        throws NoSuchAlgorithmException, InvalidKeyException, SignatureException, UnsupportedEncodingException {
    PublicKey publicKey = KeyStoreUtil.getPublicKey(certFilePath, publicKeyAlias);
    Signature signature = Signature.getInstance(ALGORITHM_SHA1WITHRSA);
    signature.initVerify(publicKey);
    signature.update(getBytes(sourceData, charset));
    return signature.verify(getBytes(signData, charset));
}

From source file:com.soomla.billing.Security.java

/**
 * Verifies that the signature from the server matches the computed
 * signature on the data.  Returns true if the data is correctly signed.
 *
 * @param publicKey public key associated with the developer account
 * @param signedData signed data from server
 * @param signature server signature//from  w  ww  .  ja  v a 2s .  co m
 * @return true if the data and signature match
 */
public static boolean verify(PublicKey publicKey, String signedData, String signature) {
    StoreUtils.LogDebug(TAG, "signature: " + signature);
    Signature sig;
    try {
        sig = Signature.getInstance(SIGNATURE_ALGORITHM);
        sig.initVerify(publicKey);
        sig.update(signedData.getBytes());
        if (!sig.verify(Base64.decode(signature))) {
            StoreUtils.LogError(TAG, "Signature verification failed.");
            return false;
        }
        return true;
    } catch (NoSuchAlgorithmException e) {
        StoreUtils.LogError(TAG, "NoSuchAlgorithmException.");
    } catch (InvalidKeyException e) {
        StoreUtils.LogError(TAG, "Invalid key specification.");
    } catch (SignatureException e) {
        StoreUtils.LogError(TAG, "Signature exception.");
    } catch (Base64DecoderException e) {
        StoreUtils.LogError(TAG, "Base64 decoding failed.");
    }
    return false;
}

From source file:libcore.tzdata.update_test_app.installupdatetestapp.MainActivity.java

private static String createSignature(File contentFile, String version, String requiredHash) throws Exception {
    byte[] contentBytes = readBytes(contentFile);
    Signature signer = Signature.getInstance("SHA512withRSA");
    signer.initSign(createKey());/*from   w ww  .j  av  a2 s. c  o  m*/
    signer.update(contentBytes);
    signer.update(version.trim().getBytes());
    signer.update(requiredHash.getBytes());
    return new String(Base64.encode(signer.sign(), Base64.DEFAULT));
}

From source file:com.subgraph.vega.internal.http.proxy.ssl.CertificateCreator.java

private X500Signer createCertificateSigner(X500Principal issuer, PrivateKey issuerPrivate)
        throws IOException, GeneralSecurityException {
    final X500Name issuerName = new X500Name(issuer.getName());
    final Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM);
    signature.initSign(issuerPrivate);//  w  ww .  j ava2s  .c  o m
    return new X500Signer(signature, issuerName);
}

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

/** @inheritDoc */
protected void engineInitVerify(Key publicKey) throws XMLSignatureException {

    if (!(publicKey instanceof PublicKey)) {
        String supplied = publicKey.getClass().getName();
        String needed = PublicKey.class.getName();
        Object exArgs[] = { supplied, needed };

        throw new XMLSignatureException("algorithms.WrongKeyForThisOperation", exArgs);
    }//from w  w w.java2  s  .  c  om

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

From source file:org.apache.jcp.xml.dsig.internal.dom.DOMSignatureMethod.java

byte[] sign(Key key, SignedInfo si, XMLSignContext context) throws InvalidKeyException, XMLSignatureException {
    if (key == null || si == null) {
        throw new NullPointerException();
    }/*from   w w  w  .  j a v a 2  s.  c o  m*/

    if (!(key instanceof PrivateKey)) {
        throw new InvalidKeyException("key must be PrivateKey");
    }
    if (signature == null) {
        try {
            Provider p = (Provider) context.getProperty("org.jcp.xml.dsig.internal.dom.SignatureProvider");
            signature = (p == null) ? Signature.getInstance(getJCAAlgorithm())
                    : Signature.getInstance(getJCAAlgorithm(), p);
        } catch (NoSuchAlgorithmException nsae) {
            throw new XMLSignatureException(nsae);
        }
    }
    signature.initSign((PrivateKey) key);
    if (log.isDebugEnabled()) {
        log.debug("Signature provider:" + signature.getProvider());
        log.debug("Signing with key: " + key);
    }

    ((DOMSignedInfo) si).canonicalize(context, new SignerOutputStream(signature));

    try {
        Type type = getAlgorithmType();
        if (type == Type.DSA) {
            return convertASN1toXMLDSIG(signature.sign());
        } else if (type == Type.ECDSA) {
            return SignatureECDSA.convertASN1toXMLDSIG(signature.sign());
        } else {
            return signature.sign();
        }
    } catch (SignatureException se) {
        throw new XMLSignatureException(se);
    } catch (IOException ioe) {
        throw new XMLSignatureException(ioe);
    }
}