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:edu.ucsb.eucalyptus.transport.query.WalrusQuerySecurityHandler.java

public UserInfo handle(String addr, String verb, Map<String, String> parameters, Map<String, String> headers)
        throws QuerySecurityException {
    CaseInsensitiveMap hdrs = new CaseInsensitiveMap(headers);

    //this.checkParameters( hdrs );
    //:: check the signature :://

    if (hdrs.containsKey(StorageQuerySecurityHandler.StorageSecurityParameters.EucaSignature)) {
        //possible internal request -- perform authentication using internal credentials
        String date = (String) hdrs.remove(SecurityParameter.Date);
        String eucaCert = (String) hdrs.remove(StorageQuerySecurityHandler.StorageSecurityParameters.EucaCert);
        String signature = (String) hdrs
                .remove(StorageQuerySecurityHandler.StorageSecurityParameters.EucaSignature);
        String data = verb + "\n" + date + "\n" + addr + "\n";

        Signature sig;//from   w  ww . j av  a2s. c  om
        boolean valid = false;
        try {
            byte[] bytes = Base64.decode(eucaCert);
            String certString = new String(bytes);
            PEMReader pemReader = new PEMReader(new StringReader(certString));
            X509Certificate cert = (X509Certificate) pemReader.readObject();
            AbstractKeyStore keyStore = ServiceKeyStore.getInstance();
            if (keyStore.getCertificateAlias(cert) != null) {
                //cert found in keystore
                PublicKey publicKey = cert.getPublicKey();
                sig = Signature.getInstance("SHA1withRSA");

                sig.initVerify(publicKey);
                sig.update(data.getBytes());
                valid = sig.verify(Base64.decode(signature));
            } else {
                LOG.warn("WalrusQuerySecurityHandler(): certificate not found in keystore");
            }
        } catch (Exception ex) {
            LOG.warn("Authentication exception: " + ex.getMessage());
            ex.printStackTrace();
        }

        if (!valid) {
            throw new QuerySecurityException("User authentication failed.");
        }
        //run as admin
        UserInfo admin = new UserInfo(EucalyptusProperties.NAME);
        admin.setIsAdministrator(Boolean.TRUE);
        return admin;
    } else if (hdrs.containsKey(WalrusProperties.FormField.FormUploadPolicyData)) {
        String data = (String) hdrs.remove(WalrusProperties.FormField.FormUploadPolicyData);
        String auth_part = (String) hdrs.remove(SecurityParameter.Authorization);

        if (auth_part != null) {
            String sigString[] = getSigInfo(auth_part);
            String signature = sigString[1];
            return getUserInfo(sigString[0], signature, data, false);
        }
        throw new QuerySecurityException("User authentication failed.");
    } else {
        //external user request
        String date;
        String verifyDate;
        if (hdrs.containsKey("x-amz-date")) {
            date = "";
            verifyDate = (String) hdrs.get("x-amz-date");
        } else {
            date = (String) hdrs.remove(SecurityParameter.Date);
            verifyDate = date;
            if (date == null || date.length() <= 0)
                throw new QuerySecurityException("User authentication failed. Date must be specified.");
        }

        try {
            Date dateToVerify = DateUtil.parseDate(verifyDate);
            Date currentDate = new Date();
            if (Math.abs(currentDate.getTime() - dateToVerify.getTime()) > EXPIRATION_LIMIT)
                throw new QuerySecurityException("Message expired. Sorry.");
        } catch (Exception ex) {
            throw new QuerySecurityException("Unable to parse date.");
        }
        String content_md5 = (String) hdrs.remove("Content-MD5");
        content_md5 = content_md5 == null ? "" : content_md5;
        String content_type = (String) hdrs.remove("Content-Type");
        content_type = content_type == null ? "" : content_type;

        String[] addrStrings = addr.split("\\?");
        String addrString = addrStrings[0];

        if (addrStrings.length > 1) {
            for (SubResource subResource : SubResource.values()) {
                if (addr.endsWith(subResource.toString())) {
                    addrString += "?" + subResource.toString();
                    break;
                }
            }
        }

        String data = verb + "\n" + content_md5 + "\n" + content_type + "\n" + date + "\n"
                + getCanonicalizedAmzHeaders(hdrs) + addrString;

        String auth_part = hdrs.remove(SecurityParameter.Authorization);

        if (auth_part != null) {
            String sigString[] = getSigInfo(auth_part);
            String signature = sigString[1];
            return getUserInfo(sigString[0], signature, data, false);
        } else if (parameters.containsKey(SecurityParameter.AWSAccessKeyId.toString())) {
            //query string authentication
            String accesskeyid = parameters.remove(SecurityParameter.AWSAccessKeyId.toString());
            try {
                String signature = URLDecoder.decode(parameters.remove(SecurityParameter.Signature.toString()),
                        "UTF-8");
                if (signature == null) {
                    throw new QuerySecurityException("User authentication failed. Null signature.");
                }
                String expires = parameters.remove(SecurityParameter.Expires.toString());
                if (expires == null) {
                    throw new QuerySecurityException("Authentication failed. Expires must be specified.");
                }
                if (checkExpires(expires)) {
                    String stringToSign = verb + "\n" + content_md5 + "\n" + content_type + "\n"
                            + Long.parseLong(expires) + "\n" + getCanonicalizedAmzHeaders(hdrs) + addrString;
                    return getUserInfo(accesskeyid, signature, stringToSign, true);
                } else {
                    throw new QuerySecurityException("Cannot process request. Expired.");
                }
            } catch (Exception ex) {
                throw new QuerySecurityException("Could not verify request " + ex.getMessage());
            }
        } else {
            //anonymous request
            return null;
        }
    }
}

