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, Provider provider) throws NoSuchAlgorithmException 

Source Link

Document

Returns a Signature object that implements the specified signature algorithm.

Usage

From source file:org.eclipse.licensing.base.LicenseKey.java

public boolean isAuthentic(PublicKey publicKey) {
    try {//  w w w. j a va  2 s. c  om
        Signature signature = Signature.getInstance("SHA1withDSA", "SUN");
        signature.initVerify(publicKey);

        String[] propKeys = properties.keySet().toArray(new String[0]);
        Arrays.sort(propKeys);
        for (String propKey : propKeys) {
            if (!SIGNATURE.equals(propKey)) {
                String propValue = getProperty(propKey);
                signature.update(propValue.getBytes("UTF-8"));
            }
        }

        byte[] encodedSignature = getSignature();
        if (encodedSignature == null) {
            return false;
        }

        return signature.verify(getSignature());
    } catch (GeneralSecurityException | UnsupportedEncodingException e) {
        e.printStackTrace();
        return false;
    }
}

From source file:com.alliander.osgp.oslp.OslpUtils.java

/**
 * Validate the signature against the message.
 *
 * @param message//from   ww w  .  j  a  v  a 2s .  c o  m
 *            message to validate
 * @param securityKey
 *            signature to validate
 * @param publicKey
 *            public key to use for decryption of signature
 * @param signature
 *            signature algorithm to use
 * @param provider
 *            provider which supplies algorithm
 * @return true when signature is correct, false when it's not
 * @throws GeneralSecurityException
 *             when configuration is incorrect.
 */
public static boolean validateSignature(final byte[] message, final byte[] securityKey,
        final PublicKey publicKey, final String signature, final String provider)
        throws GeneralSecurityException {

    // Use fallback to plain SHA512 hash, which is encrypted with RSA
    // instead of real RSA signature
    if (signature.equalsIgnoreCase(FALLBACK_SIGNATURE)) {
        return validateEncryptedHash(message, securityKey, publicKey);
    }

    final Signature signatureBuilder = Signature.getInstance(signature, provider);
    signatureBuilder.initVerify(publicKey);
    signatureBuilder.update(message);

    return signatureBuilder.verify(securityKey);
}

From source file:ee.ria.xroad.common.request.ManagementRequestHandler.java

private static boolean verifySignature(X509Certificate cert, byte[] signatureData, String signatureAlgorithmId,
        byte[] dataToVerify) throws Exception {
    try {//w w  w.jav a2 s. co m
        Signature signature = Signature.getInstance(signatureAlgorithmId, "BC");
        signature.initVerify(cert.getPublicKey());
        signature.update(dataToVerify);

        return signature.verify(signatureData);
    } catch (Exception e) {
        log.error("Failed to verify signature", e);

        throw translateException(e);
    }
}

From source file:im.whistle.crypt.Crypt.java

/**
 * Encrypts a message./*  w ww . j a va  2  s. co m*/
 * @param args Arguments: data, publicKey[, privateKey]
 * @param callback Callback
 */
public static void encrypt(JSONArray args, AsyncCallback<JSONArray> callback) {
    try {
        PRNGProvider.init(); // Ensure OpenSSL fix

        // Get the arguments
        String data = args.getString(0);
        String pub = args.getString(1);
        String priv = null;
        if (args.length() == 3) {
            priv = args.getString(2);
        }
        String sig = null;

        // Convert everything into byte arrays
        byte[] dataRaw = data.getBytes("utf-8");
        byte[] pubRaw = Base64.decode(stripKey(pub), Base64.DEFAULT);

        // Generate random AES key and IV
        byte[] aesKey = new byte[AES_BYTES];
        new SecureRandom().nextBytes(aesKey);
        byte[] aesIv = new byte[16]; // Block size
        new SecureRandom().nextBytes(aesIv);
        Cipher c = Cipher.getInstance("AES/CBC/PKCS7Padding", "BC");
        c.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(aesKey, "AES"), new IvParameterSpec(aesIv));

        // Encrypt data with AES
        byte[] encData = c.doFinal(dataRaw);

        // Encrypt aes data with RSA
        X509EncodedKeySpec publicKeySpec = new X509EncodedKeySpec(pubRaw);
        KeyFactory kf = KeyFactory.getInstance("RSA", "BC");
        c = Cipher.getInstance("RSA/None/OAEPWithSHA-1AndMGF1Padding", "BC");
        c.init(Cipher.ENCRYPT_MODE, kf.generatePublic(publicKeySpec));
        c.update(aesKey);
        c.update(aesIv);
        byte[] encKey = c.doFinal();

        // Concatenate and transform
        byte[] encRaw = new byte[encKey.length + encData.length];
        System.arraycopy(encKey, 0, encRaw, 0, encKey.length);
        System.arraycopy(encData, 0, encRaw, encKey.length, encData.length);
        encKey = null;
        encData = null;
        String enc = new String(Base64.encode(encRaw /* needed for sign */, Base64.NO_WRAP), "utf-8");

        // Sign
        if (priv != null) {
            // Fail on error (no try-catch)
            byte[] privRaw = Base64.decode(stripKey(priv), Base64.DEFAULT);
            PKCS8EncodedKeySpec privateKeySpec = new PKCS8EncodedKeySpec(privRaw);
            Signature s = Signature.getInstance("SHA1withRSA", "BC");
            s.initSign(kf.generatePrivate(privateKeySpec));
            s.update(encRaw);
            sig = new String(Base64.encode(s.sign(), Base64.NO_WRAP), "utf-8");
        }

        JSONArray res = new JSONArray();
        res.put(enc);
        res.put(sig);
        callback.success(res);
    } catch (Exception ex) {
        Log.w("whistle", "Encrypt error: " + ex.getMessage(), ex);
        callback.error(ex);
    }
}

