Example usage for java.security KeyStore getKey

List of usage examples for java.security KeyStore getKey

Introduction

In this page you can find the example usage for java.security KeyStore getKey.

Prototype

public final Key getKey(String alias, char[] password)
        throws KeyStoreException, NoSuchAlgorithmException, UnrecoverableKeyException 

Source Link

Document

Returns the key associated with the given alias, using the given password to recover it.

Usage

From source file:org.openhealthtools.openatna.net.MailConnection.java

public MimeBodyPart decryptMessage(Message message) throws MessagingException {

    try {/*from w ww  .j  a  va 2 s  .c  om*/
        /* Add BC */
        Security.addProvider(new BouncyCastleProvider());
        // Open the key store
        KeyStore ks = KeyStore.getInstance("PKCS12", "BC");
        ks.load(new FileInputStream(getSenderKeystoreFile()), getSenderKeystorePassword().toCharArray());

        // find the certificate for the private key and generate a
        // suitable recipient identifier.
        X509Certificate cert = (X509Certificate) ks.getCertificate(getSenderKeyAlias());
        RecipientId recId = new RecipientId();

        recId.setSerialNumber(cert.getSerialNumber());
        recId.setIssuer(cert.getIssuerX500Principal().getEncoded());

        SMIMEEnveloped m = new SMIMEEnveloped((MimeMessage) message);
        RecipientInformationStore recipients = m.getRecipientInfos();
        // TODO figure out why this doesn't work...
        //RecipientInformation        recipient = recipients.get(recId);
        RecipientInformation recipient = (RecipientInformation) recipients.getRecipients().iterator().next();

        Key key = ks.getKey(getSenderKeyAlias(), getSenderKeystorePassword().toCharArray());
        byte[] byteContent = recipient.getContent(key, "BC");
        MimeBodyPart res = SMIMEUtil.toMimeBodyPart(byteContent);
        return res;

    } catch (Exception e) {
        log.error("Problem decrypting message: ", e);
        throw new MessagingException(e.getMessage());
    }
}

From source file:com.z299studio.pb.FingerprintDialog.java

private void initCipher(int mode) {
    try {/*from   w w w. j a  v  a 2  s . c  om*/
        IvParameterSpec ivParams;
        KeyStore keyStore = KeyStore.getInstance("AndroidKeyStore");
        keyStore.load(null);
        SecretKey key;
        mCipher = Cipher.getInstance(KeyProperties.KEY_ALGORITHM_AES + "/" + KeyProperties.BLOCK_MODE_CBC + "/"
                + KeyProperties.ENCRYPTION_PADDING_PKCS7);

        if (mode == Cipher.ENCRYPT_MODE) {
            KeyGenerator keyGenerator = KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES,
                    "AndroidKeyStore");
            keyGenerator.init(new KeyGenParameterSpec.Builder(KEY_NAME,
                    KeyProperties.PURPOSE_ENCRYPT | KeyProperties.PURPOSE_DECRYPT)
                            .setBlockModes(KeyProperties.BLOCK_MODE_CBC).setUserAuthenticationRequired(true)
                            .setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_PKCS7).build());
            mCipher.init(mode, keyGenerator.generateKey());
        } else {
            key = (SecretKey) keyStore.getKey(KEY_NAME, null);
            ivParams = new IvParameterSpec(Application.getInstance().getFpIv());
            mCipher.init(mode, key, ivParams);
        }
        mCryptoObject = new FingerprintManager.CryptoObject(mCipher);
    } catch (KeyStoreException | CertificateException | UnrecoverableKeyException | IOException
            | NoSuchAlgorithmException | InvalidKeyException | NoSuchProviderException
            | InvalidAlgorithmParameterException | NoSuchPaddingException e) {
        Log.e("Pb:FingerprintDialog", "Runtime error in initCipher.");
        Log.e("Pb:FingerprintDialog", e.toString());
    }
}

From source file:org.nuxeo.ecm.core.storage.sql.S3BinaryManager.java