From source file:SignPdf.java

/**
* Add a signature and a cryptographic timestamp to a pdf document. See www.ietf.org/rfc/rfc3161.txt. Proves that this
* pdf had the current content at the current point in time.
*
* @param originalPdf//from  w  w w .  j a v a2 s  .  co m
* @param targetPdf
* @param pk
* @param certChain
* @param revoked
* @param tsaAddress
* address of a rfc 3161 compatible timestamp server
* @param reason
* reason for the signature
* @param location
* location of signing
* @param contact
* emailaddress of the person who is signing
* @throws IOException
* @throws DocumentException
* @throws SignatureException
*/
public static void signAndTimestamp(final InputStream originalPdf, final OutputStream targetPdf,
        final PrivateKey pk, final X509Certificate[] certChain, final CRL[] revoked, final String tsaAddress,
        final String reason, final String location, final String contact)
        throws IOException, DocumentException, SignatureException {
    // only an estimate, depends on the certificates returned by the TSA
    final int timestampSize = 4400;
    Security.addProvider(new BouncyCastleProvider());

    final PdfReader reader = new PdfReader(originalPdf);
    final PdfStamper stamper = PdfStamper.createSignature(reader, targetPdf, '\0');
    final PdfSignatureAppearance sap = stamper.getSignatureAppearance();

    // comment next lines to have an invisible signature
    Rectangle cropBox = reader.getCropBox(1);
    float width = 50;
    float height = 50;
    Rectangle rectangle = new Rectangle(cropBox.getRight(width) - 20, cropBox.getTop(height) - 20,
            cropBox.getRight() - 20, cropBox.getTop() - 20);
    sap.setVisibleSignature(rectangle, 1, null);
    //sap.setVisibleSignature(new Rectangle(450, 650, 500, 700), 1, null);
    sap.setLayer2Text("");

    final PdfSigGenericPKCS sig = new PdfSigGenericPKCS.PPKMS("BC");
    final HashMap<PdfName, Integer> exclusionSizes = new HashMap<PdfName, Integer>();

    // some informational fields
    sig.setReason(reason);
    sig.setLocation(location);
    sig.setContact(contact);
    sig.setName(PdfPKCS7.getSubjectFields(certChain[0]).getField("CN"));
    sig.setDate(new PdfDate(Calendar.getInstance()));

    // signing stuff
    final byte[] digest = new byte[256];
    final byte[] rsaData = new byte[20];
    sig.setExternalDigest(digest, rsaData, "RSA");
    sig.setSignInfo(pk, certChain, revoked);
    final PdfString contents = (PdfString) sig.get(PdfName.CONTENTS);
    // *2 to get hex size, +2 for delimiters
    PdfLiteral contentsLit = new PdfLiteral((contents.toString().length() + timestampSize) * 2 + 2);
    exclusionSizes.put(PdfName.CONTENTS, new Integer(contentsLit.getPosLength()));
    sig.put(PdfName.CONTENTS, contentsLit);

    // certification; will display dialog or blue bar in Acrobat Reader

    sap.setCertificationLevel(PdfSignatureAppearance.CERTIFIED_NO_CHANGES_ALLOWED);

    // process all the information set above
    sap.setCryptoDictionary(sig);
    sap.preClose(exclusionSizes);

    // calculate digest (hash)
    try {
        final MessageDigest messageDigest = MessageDigest.getInstance("SHA1");
        final byte[] buf = new byte[8192];
        int n;
        final InputStream inp = sap.getRangeStream();
        while ((n = inp.read(buf)) != -1) {
            messageDigest.update(buf, 0, n);
        }
        final byte[] hash = messageDigest.digest();

        // make signature (SHA1 the hash, prepend algorithm ID, pad, and encrypt with RSA)
        final Signature sign = Signature.getInstance("SHA1withRSA");
        sign.initSign(pk);
        sign.update(hash);
        final byte[] signature = sign.sign();

        // prepare the location of the signature in the target PDF
        contentsLit = (PdfLiteral) sig.get(PdfName.CONTENTS);
        final byte[] outc = new byte[(contentsLit.getPosLength() - 2) / 2];
        final PdfPKCS7 pkcs7 = sig.getSigner();
        pkcs7.setExternalDigest(signature, hash, "RSA");
        final PdfDictionary dic = new PdfDictionary();

        byte[] ssig = pkcs7.getEncodedPKCS7();
        try {
            // try to retrieve cryptographic timestamp from configured tsa server
            ssig = pkcs7.getEncodedPKCS7(null, null, new TSAClientBouncyCastle(tsaAddress), null);
        } catch (final RuntimeException e) {
            log.error("Could not retrieve timestamp from server.", e);
        }
        System.arraycopy(ssig, 0, outc, 0, ssig.length);

        // add the timestamped signature
        dic.put(PdfName.CONTENTS, new PdfString(outc).setHexWriting(true));

        // finish up
        sap.close(dic);
    } catch (final InvalidKeyException e) {
        throw new RuntimeException("Internal implementation error! No such signature type.", e);
    } catch (final NoSuchAlgorithmException e) {
        throw new RuntimeException("Internal implementation error! No such algorithm type.", e);
    }
}

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