From source file:acp.sdk.SecureUtil.java

/**
 * ??//from  w  w  w .  j a va 2 s .  c  om
 * 
 * @param privateKey
 *            ?
 * @param data
 *            ???
 * @param signMethod
 *            ??
 * @return 
 * @throws Exception
 */
public static byte[] signBySoft(PrivateKey privateKey, byte[] data) throws Exception {
    byte[] result = null;
    Signature st = Signature.getInstance(BC_PROV_ALGORITHM_SHA1RSA, "BC");
    st.initSign(privateKey);
    st.update(data);
    result = st.sign();
    return result;
}

From source file:com.mycompany.bankinterface.crypto.Signer.java

public boolean isVerified(String clearText, String signature, String signerPublicKey) throws SignerException {

    boolean isVerified = false;

    byte[] signerPublicKeyBytes = Base64.decodeBase64(signerPublicKey);
    byte[] signatureAsBytes = Base64.decodeBase64(signature);

    X509EncodedKeySpec pubKeySpec = new X509EncodedKeySpec(signerPublicKeyBytes);
    KeyFactory keyFactory;//from  w w w .  j av  a2 s.  c  om

    try {
        keyFactory = KeyFactory.getInstance(PUBLIC_KEY_ALGORITHM, PROVIDER);
    } catch (NoSuchAlgorithmException | NoSuchProviderException ex) {
        throw new SignerException("Failed to create key factory", ex);
    }

    PublicKey pubKey;

    try {
        pubKey = keyFactory.generatePublic(pubKeySpec);
    } catch (InvalidKeySpecException ex) {
        throw new SignerException("Failed to create public key", ex);
    }

    Signature dsa;

    try {
        dsa = Signature.getInstance(SIGNER_ALGORITHM, PROVIDER);
    } catch (NoSuchAlgorithmException | NoSuchProviderException ex) {
        throw new SignerException("Could not get signing instance", ex);
    }

    try {
        dsa.initVerify(pubKey);
        dsa.update(clearText.getBytes());
        isVerified = dsa.verify(signatureAsBytes);

    } catch (InvalidKeyException | SignatureException ex) {
        throw new SignerException("Could not verify data", ex);
    }

    return isVerified;
}

From source file:be.e_contract.eid.applet.service.impl.handler.SignatureDataMessageHandler.java