@Override
protected void setupCloudClient() throws IOException {
    // Get settings from the configuration
    bucketName = getProperty(BUCKET_NAME_PROPERTY);
    bucketNamePrefix = MoreObjects.firstNonNull(getProperty(BUCKET_PREFIX_PROPERTY), StringUtils.EMPTY);
    String bucketRegion = getProperty(BUCKET_REGION_PROPERTY);
    if (isBlank(bucketRegion)) {
        bucketRegion = DEFAULT_BUCKET_REGION;
    }//from  w w w. j  a va 2s  .  co  m
    String awsID = getProperty(AWS_ID_PROPERTY);
    String awsSecret = getProperty(AWS_SECRET_PROPERTY);

    String proxyHost = Framework.getProperty(Environment.NUXEO_HTTP_PROXY_HOST);
    String proxyPort = Framework.getProperty(Environment.NUXEO_HTTP_PROXY_PORT);
    String proxyLogin = Framework.getProperty(Environment.NUXEO_HTTP_PROXY_LOGIN);
    String proxyPassword = Framework.getProperty(Environment.NUXEO_HTTP_PROXY_PASSWORD);

    int maxConnections = getIntProperty(CONNECTION_MAX_PROPERTY);
    int maxErrorRetry = getIntProperty(CONNECTION_RETRY_PROPERTY);
    int connectionTimeout = getIntProperty(CONNECTION_TIMEOUT_PROPERTY);
    int socketTimeout = getIntProperty(SOCKET_TIMEOUT_PROPERTY);

    String keystoreFile = getProperty(KEYSTORE_FILE_PROPERTY);
    String keystorePass = getProperty(KEYSTORE_PASS_PROPERTY);
    String privkeyAlias = getProperty(PRIVKEY_ALIAS_PROPERTY);
    String privkeyPass = getProperty(PRIVKEY_PASS_PROPERTY);
    String endpoint = getProperty(ENDPOINT_PROPERTY);
    String sseprop = getProperty(SERVERSIDE_ENCRYPTION_PROPERTY);
    if (isNotBlank(sseprop)) {
        userServerSideEncryption = Boolean.parseBoolean(sseprop);
    }

    // Fallback on default env keys for ID and secret
    if (isBlank(awsID)) {
        awsID = System.getenv(AWS_ID_ENV);
    }
    if (isBlank(awsSecret)) {
        awsSecret = System.getenv(AWS_SECRET_ENV);
    }

    if (isBlank(bucketName)) {
        throw new RuntimeException("Missing conf: " + BUCKET_NAME_PROPERTY);
    }

    if (!isBlank(bucketNamePrefix) && !bucketNamePrefix.endsWith("/")) {
        log.warn(String.format("%s %s S3 bucket prefix should end by '/' " + ": added automatically.",
                BUCKET_PREFIX_PROPERTY, bucketNamePrefix));
        bucketNamePrefix += "/";
    }
    // set up credentials
    if (isBlank(awsID) || isBlank(awsSecret)) {
        awsCredentialsProvider = new InstanceProfileCredentialsProvider();
        try {
            awsCredentialsProvider.getCredentials();
        } catch (AmazonClientException e) {
            throw new RuntimeException("Missing AWS credentials and no instance role found");
        }
    } else {
        awsCredentialsProvider = new BasicAWSCredentialsProvider(awsID, awsSecret);
    }

    // set up client configuration
    clientConfiguration = new ClientConfiguration();
    if (isNotBlank(proxyHost)) {
        clientConfiguration.setProxyHost(proxyHost);
    }
    if (isNotBlank(proxyPort)) {
        clientConfiguration.setProxyPort(Integer.parseInt(proxyPort));
    }
    if (isNotBlank(proxyLogin)) {
        clientConfiguration.setProxyUsername(proxyLogin);
    }
    if (proxyPassword != null) { // could be blank
        clientConfiguration.setProxyPassword(proxyPassword);
    }
    if (maxConnections > 0) {
        clientConfiguration.setMaxConnections(maxConnections);
    }
    if (maxErrorRetry >= 0) { // 0 is allowed
        clientConfiguration.setMaxErrorRetry(maxErrorRetry);
    }
    if (connectionTimeout >= 0) { // 0 is allowed
        clientConfiguration.setConnectionTimeout(connectionTimeout);
    }
    if (socketTimeout >= 0) { // 0 is allowed
        clientConfiguration.setSocketTimeout(socketTimeout);
    }

    // set up encryption
    encryptionMaterials = null;
    if (isNotBlank(keystoreFile)) {
        boolean confok = true;
        if (keystorePass == null) { // could be blank
            log.error("Keystore password missing");
            confok = false;
        }
        if (isBlank(privkeyAlias)) {
            log.error("Key alias missing");
            confok = false;
        }
        if (privkeyPass == null) { // could be blank
            log.error("Key password missing");
            confok = false;
        }
        if (!confok) {
            throw new RuntimeException("S3 Crypto configuration incomplete");
        }
        try {
            // Open keystore
            File ksFile = new File(keystoreFile);
            FileInputStream ksStream = new FileInputStream(ksFile);
            KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType());
            keystore.load(ksStream, keystorePass.toCharArray());
            ksStream.close();
            // Get keypair for alias
            if (!keystore.isKeyEntry(privkeyAlias)) {
                throw new RuntimeException("Alias " + privkeyAlias + " is missing or not a key alias");
            }
            PrivateKey privKey = (PrivateKey) keystore.getKey(privkeyAlias, privkeyPass.toCharArray());
            Certificate cert = keystore.getCertificate(privkeyAlias);
            PublicKey pubKey = cert.getPublicKey();
            KeyPair keypair = new KeyPair(pubKey, privKey);
            // Get encryptionMaterials from keypair
            encryptionMaterials = new EncryptionMaterials(keypair);
            cryptoConfiguration = new CryptoConfiguration();
        } catch (IOException | GeneralSecurityException e) {
            throw new RuntimeException("Could not read keystore: " + keystoreFile + ", alias: " + privkeyAlias,
                    e);
        }
    }
    isEncrypted = encryptionMaterials != null;

    // Try to create bucket if it doesn't exist
    if (!isEncrypted) {
        amazonS3 = new AmazonS3Client(awsCredentialsProvider, clientConfiguration);
    } else {
        amazonS3 = new AmazonS3EncryptionClient(awsCredentialsProvider,
                new StaticEncryptionMaterialsProvider(encryptionMaterials), clientConfiguration,
                cryptoConfiguration);
    }
    if (isNotBlank(endpoint)) {
        amazonS3.setEndpoint(endpoint);
    }

    // Set region explicitely for regions that reguire Version 4 signature
    ArrayList<String> V4_ONLY_REGIONS = new ArrayList<String>();
    V4_ONLY_REGIONS.add("eu-central-1");
    V4_ONLY_REGIONS.add("ap-northeast-2");
    if (V4_ONLY_REGIONS.contains(bucketRegion)) {
        amazonS3.setRegion(Region.getRegion(Regions.fromName(bucketRegion)));
    }

    try {
        if (!amazonS3.doesBucketExist(bucketName)) {
            amazonS3.createBucket(bucketName, bucketRegion);
            amazonS3.setBucketAcl(bucketName, CannedAccessControlList.Private);
        }
    } catch (AmazonClientException e) {
        throw new IOException(e);
    }

    // compat for NXP-17895, using "downloadfroms3", to be removed
    // these two fields have already been initialized by the base class initialize()
    // using standard property "directdownload"
    String dd = getProperty(DIRECTDOWNLOAD_PROPERTY_COMPAT);
    if (dd != null) {
        directDownload = Boolean.parseBoolean(dd);
    }
    int dde = getIntProperty(DIRECTDOWNLOAD_EXPIRE_PROPERTY_COMPAT);
    if (dde >= 0) {
        directDownloadExpire = dde;
    }

    transferManager = new TransferManager(amazonS3);
    abortOldUploads();
}