String getSignature(PrivateKey key) throws Exception {
    Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
    byte[] bytes = getOriginalBytes();
    Signature sig = Signature.getInstance("SHA1withRSA");
    sig.initSign(key);//  ww  w  . j ava  2  s  . co m
    sig.update(bytes);
    byte[] signed = sig.sign();
    Base64 b64 = new Base64(-1);
    return b64.encodeToString(signed);
}

From source file:org.pepstock.jem.node.https.SubmitHandler.java

@Override
public void handle(final HttpRequest request, final HttpResponse response, final HttpContext context)
        throws HttpException, IOException {
    // extracts the host
    String host = context.getAttribute(JOB_SUBMIT_IP_ADDRESS_KEY).toString();
    // gets HTTP method (uses locale ENGLISH to be sure to have POST)
    String method = request.getRequestLine().getMethod().toUpperCase(Locale.ENGLISH);
    // if NOT post, exception!
    if (!method.equals(POST)) {
        LogAppl.getInstance().emit(NodeMessage.JEMC284W, method, host);
        throw new MethodNotSupportedException(
                NodeMessage.JEMC284W.toMessage().getFormattedMessage(method, host));
    }/*from www  .  j  a va 2 s  . com*/
    // gets the URI or the request
    String target = request.getRequestLine().getUri();
    // if is not the same , accepts, exception!
    if (!target.equalsIgnoreCase(DEFAULT_ACTION)) {
        LogAppl.getInstance().emit(NodeMessage.JEMC285W, target, host);
        throw new MethodNotSupportedException(
                NodeMessage.JEMC285W.toMessage().getFormattedMessage(target, host));
    }
    // checks the HTTP request
    if (request instanceof HttpEntityEnclosingRequest) {
        // gets the entity of the request
        HttpEntity entity = ((HttpEntityEnclosingRequest) request).getEntity();
        // gets the body in string format
        String result = EntityUtils.toString(entity, CharSet.DEFAULT);
        // reads the first line,
        // with all URL encoded variables  
        String vars = StringUtils.substringBefore(result, DELIMITER);
        // loads a map with all parms
        Map<String, String> parms = loadParametersMap(URLEncodedUtils.parse(vars, CharSet.DEFAULT));
        // gets the USER
        String user = parms.get(SubmitParameters.USER.getName());
        // if JEM is configured to have the Socket Interceptor on HC
        // the client MUST provide a SIGNATURE (using own private key) with
        // the user crypted inside
        if (Main.getHazelcastConfig().getNetworkConfig().getSocketInterceptorConfig().isEnabled()) {
            // checks if there is the signature
            if (parms.containsKey(USER_SIGNATURE_KEY)) {
                // gets the signature in HEX format
                String cryptedUserString = parms.get(USER_SIGNATURE_KEY);
                // gets keys stores
                KeyStoresInfo keyStoresInfo = KeyStoreUtil.getKeyStoresInfo();
                try {
                    // extracts from the USER key store the PUBLIC KEY (upload by UI) for the user  
                    PublicKey publicKey = KeysUtil.getPublicKeyByAlias(keyStoresInfo.getUserKeystoreInfo(),
                            user);
                    // creates tne SIGNATURE verifying steps
                    Signature signature = Signature.getInstance("SHA256withRSA");
                    // sets public key
                    signature.initVerify(publicKey);
                    // sets content to check. It uses USER
                    signature.update(user.getBytes(CharSet.DEFAULT_CHARSET_NAME));
                    // checks if is verified
                    if (!signature.verify(Hex.decodeHex(cryptedUserString.toCharArray()))) {
                        // if not, log and EXCEPTION
                        LogAppl.getInstance().emit(NodeMessage.JEMC286W, user, host);
                        throw new HttpException(
                                NodeMessage.JEMC286W.toMessage().getFormattedMessage(user, host));
                    }
                } catch (MessageException e) {
                    LogAppl.getInstance().emit(NodeMessage.JEMC286W, user, host);
                    throw new ProtocolException(e.getMessage(), e);
                } catch (KeyException e) {
                    throw new ProtocolException(e.getMessage(), e);
                } catch (DecoderException e) {
                    throw new ProtocolException(e.getMessage(), e);
                } catch (NoSuchAlgorithmException e) {
                    throw new ProtocolException(e.getMessage(), e);
                } catch (SignatureException e) {
                    throw new ProtocolException(e.getMessage(), e);
                }
            } else {
                LogAppl.getInstance().emit(NodeMessage.JEMC287W, user, host);
                // if here, the signature is missing
                throw new HttpException(NodeMessage.JEMC287W.toMessage().getFormattedMessage(user, host));
            }
        }
        // gets JEM environemnt name and its passwrod
        String env = parms.get(SubmitParameters.ENV.getName());
        String password = parms.get(SubmitParameters.PASSWORD.getName());
        // checks if password and env are same, 
        // comparing with the HC configuration
        if (!Main.getHazelcastConfig().getGroupConfig().getName().equalsIgnoreCase(env)
                || !Main.getHazelcastConfig().getGroupConfig().getPassword().equalsIgnoreCase(password)) {
            // if not equals, exception
            LogAppl.getInstance().emit(NodeMessage.JEMC288W, host);
            throw new HttpException(NodeMessage.JEMC288W.toMessage().getFormattedMessage(host));
        }

        // reads teh second row of the body, with the JCL
        String jcl = StringUtils.substringAfter(result, DELIMITER);

        // sets the entity to send back, submitting the job.
        // it returns the JOBID
        StringEntity resultEntity = new StringEntity(submit(jcl, user, host, parms),
                ContentType.create(RESPONSE_MIME_TYPE, CharSet.DEFAULT_CHARSET_NAME));
        // sets STATUS code and entity 
        response.setStatusCode(HttpStatus.SC_OK);
        response.setEntity(resultEntity);
    } else {
        // if here, the request is not correct
        LogAppl.getInstance().emit(NodeMessage.JEMC284W, method, host);
        throw new MethodNotSupportedException(
                NodeMessage.JEMC284W.toMessage().getFormattedMessage(method, host));
    }
}