@Override
public Object handleMessage(SignatureDataMessage message, Map<String, String> httpHeaders,
        HttpServletRequest request, HttpSession session) throws ServletException {
    byte[] signatureValue = message.signatureValue;
    List<X509Certificate> certificateChain = message.certificateChain;
    if (certificateChain.isEmpty()) {
        throw new ServletException("certificate chain is empty");
    }//  w w  w. j av a 2  s . c  o  m
    X509Certificate signingCertificate = certificateChain.get(0);
    if (null == signingCertificate) {
        throw new ServletException("non-repudiation certificate missing");
    }
    LOG.debug("non-repudiation signing certificate: " + signingCertificate.getSubjectX500Principal());
    PublicKey signingPublicKey = signingCertificate.getPublicKey();

    BeIDContextQualifier contextQualifier = new BeIDContextQualifier(request);

    /*
     * Verify the signature.
     */
    String digestAlgo = this.signatureState.getDigestAlgo();
    byte[] expectedDigestValue = this.signatureState.getDigestValue();
    if (digestAlgo.endsWith("-PSS")) {
        LOG.debug("verifying RSA/PSS signature");
        try {
            Signature signature = Signature.getInstance("RAWRSASSA-PSS", BouncyCastleProvider.PROVIDER_NAME);
            if ("SHA-256-PSS".equals(digestAlgo)) {
                LOG.debug("RSA/PSS SHA256");
                signature.setParameter(
                        new PSSParameterSpec("SHA-256", "MGF1", new MGF1ParameterSpec("SHA-256"), 32, 1));
            }
            signature.initVerify(signingPublicKey);
            signature.update(expectedDigestValue);
            boolean result = signature.verify(signatureValue);
            if (false == result) {
                SecurityAuditEvent securityAuditEvent = new SecurityAuditEvent(Incident.SIGNATURE,
                        signingCertificate, signatureValue);
                this.securityAuditEvent.select(contextQualifier).fire(securityAuditEvent);
                throw new SecurityException("signature incorrect");
            }
        } catch (Exception e) {
            LOG.debug("signature verification error: " + e.getMessage(), e);
            SecurityAuditEvent securityAuditEvent = new SecurityAuditEvent(Incident.SIGNATURE,
                    signingCertificate, signatureValue);
            this.securityAuditEvent.select(contextQualifier).fire(securityAuditEvent);
            throw new ServletException("signature verification error: " + e.getMessage(), e);
        }
    } else {
        try {
            Signature signature = Signature.getInstance("RawRSA", BouncyCastleProvider.PROVIDER_NAME);
            signature.initVerify(signingPublicKey);
            ByteArrayOutputStream digestInfo = new ByteArrayOutputStream();
            if ("SHA-1".equals(digestAlgo) || "SHA1".equals(digestAlgo)) {
                digestInfo.write(SHA1_DIGEST_INFO_PREFIX);
            } else if ("SHA-224".equals(digestAlgo)) {
                digestInfo.write(SHA224_DIGEST_INFO_PREFIX);
            } else if ("SHA-256".equals(digestAlgo)) {
                digestInfo.write(SHA256_DIGEST_INFO_PREFIX);
            } else if ("SHA-384".equals(digestAlgo)) {
                digestInfo.write(SHA384_DIGEST_INFO_PREFIX);
            } else if ("SHA-512".equals(digestAlgo)) {
                digestInfo.write(SHA512_DIGEST_INFO_PREFIX);
            } else if ("RIPEMD160".equals(digestAlgo)) {
                digestInfo.write(RIPEMD160_DIGEST_INFO_PREFIX);
            } else if ("RIPEMD128".equals(digestAlgo)) {
                digestInfo.write(RIPEMD128_DIGEST_INFO_PREFIX);
            } else if ("RIPEMD256".equals(digestAlgo)) {
                digestInfo.write(RIPEMD256_DIGEST_INFO_PREFIX);
            }
            digestInfo.write(expectedDigestValue);
            signature.update(digestInfo.toByteArray());
            boolean result = signature.verify(signatureValue);
            if (false == result) {
                SecurityAuditEvent securityAuditEvent = new SecurityAuditEvent(Incident.SIGNATURE,
                        signingCertificate, signatureValue);
                this.securityAuditEvent.select(contextQualifier).fire(securityAuditEvent);
                throw new SecurityException("signature incorrect");
            }
        } catch (Exception e) {
            LOG.debug("signature verification error: " + e.getMessage());
            SecurityAuditEvent securityAuditEvent = new SecurityAuditEvent(Incident.SIGNATURE,
                    signingCertificate, signatureValue);
            this.securityAuditEvent.select(contextQualifier).fire(securityAuditEvent);
            throw new ServletException("signature verification error: " + e.getMessage(), e);
        }
    }

    SignatureEvent signatureEvent = new SignatureEvent(signatureValue, certificateChain);
    try {
        this.signatureEvent.select(contextQualifier).fire(signatureEvent);
    } catch (ExpiredCertificateSecurityException e) {
        return new FinishedMessage(ErrorCode.CERTIFICATE_EXPIRED);
    } catch (RevokedCertificateSecurityException e) {
        return new FinishedMessage(ErrorCode.CERTIFICATE_REVOKED);
    } catch (TrustCertificateSecurityException e) {
        return new FinishedMessage(ErrorCode.CERTIFICATE_NOT_TRUSTED);
    } catch (CertificateSecurityException e) {
        return new FinishedMessage(ErrorCode.CERTIFICATE);
    }

    if (null != signatureEvent.getError()) {
        SecurityAuditEvent securityAuditEvent = new SecurityAuditEvent(Incident.TRUST, signingCertificate);
        this.securityAuditEvent.select(contextQualifier).fire(securityAuditEvent);
        return new FinishedMessage(signatureEvent.getError());
    }
    return new FinishedMessage();
}