From source file:be.agiv.security.demo.Main.java

private void ipStsIssueToken() {
    GridBagLayout gridBagLayout = new GridBagLayout();
    GridBagConstraints gridBagConstraints = new GridBagConstraints();
    JPanel contentPanel = new JPanel(gridBagLayout);

    JLabel urlLabel = new JLabel("URL:");
    gridBagConstraints.gridx = 0;//from w  w  w.  j av a  2 s  . co  m
    gridBagConstraints.gridy = 0;
    gridBagConstraints.anchor = GridBagConstraints.WEST;
    gridBagConstraints.ipadx = 5;
    gridBagLayout.setConstraints(urlLabel, gridBagConstraints);
    contentPanel.add(urlLabel);

    JTextField urlTextField = new JTextField(
            "https://auth.beta.agiv.be/ipsts/Services/DaliSecurityTokenServiceConfiguration.svc/IWSTrust13",
            60);
    gridBagConstraints.gridx++;
    gridBagLayout.setConstraints(urlTextField, gridBagConstraints);
    contentPanel.add(urlTextField);

    JLabel realmLabel = new JLabel("Realm:");
    gridBagConstraints.gridx = 0;
    gridBagConstraints.gridy++;
    gridBagLayout.setConstraints(realmLabel, gridBagConstraints);
    contentPanel.add(realmLabel);

    JTextField realmTextField = new JTextField(AGIVSecurity.BETA_REALM, 30);
    gridBagConstraints.gridx++;
    gridBagLayout.setConstraints(realmTextField, gridBagConstraints);
    contentPanel.add(realmTextField);

    CredentialPanel credentialPanel = new CredentialPanel();
    gridBagConstraints.gridx = 0;
    gridBagConstraints.gridy++;
    gridBagConstraints.gridwidth = GridBagConstraints.REMAINDER;
    gridBagLayout.setConstraints(credentialPanel, gridBagConstraints);
    contentPanel.add(credentialPanel);

    int result = JOptionPane.showConfirmDialog(this, contentPanel, "IP-STS Issue Token",
            JOptionPane.OK_CANCEL_OPTION);
    if (result == JOptionPane.CANCEL_OPTION) {
        return;
    }

    String location = urlTextField.getText();
    String username = credentialPanel.getUsername();
    String password = credentialPanel.getPassword();
    File pkcs12File = credentialPanel.getPKCS12File();
    String realm = realmTextField.getText();

    IPSTSClient ipStsClient = new IPSTSClient(location, realm);
    try {
        if (null != username) {
            this.ipStsSecurityToken = ipStsClient.getSecurityToken(username, password);
        } else {
            KeyStore keyStore = KeyStore.getInstance("PKCS12");
            keyStore.load(new FileInputStream(pkcs12File), password.toCharArray());
            String alias = keyStore.aliases().nextElement();
            X509Certificate certificate = (X509Certificate) keyStore.getCertificate(alias);
            PrivateKey privateKey = (PrivateKey) keyStore.getKey(alias, password.toCharArray());
            this.ipStsSecurityToken = ipStsClient.getSecuritytoken(certificate, privateKey);
        }
        this.ipStsViewMenuItem.setEnabled(true);
        this.rStsIssueMenuItem.setEnabled(true);
        ipStsViewToken();
    } catch (Exception e) {
        showException(e);
    }
}