From source file:com.cws.esolutions.security.dao.certmgmt.impl.CertificateManagerImpl.java

/**
 * @see com.cws.esolutions.security.dao.certmgmt.interfaces.ICertificateManager#createCertificateRequest(List, String, int, int)
 */// w  ww .  ja v a  2s.c  o  m
public synchronized File createCertificateRequest(final List<String> subjectData, final String storePassword,
        final int validityPeriod, final int keySize) throws CertificateManagementException {
    final String methodName = ICertificateManager.CNAME
            + "#createCertificateRequest(final List<String> subjectData, final String storePassword, final int validityPeriod, final int keySize) throws CertificateManagementException";

    if (DEBUG) {
        DEBUGGER.debug(methodName);
        DEBUGGER.debug("Value: {}", subjectData);
        DEBUGGER.debug("Value: {}", validityPeriod);
        DEBUGGER.debug("Value: {}", keySize);
    }

    final File rootDirectory = certConfig.getRootDirectory();
    final String signatureAlgorithm = certConfig.getSignatureAlgorithm();
    final String certificateAlgorithm = certConfig.getCertificateAlgorithm();
    final File privateKeyDirectory = FileUtils
            .getFile(certConfig.getPrivateKeyDirectory() + "/" + subjectData.get(0));
    final File publicKeyDirectory = FileUtils
            .getFile(certConfig.getPublicKeyDirectory() + "/" + subjectData.get(0));
    final File csrDirectory = FileUtils.getFile(certConfig.getCsrDirectory() + "/" + subjectData.get(0));
    final File storeDirectory = FileUtils.getFile(certConfig.getStoreDirectory() + "/" + subjectData.get(0));
    final X500Name x500Name = new X500Name("CN=" + subjectData.get(0) + ",OU=" + subjectData.get(1) + ",O="
            + subjectData.get(2) + ",L=" + subjectData.get(3) + ",ST=" + subjectData.get(4) + ",C="
            + subjectData.get(5) + ",E=" + subjectData.get(6));

    if (DEBUG) {
        DEBUGGER.debug("rootDirectory: {}", rootDirectory);
        DEBUGGER.debug("signatureAlgorithm: {}", signatureAlgorithm);
        DEBUGGER.debug("certificateAlgorithm: {}", certificateAlgorithm);
        DEBUGGER.debug("privateKeyDirectory: {}", privateKeyDirectory);
        DEBUGGER.debug("publicKeyDirectory: {}", publicKeyDirectory);
        DEBUGGER.debug("csrDirectory: {}", csrDirectory);
        DEBUGGER.debug("storeDirectory: {}", storeDirectory);
        DEBUGGER.debug("x500Name: {}", x500Name);
    }

    File csrFile = null;
    JcaPEMWriter csrPemWriter = null;
    JcaPEMWriter publicKeyWriter = null;
    JcaPEMWriter privateKeyWriter = null;
    FileOutputStream csrFileStream = null;
    FileOutputStream keyStoreStream = null;
    FileOutputStream publicKeyFileStream = null;
    FileOutputStream privateKeyFileStream = null;
    OutputStreamWriter csrFileStreamWriter = null;
    OutputStreamWriter privateKeyStreamWriter = null;
    OutputStreamWriter publicKeyStreamWriter = null;

    try {
        KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
        keyStore.load(null, storePassword.toCharArray());

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

        SecureRandom random = new SecureRandom();
        KeyPairGenerator keyGenerator = KeyPairGenerator.getInstance(certificateAlgorithm);
        keyGenerator.initialize(keySize, random);

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

        KeyPair keyPair = keyGenerator.generateKeyPair();

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

        if (keyPair != null) {
            final Signature sig = Signature.getInstance(signatureAlgorithm);
            final PrivateKey privateKey = keyPair.getPrivate();
            final PublicKey publicKey = keyPair.getPublic();

            if (DEBUG) {
                DEBUGGER.debug("Signature: {}", sig);
                DEBUGGER.debug("PrivateKey: {}", privateKey);
                DEBUGGER.debug("PublicKey: {}", publicKey);
            }

            sig.initSign(privateKey, random);
            ContentSigner signGen = new JcaContentSignerBuilder(signatureAlgorithm).build(privateKey);

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

            Calendar expiry = Calendar.getInstance();
            expiry.add(Calendar.DAY_OF_YEAR, validityPeriod);

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

            CertificateFactory certFactory = CertificateFactory.getInstance(certConfig.getCertificateType());

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

            X509Certificate[] issuerCert = new X509Certificate[] { (X509Certificate) certFactory
                    .generateCertificate(new FileInputStream(certConfig.getIntermediateCertificateFile())) };

            if (DEBUG) {
                DEBUGGER.debug("X509Certificate[]: {}", (Object) issuerCert);
            }

            keyStore.setCertificateEntry(certConfig.getRootCertificateName(), certFactory.generateCertificate(
                    new FileInputStream(FileUtils.getFile(certConfig.getRootCertificateFile()))));
            keyStore.setCertificateEntry(certConfig.getIntermediateCertificateName(),
                    certFactory.generateCertificate(new FileInputStream(
                            FileUtils.getFile(certConfig.getIntermediateCertificateFile()))));

            PKCS10CertificationRequestBuilder builder = new JcaPKCS10CertificationRequestBuilder(x500Name,
                    publicKey);

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

            PKCS10CertificationRequest csr = builder.build(signGen);

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

            // write private key
            File privateKeyFile = FileUtils.getFile(privateKeyDirectory + "/" + subjectData.get(0)
                    + SecurityServiceConstants.PRIVATEKEY_FILE_EXT);

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

            if (!(privateKeyFile.createNewFile())) {
                throw new IOException("Failed to store private file");
            }

            privateKeyFileStream = new FileOutputStream(privateKeyFile);
            privateKeyStreamWriter = new OutputStreamWriter(privateKeyFileStream);

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

            privateKeyWriter = new JcaPEMWriter(privateKeyStreamWriter);
            privateKeyWriter.writeObject(privateKey);
            privateKeyWriter.flush();
            privateKeyStreamWriter.flush();
            privateKeyFileStream.flush();

            // write public key
            File publicKeyFile = FileUtils.getFile(publicKeyDirectory + "/" + subjectData.get(0)
                    + SecurityServiceConstants.PUBLICKEY_FILE_EXT);

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

            if (!(publicKeyFile.createNewFile())) {
                throw new IOException("Failed to store public key file");
            }

            publicKeyFileStream = new FileOutputStream(publicKeyFile);
            publicKeyStreamWriter = new OutputStreamWriter(publicKeyFileStream);

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

            publicKeyWriter = new JcaPEMWriter(publicKeyStreamWriter);
            publicKeyWriter.writeObject(publicKey);
            publicKeyWriter.flush();
            publicKeyStreamWriter.flush();
            publicKeyFileStream.flush();

            // write csr
            csrFile = FileUtils
                    .getFile(csrDirectory + "/" + subjectData.get(0) + SecurityServiceConstants.CSR_FILE_EXT);

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

            if (!(csrFile.createNewFile())) {
                throw new IOException("Failed to store CSR file");
            }

            csrFileStream = new FileOutputStream(csrFile);
            csrFileStreamWriter = new OutputStreamWriter(csrFileStream);

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

            csrPemWriter = new JcaPEMWriter(csrFileStreamWriter);
            csrPemWriter.writeObject(csr);
            csrPemWriter.flush();
            csrFileStreamWriter.flush();
            csrFileStream.flush();

            File keyStoreFile = FileUtils
                    .getFile(storeDirectory + "/" + subjectData.get(0) + "." + KeyStore.getDefaultType());

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

            keyStoreStream = FileUtils.openOutputStream(keyStoreFile);

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

            keyStore.setKeyEntry(subjectData.get(0), (Key) keyPair.getPrivate(), storePassword.toCharArray(),
                    issuerCert);
            keyStore.store(keyStoreStream, storePassword.toCharArray());
            keyStoreStream.flush();

            if (DEBUG) {
                DEBUGGER.debug("KeyStore: {}", keyStore);
            }
        } else {
            throw new CertificateManagementException("Failed to generate keypair. Cannot continue.");
        }
    } catch (FileNotFoundException fnfx) {
        throw new CertificateManagementException(fnfx.getMessage(), fnfx);
    } catch (IOException iox) {
        throw new CertificateManagementException(iox.getMessage(), iox);
    } catch (NoSuchAlgorithmException nsax) {
        throw new CertificateManagementException(nsax.getMessage(), nsax);
    } catch (IllegalStateException isx) {
        throw new CertificateManagementException(isx.getMessage(), isx);
    } catch (InvalidKeyException ikx) {
        throw new CertificateManagementException(ikx.getMessage(), ikx);
    } catch (OperatorCreationException ocx) {
        throw new CertificateManagementException(ocx.getMessage(), ocx);
    } catch (KeyStoreException ksx) {
        throw new CertificateManagementException(ksx.getMessage(), ksx);
    } catch (CertificateException cx) {
        throw new CertificateManagementException(cx.getMessage(), cx);
    } finally {
        if (csrFileStreamWriter != null) {
            IOUtils.closeQuietly(csrFileStreamWriter);
        }

        if (csrFileStream != null) {
            IOUtils.closeQuietly(csrFileStream);
        }

        if (csrPemWriter != null) {
            IOUtils.closeQuietly(csrPemWriter);
        }

        if (publicKeyFileStream != null) {
            IOUtils.closeQuietly(publicKeyFileStream);
        }

        if (publicKeyStreamWriter != null) {
            IOUtils.closeQuietly(publicKeyStreamWriter);
        }

        if (publicKeyWriter != null) {
            IOUtils.closeQuietly(publicKeyWriter);
        }

        if (privateKeyFileStream != null) {
            IOUtils.closeQuietly(privateKeyFileStream);
        }

        if (privateKeyStreamWriter != null) {
            IOUtils.closeQuietly(privateKeyStreamWriter);
        }

        if (privateKeyWriter != null) {
            IOUtils.closeQuietly(privateKeyWriter);
        }

        if (keyStoreStream != null) {
            IOUtils.closeQuietly(keyStoreStream);
        }
    }

    return csrFile;
}