From source file:cn.mrdear.pay.util.RSAUtils.java

/**
 * ???//from   ww  w.j  a v a 2s  .c  o m
 * 
 * @param algorithm
 *            ??
 * @param privateKey
 *            ?
 * @param data
 *            ?
 * @return ??
 */
public static byte[] sign(String algorithm, PrivateKey privateKey, byte[] data) {
    Assert.isNotEmpty(algorithm);
    Assert.notNull(privateKey);
    Assert.notNull(data);

    try {
        Signature signature = Signature.getInstance(algorithm, PROVIDER);
        signature.initSign(privateKey);
        signature.update(data);
        return signature.sign();
    } catch (NoSuchAlgorithmException e) {
        throw new RuntimeException(e.getMessage(), e);
    } catch (InvalidKeyException e) {
        throw new RuntimeException(e.getMessage(), e);
    } catch (SignatureException e) {
        throw new RuntimeException(e.getMessage(), e);
    }
}

From source file:acp.sdk.SecureUtil.java

/**
 * ???// ww w  .j a  va 2s  . c  o m
 * 
 * @param publicKey
 *            
 * @param signData
 *            ???
 * @param srcData
 *            ?
 * @param validateMethod
 *            ??.
 * @return
 * @throws Exception
 */
public static boolean validateSignBySoft(PublicKey publicKey, byte[] signData, byte[] srcData)
        throws Exception {
    Signature st = Signature.getInstance(BC_PROV_ALGORITHM_SHA1RSA, "BC");
    st.initVerify(publicKey);
    st.update(srcData);
    return st.verify(signData);
}

From source file:be.fedict.eid.applet.service.impl.handler.SignatureDataMessageHandler.java