From source file:com.bluexml.side.Framework.alfresco.signature.repo.action.executer.PDFSignatureActionExecuter.java

/**
 * /* w  w  w . j  av a 2 s .c om*/
 * @param ruleAction
 * @param actionedUponNodeRef
 * @param actionedUponContentReader
 * @throws Exception 
 */
protected void doSignature(Action ruleAction, NodeRef actionedUponNodeRef,
        ContentReader actionedUponContentReader) throws Exception {

    NodeRef privateKey = (NodeRef) ruleAction.getParameterValue(PARAM_PRIVATE_KEY);
    String location = (String) ruleAction.getParameterValue(PARAM_LOCATION);
    String reason = (String) ruleAction.getParameterValue(PARAM_REASON);
    String visibility = (String) ruleAction.getParameterValue(PARAM_VISIBILITY);
    String keyPassword = (String) ruleAction.getParameterValue(PARAM_KEY_PASSWORD);
    String keyType = (String) ruleAction.getParameterValue(PARAM_KEY_TYPE);
    String signedName = (String) ruleAction.getParameterValue(PARAM_SIGNED_NAME);
    int height = Integer.parseInt((String) ruleAction.getParameterValue(PARAM_HEIGHT));
    int width = Integer.parseInt((String) ruleAction.getParameterValue(PARAM_WIDTH));

    // New keystore parameters
    String alias = (String) ruleAction.getParameterValue(PARAM_ALIAS);
    String storePassword = (String) ruleAction.getParameterValue(PARAM_STORE_PASSWORD);

    // Ugly and verbose, but fault-tolerant
    String locationXStr = (String) ruleAction.getParameterValue(PARAM_LOCATION_X);
    String locationYStr = (String) ruleAction.getParameterValue(PARAM_LOCATION_Y);
    int locationX = 0;
    int locationY = 0;
    try {
        locationX = locationXStr != null ? Integer.parseInt(locationXStr) : 0;
    } catch (NumberFormatException e) {
        locationX = 0;
    }
    try {
        locationY = locationXStr != null ? Integer.parseInt(locationYStr) : 0;
    } catch (NumberFormatException e) {
        locationY = 0;
    }

    File tempDir = null;
    ContentWriter writer = null;
    KeyStore ks = null;

    try {
        // get a keystore instance by
        if (keyType == null || keyType.equalsIgnoreCase(KEY_TYPE_DEFAULT)) {
            ks = KeyStore.getInstance(KeyStore.getDefaultType());
        } else if (keyType.equalsIgnoreCase(KEY_TYPE_PKCS12)) {
            ks = KeyStore.getInstance("pkcs12");
        } else {
            throw new Exception("Unknown key type " + keyType + " specified");
        }

        // open the reader to the key and load it
        ContentReader keyReader = serviceRegistry.getContentService().getReader(privateKey,
                ContentModel.PROP_CONTENT);
        ks.load(keyReader.getContentInputStream(), storePassword.toCharArray());

        // set alias
        //         String alias = (String) ks.aliases().nextElement();

        PrivateKey key = (PrivateKey) ks.getKey(alias, keyPassword.toCharArray());
        Certificate[] chain = ks.getCertificateChain(alias);

        //open original pdf
        ContentReader pdfReader = getReader(actionedUponNodeRef);
        PdfReader reader = new PdfReader(pdfReader.getContentInputStream());

        // create temp dir to store file
        File alfTempDir = TempFileProvider.getTempDir();
        tempDir = new File(alfTempDir.getPath() + File.separatorChar + actionedUponNodeRef.getId());
        tempDir.mkdir();
        File file = new File(tempDir,
                serviceRegistry.getFileFolderService().getFileInfo(actionedUponNodeRef).getName());

        FileOutputStream fout = new FileOutputStream(file);
        PdfStamper stamp = PdfStamper.createSignature(reader, fout, '\0');
        PdfSignatureAppearance sap = stamp.getSignatureAppearance();
        sap.setCrypto(key, chain, null, PdfSignatureAppearance.WINCER_SIGNED);

        // set reason for signature and location of signer
        sap.setReason(reason);
        sap.setLocation(location);

        if (visibility.equalsIgnoreCase(PDFSignatureActionExecuter.VISIBILITY_VISIBLE)) {
            sap.setVisibleSignature(new Rectangle(locationX + width, locationY - height, locationX, locationY),
                    1, null);
        }

        stamp.close();

        String[] splitedFilename = file.getName().split("\\.");
        String name = "-" + signedName + "." + splitedFilename[splitedFilename.length - 1];
        for (int i = splitedFilename.length - 2; i >= 0; i--) {
            if (name.equals("-" + signedName + "." + splitedFilename[splitedFilename.length - 1])) {
                name = splitedFilename[i] + name;
            } else {
                name = splitedFilename[i] + "." + name;
            }
        }

        writer = getWriter(name, (NodeRef) ruleAction.getParameterValue(PARAM_DESTINATION_FOLDER));
        writer.setEncoding(actionedUponContentReader.getEncoding());
        writer.setMimetype(FILE_MIMETYPE);
        writer.putContent(file);

        file.delete();
    } catch (Exception e) {
        throw e;
    } finally {
        if (tempDir != null) {
            try {
                tempDir.delete();
            } catch (Exception ex) {
            }
        }
    }
}