From source file:bftsmart.tom.core.TOMLayer.java

/**
 * Creates a new instance of TOMulticastLayer
 * @param manager Execution manager/*from  w  ww .  j  av a  2 s  .  c o  m*/
 * @param receiver Object that receives requests from clients
 * @param lm Leader module
 * @param a Acceptor role of the PaW algorithm
 * @param cs Communication system between replicas
 * @param controller Reconfiguration Manager
 */
public TOMLayer(ExecutionManager manager, ServiceReplica receiver, Recoverable recoverer, LeaderModule lm,
        Acceptor a, ServerCommunicationSystem cs, ServerViewController controller) {

    super("TOM Layer");

    this.execManager = manager;
    this.lm = lm;
    this.acceptor = a;
    this.communication = cs;
    this.controller = controller;

    //do not create a timer manager if the timeout is 0
    if (this.controller.getStaticConf().getRequestTimeout() == 0) {
        this.requestsTimer = null;
    } else
        this.requestsTimer = new RequestsTimer(this, communication, this.controller); // Create requests timers manager (a thread)

    this.clientsManager = new ClientsManager(this.controller, requestsTimer); // Create clients manager

    try {
        this.md = MessageDigest.getInstance("MD5"); // TODO: shouldn't it be SHA?
    } catch (Exception e) {
        e.printStackTrace(System.out);
    }

    try {
        this.engine = Signature.getInstance("SHA1withRSA");
    } catch (Exception e) {
        e.printStackTrace(System.err);
    }

    this.prk = this.controller.getStaticConf().getRSAPrivateKey();
    this.lcManager = new LCManager(this, controller, md);
    this.dt = new DeliveryThread(this, receiver, recoverer, this.controller); // Create delivery thread
    this.dt.start();
    this.stateManager = recoverer.getStateManager();
    stateManager.init(this, dt);
}