public Object handleMessage(SignatureDataMessage message, Map<String, String> httpHeaders,
        HttpServletRequest request, HttpSession session) throws ServletException {
    LOG.debug("signature data message received");

    byte[] signatureValue = message.signatureValue;
    List<X509Certificate> certificateChain = message.certificateChain;
    if (certificateChain.isEmpty()) {
        throw new ServletException("certificate chain is empty");
    }/*from   w w  w  .j a  v  a  2 s  .c  om*/
    X509Certificate signingCertificate = certificateChain.get(0);
    if (null == signingCertificate) {
        throw new ServletException("non-repudiation certificate missing");
    }
    LOG.debug("non-repudiation signing certificate: " + signingCertificate.getSubjectX500Principal());

    for (X509Certificate certificate : certificateChain) {
        LOG.debug("signing x509 cert: " + certificate.getSubjectX500Principal());

    }
    PublicKey signingPublicKey = signingCertificate.getPublicKey();

    /*
     * Verify the signature.
     */
    String digestAlgo = SignatureDataMessageHandler.getDigestAlgo(session);
    byte[] expectedDigestValue = SignatureDataMessageHandler.getDigestValue(session);
    if (digestAlgo.endsWith("-PSS")) {
        LOG.debug("verifying RSA/PSS signature");
        try {
            Signature signature = Signature.getInstance("RAWRSASSA-PSS", BouncyCastleProvider.PROVIDER_NAME);
            if ("SHA-256-PSS".equals(digestAlgo)) {
                LOG.debug("RSA/PSS SHA256");
                signature.setParameter(
                        new PSSParameterSpec("SHA-256", "MGF1", new MGF1ParameterSpec("SHA-256"), 32, 1));
            }
            signature.initVerify(signingPublicKey);
            signature.update(expectedDigestValue);
            boolean result = signature.verify(signatureValue);
            if (false == result) {
                throw new SecurityException("signature incorrect");
            }
        } catch (Exception e) {
            LOG.debug("signature verification error: " + e.getMessage(), e);
            throw new ServletException("signature verification error: " + e.getMessage(), e);
        }
    } else {
        try {
            Signature signature = Signature.getInstance("RawRSA", BouncyCastleProvider.PROVIDER_NAME);
            signature.initVerify(signingPublicKey);
            ByteArrayOutputStream digestInfo = new ByteArrayOutputStream();
            if ("SHA-1".equals(digestAlgo) || "SHA1".equals(digestAlgo)) {
                digestInfo.write(SHA1_DIGEST_INFO_PREFIX);
            } else if ("SHA-224".equals(digestAlgo)) {
                digestInfo.write(SHA224_DIGEST_INFO_PREFIX);
            } else if ("SHA-256".equals(digestAlgo)) {
                digestInfo.write(SHA256_DIGEST_INFO_PREFIX);
            } else if ("SHA-384".equals(digestAlgo)) {
                digestInfo.write(SHA384_DIGEST_INFO_PREFIX);
            } else if ("SHA-512".equals(digestAlgo)) {
                digestInfo.write(SHA512_DIGEST_INFO_PREFIX);
            } else if ("RIPEMD160".equals(digestAlgo)) {
                digestInfo.write(RIPEMD160_DIGEST_INFO_PREFIX);
            } else if ("RIPEMD128".equals(digestAlgo)) {
                digestInfo.write(RIPEMD128_DIGEST_INFO_PREFIX);
            } else if ("RIPEMD256".equals(digestAlgo)) {
                digestInfo.write(RIPEMD256_DIGEST_INFO_PREFIX);
            }
            digestInfo.write(expectedDigestValue);
            signature.update(digestInfo.toByteArray());
            boolean result = signature.verify(signatureValue);
            if (false == result) {
                AuditService auditService = this.auditServiceLocator.locateService();
                if (null != auditService) {
                    String remoteAddress = request.getRemoteAddr();
                    auditService.signatureError(remoteAddress, signingCertificate);
                }
                throw new SecurityException("signature incorrect");
            }
        } catch (Exception e) {
            LOG.debug("signature verification error: " + e.getMessage());
            throw new ServletException("signature verification error: " + e.getMessage(), e);
        }
    }

    AuditService auditService = this.auditServiceLocator.locateService();
    if (null != auditService) {
        String userId = UserIdentifierUtil.getUserId(signingCertificate);
        auditService.signed(userId);
    }

    SignatureService signatureService = this.signatureServiceLocator.locateService();
    try {
        signatureService.setHttpSessionObject(request.getSession());
        signatureService.postSign(signatureValue, certificateChain);
    } catch (ExpiredCertificateSecurityException e) {
        return new FinishedMessage(ErrorCode.CERTIFICATE_EXPIRED);
    } catch (RevokedCertificateSecurityException e) {
        return new FinishedMessage(ErrorCode.CERTIFICATE_REVOKED);
    } catch (TrustCertificateSecurityException e) {
        return new FinishedMessage(ErrorCode.CERTIFICATE_NOT_TRUSTED);
    } catch (CertificateSecurityException e) {
        return new FinishedMessage(ErrorCode.CERTIFICATE);
    } catch (Exception e) {
        /*
         * We don't want to depend on the full JavaEE profile in this
         * artifact.
         */
        if ("javax.ejb.EJBException".equals(e.getClass().getName())) {
            Exception exception;
            try {
                Method getCausedByExceptionMethod = e.getClass().getMethod("getCausedByException",
                        new Class[] {});
                exception = (Exception) getCausedByExceptionMethod.invoke(e, new Object[] {});
            } catch (Exception e2) {
                LOG.debug("error: " + e.getMessage(), e);
                throw new SecurityException("error retrieving the root cause: " + e2.getMessage());
            }
            if (exception instanceof ExpiredCertificateSecurityException) {
                return new FinishedMessage(ErrorCode.CERTIFICATE_EXPIRED);
            }
            if (exception instanceof RevokedCertificateSecurityException) {
                return new FinishedMessage(ErrorCode.CERTIFICATE_REVOKED);
            }
            if (exception instanceof TrustCertificateSecurityException) {
                return new FinishedMessage(ErrorCode.CERTIFICATE_NOT_TRUSTED);
            }
            if (exception instanceof CertificateSecurityException) {
                return new FinishedMessage(ErrorCode.CERTIFICATE);
            }
        }
        throw new SecurityException("signature service error: " + e.getMessage(), e);
    }

    return new FinishedMessage();
}