From source file:org.wso2.carbon.core.util.KeyStoreManager.java

/**
 * This method loads the private key of a given key store
 *
 * @param keyStoreName name of the key store
 * @param alias        alias of the private key
 * @return private key corresponding to the alias
 *//* www . j a va2 s.co  m*/
public Key getPrivateKey(String keyStoreName, String alias) {
    try {
        if (KeyStoreUtil.isPrimaryStore(keyStoreName)) {
            return getDefaultPrivateKey();
        }

        String path = RegistryResources.SecurityManagement.KEY_STORES + "/" + keyStoreName;
        org.wso2.carbon.registry.api.Resource resource;
        KeyStore keyStore;

        if (registry.resourceExists(path)) {
            resource = registry.get(path);
        } else {
            throw new SecurityException("Given Key store is not available in registry : " + keyStoreName);
        }

        CryptoUtil cryptoUtil = CryptoUtil.getDefaultCryptoUtil();
        String encryptedPassword = resource
                .getProperty(RegistryResources.SecurityManagement.PROP_PRIVATE_KEY_PASS);
        String privateKeyPasswd = new String(cryptoUtil.base64DecodeAndDecrypt(encryptedPassword));

        if (isCachedKeyStoreValid(keyStoreName)) {
            keyStore = loadedKeyStores.get(keyStoreName).getKeyStore();
            return keyStore.getKey(alias, privateKeyPasswd.toCharArray());
        } else {
            byte[] bytes = (byte[]) resource.getContent();
            String keyStorePassword = new String(cryptoUtil.base64DecodeAndDecrypt(
                    resource.getProperty(RegistryResources.SecurityManagement.PROP_PASSWORD)));
            keyStore = KeyStore
                    .getInstance(resource.getProperty(RegistryResources.SecurityManagement.PROP_TYPE));
            ByteArrayInputStream stream = new ByteArrayInputStream(bytes);
            keyStore.load(stream, keyStorePassword.toCharArray());

            KeyStoreBean keyStoreBean = new KeyStoreBean(keyStore, resource.getLastModified());
            updateKeyStoreCache(keyStoreName, keyStoreBean);
            return keyStore.getKey(alias, privateKeyPasswd.toCharArray());
        }
    } catch (Exception e) {
        log.error("Error loading the private key from the key store : " + keyStoreName);
        throw new SecurityException("Error loading the private key from the key store : " + keyStoreName, e);
    }
}

From source file:org.yawlfoundation.yawl.digitalSignature.DigitalSignature.java