From source file:com.vmware.identity.samlservice.impl.SamlServiceImpl.java

@Override
public void verifySignature(String message, String signature) throws IllegalStateException {

    Validate.notNull(this.getCheckAlgorithm());
    Validate.notNull(this.getCertPath());

    boolean verifies = false;
    try {/*from  w ww .j av  a  2 s. co m*/
        /* create a Signature object and initialize it with the public key */
        Signature sig = Signature.getInstance(this.getCheckAlgorithm().getAlgorithmName());
        X509Certificate[] chain = this.getCertPath().getCertificates().toArray(new X509Certificate[0]);

        for (int i = 0; i < chain.length && !verifies; i++) {
            sig.initVerify(chain[i].getPublicKey());

            /* add buffer to verify */
            byte[] buffer = message.getBytes("UTF-8");
            sig.update(buffer);

            byte[] sigToVerify = Base64.decode(signature);

            verifies = sig.verify(sigToVerify);
            if (!verifies) {
                log.error("Unable to verify the signature, message " + message + ", sigAlg "
                        + this.getCheckAlgorithm().getAlgorithmName() + ", signature " + signature);
            }
        }

        log.debug("signature verifies: {}", verifies);
    } catch (Exception e) {
        log.error("Caught exception while verifying signature, message: " + message + ", sigAlg "
                + this.getCheckAlgorithm().getAlgorithmName() + ", signature " + signature);
        log.error("Exception is: {}", e.toString());
        throw new IllegalStateException(e);
    }
    if (!verifies) {
        throw new IllegalStateException("Signature verification failed.");
    }
}