private PrivateKey getPrivateKey() {
    KeyStore keystore = null;

    try {//from w  w w  .  ja  v a 2s. c  o  m
        char[] password = _Password.toCharArray();
        String _alias = "";
        _Password = null;
        keystore = KeyStore.getInstance("PKCS12");

        keystore.load(new FileInputStream(_Pathway + _P12), password);

        Enumeration enumeration = keystore.aliases();
        Vector vectaliases = new Vector();
        while (enumeration.hasMoreElements())
            vectaliases.add(enumeration.nextElement());

        String[] aliases = (String[]) (vectaliases.toArray(new String[0]));
        for (int i = 0; i < aliases.length; i++)
            if (keystore.isKeyEntry(aliases[i])) {
                _alias = aliases[i];
                break;
            }
        PrivateKey pk = (PrivateKey) keystore.getKey(_alias, password);
        password = null;
        return pk;

    } catch (Exception e) {
        System.out.println("Error: " + "Invalid pkcs#12 Certificate");
        return null;
    }

}

From source file:org.alfresco.extension.pdftoolkit.repo.action.executer.PDFSignatureActionExecuter.java

/**
 * //from   w ww.  jav  a  2  s. c o m
 * @param ruleAction
 * @param actionedUponNodeRef
 * @param actionedUponContentReader
 */
protected void doSignature(Action ruleAction, NodeRef actionedUponNodeRef,
        ContentReader actionedUponContentReader) {

    NodeRef privateKey = (NodeRef) ruleAction.getParameterValue(PARAM_PRIVATE_KEY);
    String location = (String) ruleAction.getParameterValue(PARAM_LOCATION);
    String position = (String) ruleAction.getParameterValue(PARAM_POSITION);
    String reason = (String) ruleAction.getParameterValue(PARAM_REASON);
    String visibility = (String) ruleAction.getParameterValue(PARAM_VISIBILITY);
    String keyPassword = (String) ruleAction.getParameterValue(PARAM_KEY_PASSWORD);
    String keyType = (String) ruleAction.getParameterValue(PARAM_KEY_TYPE);
    int height = getInteger(ruleAction.getParameterValue(PARAM_HEIGHT));
    int width = getInteger(ruleAction.getParameterValue(PARAM_WIDTH));
    int pageNumber = getInteger(ruleAction.getParameterValue(PARAM_PAGE));

    // New keystore parameters
    String alias = (String) ruleAction.getParameterValue(PARAM_ALIAS);
    String storePassword = (String) ruleAction.getParameterValue(PARAM_STORE_PASSWORD);

    int locationX = getInteger(ruleAction.getParameterValue(PARAM_LOCATION_X));
    int locationY = getInteger(ruleAction.getParameterValue(PARAM_LOCATION_Y));

    File tempDir = null;
    ContentWriter writer = null;
    KeyStore ks = null;

    try {
        // get a keystore instance by
        if (keyType == null || keyType.equalsIgnoreCase(KEY_TYPE_DEFAULT)) {
            ks = KeyStore.getInstance(KeyStore.getDefaultType());
        } else if (keyType.equalsIgnoreCase(KEY_TYPE_PKCS12)) {
            ks = KeyStore.getInstance("pkcs12");
        } else {
            throw new AlfrescoRuntimeException("Unknown key type " + keyType + " specified");
        }

        // open the reader to the key and load it
        ContentReader keyReader = getReader(privateKey);
        ks.load(keyReader.getContentInputStream(), storePassword.toCharArray());

        // set alias
        // String alias = (String) ks.aliases().nextElement();

        PrivateKey key = (PrivateKey) ks.getKey(alias, keyPassword.toCharArray());
        Certificate[] chain = ks.getCertificateChain(alias);

        // open original pdf
        ContentReader pdfReader = getReader(actionedUponNodeRef);
        PdfReader reader = new PdfReader(pdfReader.getContentInputStream());

        // create temp dir to store file
        File alfTempDir = TempFileProvider.getTempDir();
        tempDir = new File(alfTempDir.getPath() + File.separatorChar + actionedUponNodeRef.getId());
        tempDir.mkdir();
        File file = new File(tempDir,
                serviceRegistry.getFileFolderService().getFileInfo(actionedUponNodeRef).getName());

        FileOutputStream fout = new FileOutputStream(file);
        PdfStamper stamp = PdfStamper.createSignature(reader, fout, '\0');
        PdfSignatureAppearance sap = stamp.getSignatureAppearance();
        sap.setCrypto(key, chain, null, PdfSignatureAppearance.WINCER_SIGNED);

        // set reason for signature and location of signer
        sap.setReason(reason);
        sap.setLocation(location);

        if (visibility.equalsIgnoreCase(PDFSignatureActionExecuter.VISIBILITY_VISIBLE)) {
            //create the signature rectangle using either the provided position or
            //the exact coordinates, if provided
            if (position != null && !position.trim().equalsIgnoreCase("")) {
                Rectangle pageRect = reader.getPageSizeWithRotation(pageNumber);
                sap.setVisibleSignature(positionSignature(position, pageRect, width, height), pageNumber, null);
            } else {
                sap.setVisibleSignature(
                        new Rectangle(locationX, locationY, locationX + width, locationY - height), pageNumber,
                        null);
            }
        }

        stamp.close();

        //can't use BasePDFActionExecuter.getWriter here need the nodeRef of the destination
        NodeRef destinationNode = createDestinationNode(file.getName(),
                (NodeRef) ruleAction.getParameterValue(PARAM_DESTINATION_FOLDER), actionedUponNodeRef);
        writer = serviceRegistry.getContentService().getWriter(destinationNode, ContentModel.PROP_CONTENT,
                true);

        writer.setEncoding(actionedUponContentReader.getEncoding());
        writer.setMimetype(FILE_MIMETYPE);
        writer.putContent(file);

        file.delete();

        //if useAspect is true, store some additional info about the signature in the props
        if (useAspect) {
            serviceRegistry.getNodeService().addAspect(destinationNode, PDFToolkitModel.ASPECT_SIGNED,
                    new HashMap<QName, Serializable>());
            serviceRegistry.getNodeService().setProperty(destinationNode, PDFToolkitModel.PROP_REASON, reason);
            serviceRegistry.getNodeService().setProperty(destinationNode, PDFToolkitModel.PROP_LOCATION,
                    location);
            serviceRegistry.getNodeService().setProperty(destinationNode, PDFToolkitModel.PROP_SIGNATUREDATE,
                    new java.util.Date());
            serviceRegistry.getNodeService().setProperty(destinationNode, PDFToolkitModel.PROP_SIGNEDBY,
                    AuthenticationUtil.getRunAsUser());
        }

    } catch (IOException e) {
        throw new AlfrescoRuntimeException(e.getMessage(), e);
    } catch (KeyStoreException e) {
        throw new AlfrescoRuntimeException(e.getMessage(), e);
    } catch (ContentIOException e) {
        throw new AlfrescoRuntimeException(e.getMessage(), e);
    } catch (NoSuchAlgorithmException e) {
        throw new AlfrescoRuntimeException(e.getMessage(), e);
    } catch (CertificateException e) {
        throw new AlfrescoRuntimeException(e.getMessage(), e);
    } catch (UnrecoverableKeyException e) {
        throw new AlfrescoRuntimeException(e.getMessage(), e);
    } catch (DocumentException e) {
        throw new AlfrescoRuntimeException(e.getMessage(), e);
    } finally {
        if (tempDir != null) {
            try {
                tempDir.delete();
            } catch (Exception ex) {
                throw new AlfrescoRuntimeException(ex.getMessage(), ex);
            }
        }
    }
}

From source file:org.demoiselle.signer.policy.impl.cades.pkcs7.impl.CAdESSignerTest.java

/**
 * Teste de coassinatura anexada/*from ww  w .ja v  a2s .  c o m*/
 */
//@Test
public void testSignCoAtached() {
    try {

        System.out.println("******** TESTANDO COM CONTEDO *****************");

        // INFORMAR o arquivo
        String fileDirName = "";
        String fileSignatureDirName = "";

        byte[] fileToSign = readContent(fileDirName);
        byte[] signatureFile = readContent(fileSignatureDirName);

        // quando certificado em arquivo, precisa informar a senha
        char[] senha = "senha".toCharArray();

        // Para certificado em Neo Id e windows
        //KeyStore ks = getKeyStoreTokenBySigner();

        // Para certificado em Token
        KeyStore ks = getKeyStoreToken();

        // Para certificado em arquivo A1
        // KeyStore ks = getKeyStoreFile();

        // Para certificados no so windows (mascapi)
        // KeyStore ks = getKeyStoreOnWindows();

        String alias = getAlias(ks);

        /* Parametrizando o objeto doSign */
        PKCS7Signer signer = PKCS7Factory.getInstance().factoryDefault();
        signer.setCertificates(ks.getCertificateChain(alias));

        // para token
        signer.setPrivateKey((PrivateKey) ks.getKey(alias, null));

        // para arquivo
        // signer.setPrivateKey((PrivateKey) ks.getKey(alias, senha));
        // politica sem carimbo de tempo
        signer.setSignaturePolicy(PolicyFactory.Policies.AD_RB_CADES_2_3);
        // com carimbo de tempo
        //signer.setSignaturePolicy(PolicyFactory.Policies.AD_RT_CADES_2_3);

        // para mudar o algoritimo
        signer.setAlgorithm(SignerAlgorithmEnum.SHA512withRSA);
        if (org.demoiselle.signer.core.keystore.loader.configuration.Configuration.getInstance().getSO()
                .toLowerCase().indexOf("indows") > 0) {
            signer.setAlgorithm(SignerAlgorithmEnum.SHA256withRSA);
        }

        /* Realiza a assinatura do conteudo */
        System.out.println("Efetuando a  assinatura do conteudo");
        // Assinatura desatachada
        byte[] signature = signer.doAttachedSign(fileToSign, signatureFile);
        File file = new File(fileDirName + "-co_atached.p7s");
        FileOutputStream os = new FileOutputStream(file);
        os.write(signature);
        os.flush();
        os.close();
        System.out.println("------------------ ok --------------------------");
        assertTrue(true);
    } catch (KeyStoreException | NoSuchAlgorithmException | UnrecoverableKeyException | IOException ex) {
        ex.printStackTrace();
        assertTrue(false);
    }
}