From source file:org.wso2.carbon.device.mgt.iot.virtualfirealarm.service.impl.util.SecurityManager.java

public static boolean verifySignature(String data, String signedData, PublicKey verificationKey)
        throws VirtualFireAlarmException {

    Signature signature;//w  w  w .  j a v  a 2  s  .  co  m
    boolean verified;

    try {
        signature = Signature.getInstance(SIGNATURE_ALG);
        signature.initVerify(verificationKey);
        signature.update(Base64.decodeBase64(data));

        verified = signature.verify(Base64.decodeBase64(signedData));

    } catch (NoSuchAlgorithmException e) {
        String errorMsg = "Algorithm not found exception occurred for Signature instance of [" + SIGNATURE_ALG
                + "]";
        log.error(errorMsg);
        throw new VirtualFireAlarmException(errorMsg, e);
    } catch (SignatureException e) {
        String errorMsg = "Signature exception occurred for Signature instance of [" + SIGNATURE_ALG + "]";
        log.error(errorMsg);
        throw new VirtualFireAlarmException(errorMsg, e);
    } catch (InvalidKeyException e) {
        String errorMsg = "InvalidKey exception occurred for signatureKey \n[\n" + verificationKey + "\n]\n";
        log.error(errorMsg);
        throw new VirtualFireAlarmException(errorMsg, e);
    }

    return verified;
}

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.j  a v a2 s  . co m
 * @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:be.fedict.commons.eid.consumer.BeIDIntegrity.java

/**
 * Verifies a signature./*  w  w w .ja  va 2s  .  c o m*/
 * 
 * @param signatureAlgo
 * @param signatureData
 * @param publicKey
 * @param data
 * @return
 * @throws NoSuchAlgorithmException
 * @throws InvalidKeyException
 * @throws SignatureException
 */
public boolean verifySignature(final String signatureAlgo, final byte[] signatureData,
        final PublicKey publicKey, final byte[]... data)
        throws NoSuchAlgorithmException, InvalidKeyException, SignatureException {
    Signature signature;
    signature = Signature.getInstance(signatureAlgo);
    signature.initVerify(publicKey);
    for (byte[] dataItem : data) {
        signature.update(dataItem);
    }
    final boolean result = signature.verify(signatureData);
    return result;
}