From source file:org.demoiselle.signer.policy.impl.cades.pkcs7.impl.CAdESSignerTest.java

/**
 * Teste de coassinatura com envio do hash calculado
 *///from   ww  w. j av a  2 s.c o m
//@Test
public void testCoSignHash() {
    try {

        System.out.println("******** TESTANDO COM CONTEDO *****************");

        // INFORMAR o arquivo
        String fileDirName = "local_e_nome_do_arquivo_para_assinar";
        String fileSignatureDirName = "local_e_nome_do_arquivo_da_assinatura";

        byte[] fileToSign = readContent(fileDirName);
        byte[] signatureFile = readContent(fileSignatureDirName);

        // gera o hash do arquivo
        java.security.MessageDigest md = java.security.MessageDigest
                .getInstance(DigestAlgorithmEnum.SHA_512.getAlgorithm());
        // devido a uma restrio do token branco, no windws s funciona com 256
        if (org.demoiselle.signer.core.keystore.loader.configuration.Configuration.getInstance().getSO()
                .toLowerCase().indexOf("indows") > 0) {
            md = java.security.MessageDigest.getInstance(DigestAlgorithmEnum.SHA_256.getAlgorithm());
        }

        byte[] hash = md.digest(fileToSign);

        // quando certificado em arquivo, precisa informar a senha
        char[] senha = "senha".toCharArray();

        // Para certificado em Token
        KeyStore ks = getKeyStoreToken();

        // Para certificado em arquivo A1
        // KeyStore ks = getKeyStoreFile();

        // Para certificados no so windows (mascapi)
        // KeyStore ks = getKeyStoreOnWindows();

        String alias = getAlias(ks);

        /* Parametrizando o objeto doSign */
        PKCS7Signer signer = PKCS7Factory.getInstance().factoryDefault();
        signer.setCertificates(ks.getCertificateChain(alias));

        // para token
        signer.setPrivateKey((PrivateKey) ks.getKey(alias, null));

        // para arquivo
        // signer.setPrivateKey((PrivateKey) ks.getKey(alias, senha));
        // politica sem carimbo de tempo
        signer.setSignaturePolicy(PolicyFactory.Policies.AD_RB_CADES_2_3);
        // com carimbo de tempo
        //signer.setSignaturePolicy(PolicyFactory.Policies.AD_RT_CADES_2_3);

        // seta o algoritmo de acordo com o que foi gerado o Hash
        signer.setAlgorithm(SignerAlgorithmEnum.SHA512withRSA);
        if (org.demoiselle.signer.core.keystore.loader.configuration.Configuration.getInstance().getSO()
                .toLowerCase().indexOf("indows") > 0) {
            signer.setAlgorithm(SignerAlgorithmEnum.SHA256withRSA);
        }

        /* Realiza a assinatura do conteudo */
        System.out.println("Efetuando a  assinatura do conteudo");
        // Assinatura desatachada
        byte[] signature = signer.doHashCoSign(hash, signatureFile);
        File file = new File(fileDirName + "hash-co.p7s");
        FileOutputStream os = new FileOutputStream(file);
        os.write(signature);
        os.flush();
        os.close();
        assertTrue(true);
    } catch (KeyStoreException | NoSuchAlgorithmException | UnrecoverableKeyException | IOException ex) {
        ex.printStackTrace();
        assertTrue(false);
    }
}