Search in sources :

Example 1 with SecureRandomDescriptor

use of org.jcryptool.crypto.flexiprovider.descriptors.algorithms.SecureRandomDescriptor in project core by jcryptool.

the class PerformOperationListener method addActionItem.

private void addActionItem(IFlexiProviderOperation operation) {
    ICommandService service = (ICommandService) PlatformUI.getWorkbench().getService(ICommandService.class);
    if ((Boolean) // $NON-NLS-1$
    service.getCommand("org.jcryptool.actions.recordCommand").getState("org.jcryptool.actions.recordCommand.toggleState").getValue()) {
        // $NON-NLS-1$
        AlgorithmDescriptor descriptor = operation.getAlgorithmDescriptor();
        ActionItem item = // $NON-NLS-1$
        new ActionItem(EditorsManager.getInstance().getActiveEditorTitle(), descriptor.getAlgorithmName());
        item.setPluginId(operation.getRegistryType().getName());
        if (operation.getOperation() == OperationType.DECRYPT) {
            // $NON-NLS-1$
            item.setActionType("decrypt");
        } else if (operation.getOperation() == OperationType.ENCRYPT) {
            // $NON-NLS-1$
            item.setActionType("encrypt");
        } else if (operation.getOperation() == OperationType.SIGN) {
            // $NON-NLS-1$
            item.setActionType("sign");
        } else if (operation.getOperation() == OperationType.VERIFY) {
            // $NON-NLS-1$
            item.setActionType("verify");
        }
        // item.addParam("input", operation.getInput()); //$NON-NLS-1$
        // item.addParam("output", operation.getOutput()); //$NON-NLS-1$
        // $NON-NLS-1$
        item.addParam("signature", operation.getSignature());
        // $NON-NLS-1$
        item.addParam("algorithm type", operation.getAlgorithmDescriptor().getType().getName());
        IKeyStoreAlias alias = operation.getKeyStoreAlias();
        if (alias != null) {
            // $NON-NLS-1$
            item.addParam("contact", alias.getContactName());
            // $NON-NLS-1$
            item.addParam("key alias", alias.getAliasString());
            // $NON-NLS-1$
            item.addParam("key length", String.valueOf(alias.getKeyLength()));
            if (operation.getPassword() != null) {
                // $NON-NLS-1$
                item.addParam("key password", String.valueOf(operation.getPassword()));
            }
        }
        if (descriptor instanceof BlockCipherDescriptor) {
            // $NON-NLS-1$
            item.addParam("mode", ((BlockCipherDescriptor) descriptor).getMode());
            // $NON-NLS-1$
            item.addParam("padding scheme", ((BlockCipherDescriptor) descriptor).getPadding());
        } else if (descriptor instanceof SecureRandomDescriptor) {
            // $NON-NLS-1$ //$NON-NLS-2$
            item.addParam("random size", "" + ((SecureRandomDescriptor) descriptor).getLength());
        // byte[][] alphabets = ((SecureRandomDescriptor) descriptor).getAlphabet();
        // TODO push alphapet to items property "alphabet"
        }
        ActionCascadeService.getInstance().addItem(item);
    }
}
Also used : SecureRandomDescriptor(org.jcryptool.crypto.flexiprovider.descriptors.algorithms.SecureRandomDescriptor) BlockCipherDescriptor(org.jcryptool.crypto.flexiprovider.descriptors.algorithms.BlockCipherDescriptor) ActionItem(org.jcryptool.actions.core.types.ActionItem) AlgorithmDescriptor(org.jcryptool.crypto.flexiprovider.descriptors.algorithms.AlgorithmDescriptor) ICommandService(org.eclipse.ui.commands.ICommandService) IKeyStoreAlias(org.jcryptool.crypto.keystore.keys.IKeyStoreAlias)

Example 2 with SecureRandomDescriptor

use of org.jcryptool.crypto.flexiprovider.descriptors.algorithms.SecureRandomDescriptor in project core by jcryptool.

the class SecureRandomEngine method perform.

@Override
public void perform(KeyObject usedKey) {
    if (initialized) {
        // $NON-NLS-1$
        LogUtil.logInfo("performing a secure random");
        OutputStream outputStream = initOutput(operation.getOutput());
        try {
            if (operation.getOutput().equals("<Editor>")) {
                // $NON-NLS-1$
                byte[][] alphabet = ((SecureRandomDescriptor) operation.getAlgorithmDescriptor()).getAlphabet();
                if (alphabet == null) {
                    random.nextBytes(value);
                    outputStream.write(value);
                    outputStream.close();
                    EditorsManager.getInstance().openNewHexEditor(AbstractEditorService.createOutputFile(new FileInputStream(new File(getOutputURI()))));
                } else {
                    value = new byte[1];
                    int log = (int) Math.pow(2, Math.ceil((Math.log(alphabet.length) / Math.log(2))));
                    for (int i = 0; i < ((SecureRandomDescriptor) operation.getAlgorithmDescriptor()).getLength(); i++) {
                        boolean found = false;
                        while (!found) {
                            random.nextBytes(value);
                            // modulo
                            int r = (int) ((int) value[0] & (log - 1));
                            if (r < 0)
                                r += log;
                            if (r < alphabet.length) {
                                outputStream.write(alphabet[r]);
                                found = true;
                                if ((i + 1) % 20 == 0)
                                    // $NON-NLS-1$
                                    outputStream.write("\n".getBytes());
                            }
                        }
                    }
                    outputStream.close();
                    EditorsManager.getInstance().openNewTextEditor(new PathEditorInput(URIUtil.toPath(getOutputURI())));
                }
            }
        } catch (IOException e) {
            LogUtil.logError(FlexiProviderEnginesPlugin.PLUGIN_ID, "IOException while performing a secure random", e, false);
        } catch (PartInitException e) {
            LogUtil.logError(FlexiProviderEnginesPlugin.PLUGIN_ID, "Failed to open the Hexeditor", e, true);
        }
    }
}
Also used : SecureRandomDescriptor(org.jcryptool.crypto.flexiprovider.descriptors.algorithms.SecureRandomDescriptor) OutputStream(java.io.OutputStream) IOException(java.io.IOException) PartInitException(org.eclipse.ui.PartInitException) File(java.io.File) FileInputStream(java.io.FileInputStream) PathEditorInput(org.jcryptool.core.operations.util.PathEditorInput)

Example 3 with SecureRandomDescriptor

use of org.jcryptool.crypto.flexiprovider.descriptors.algorithms.SecureRandomDescriptor in project core by jcryptool.

the class IntegratorHandler method execute.

/**
 * runs the action: setup the algorithm and executed the specified operation
 */
@Override
public Object execute(ExecutionEvent event) {
    AlgorithmDescriptor descriptor = getAlgorithmDescriptor(FLEXIPROVIDER_ALGORITHM_NAME);
    if (descriptor == null) {
        MessageBox messageBox = new MessageBox(getActiveWorkbenchWindow().getShell());
        // $NON-NLS-1$
        messageBox.setText(Messages.getString("DummyAction.error"));
        // $NON-NLS-1$
        messageBox.setMessage(Messages.getString("DummyAction.8"));
        messageBox.open();
        return (null);
    }
    String readableNameExtension;
    switch(algorithmType) {
        case TYPE_RANDOM_NUMBER_GENERATOR:
            // $NON-NLS-1$
            readableNameExtension = Messages.getString("DummyAction.random_number_generator");
            break;
        case TYPE_SIGNATURE:
            // $NON-NLS-1$
            readableNameExtension = Messages.getString("DummyAction.signature");
            break;
        case TYPE_MESSAGE_DIGEST:
            // $NON-NLS-1$
            readableNameExtension = Messages.getString("DummyAction.message_digest");
            break;
        case TYPE_MESSAGE_AUTHTIFICATION_CODE:
            // $NON-NLS-1$
            readableNameExtension = Messages.getString("DummyAction.message_authentification_code");
            break;
        default:
            // $NON-NLS-1$
            readableNameExtension = Messages.getString("DummyAction.encryption");
    }
    // Get which key lengths are valid for this algorithm
    int[] validKeyLengths = null;
    IMetaKeyGenerator keyGen = AlgorithmsXMLManager.getInstance().getSecretKeyGenerator(FLEXIPROVIDER_ALGORITHM_NAME);
    if (keyGen != null) {
        if (keyGen.getLengths().getLengths() != null) {
            validKeyLengths = new int[keyGen.getLengths().getLengths().size()];
            for (int i = 0; i < validKeyLengths.length; i++) validKeyLengths[i] = keyGen.getLengths().getLengths().get(i);
        } else {
            validKeyLengths = new int[1];
            validKeyLengths[0] = keyGen.getLengths().getDefaultLength();
        }
    }
    wizard = new IntegratorWizard(READABLE_ALGORITHM_NAME + readableNameExtension, READABLE_ALGORITHM_NAME, HEADER_DESCRIPTION, SHOW_OPERATION_GROUP, SHOW_PADDING_GROUP, SHOW_KEY, SHOW_KEY_SOURCE_GROUP, validKeyLengths, SHOW_SIGNATURE_GROUP, SHOW_RANDOM_GROUP, SHOW_MESSAGE_DIGEST_GROUP, algorithmType);
    WizardDialog dialog = new WizardDialog(getActiveWorkbenchWindow().getShell(), wizard);
    dialog.setHelpAvailable(true);
    switch(dialog.open()) {
        case Window.OK:
            if (algorithmType == TYPE_CIPHER_BLOCK) {
                descriptor = new BlockCipherDescriptor(descriptor.getAlgorithmName(), AlgorithmsXMLManager.getInstance().getMode(wizard.getMode().getDescription()).getID(), AlgorithmsXMLManager.getInstance().getPaddingScheme(wizard.getPadding().getPaddingSchemeName()).getID(), null, descriptor.getAlgorithmParameterSpec());
            }
            if (algorithmType == TYPE_RANDOM_NUMBER_GENERATOR) {
                if (wizard.doFilter())
                    descriptor = new SecureRandomDescriptor(descriptor.getAlgorithmName(), wizard.getRandomSize(), wizard.getFilter());
                else
                    descriptor = new SecureRandomDescriptor(descriptor.getAlgorithmName(), wizard.getRandomSize());
            }
            IntegratorOperation operation = new IntegratorOperation(descriptor);
            // $NON-NLS-1$
            operation.setEntryName("");
            // $NON-NLS-1$
            operation.setInput(Messages.getString("InputType"));
            // $NON-NLS-1$
            operation.setOutput("<Editor>");
            operation.setSignature(wizard.signature());
            operation.setUseCustomKey(wizard.useCustomKey());
            if (wizard.useCustomKey())
                operation.setKeyBytes(wizard.getCustomKey());
            try {
                if (// $NON-NLS-1$
                SHOW_KEY != null && !SHOW_KEY.equals("") && !wizard.useCustomKey())
                    operation.setKeyStoreAlias(wizard.getKey());
                if (wizard.encrypt()) {
                    // explicit encrypt
                    if (descriptor.getType() == RegistryType.SIGNATURE) {
                        operation.setOperation(OperationType.VERIFY);
                    } else {
                        operation.setOperation(OperationType.ENCRYPT);
                    }
                } else {
                    // implicit decrypt
                    if (descriptor.getType() == RegistryType.SIGNATURE) {
                        operation.setOperation(OperationType.SIGN);
                    } else {
                        operation.setOperation(OperationType.DECRYPT);
                    }
                }
                if (SHOW_MESSAGE_DIGEST_GROUP > 0 && !wizard.encrypt()) {
                    try {
                        MessageDigest digest = Registry.getMessageDigest(operation.getAlgorithmDescriptor().getAlgorithmName());
                        InputStream inputStream = EditorsManager.getInstance().getActiveEditorContentInputStream();
                        int i;
                        while ((i = inputStream.read()) != -1) {
                            digest.update((byte) i);
                        }
                        byte[] checksumAsBytes = digest.digest();
                        // $NON-NLS-1$
                        String checksum = "";
                        for (byte b : checksumAsBytes) {
                            String temp = Integer.toHexString((int) b);
                            // $NON-NLS-1$ //$NON-NLS-2$
                            checksum += (temp.length() == 1 ? "0" : "") + temp.substring(Math.max(0, temp.length() - 2));
                        }
                        String expectedChecksum = wizard.getExpectedChecksum();
                        if (checksum.equalsIgnoreCase(expectedChecksum)) {
                            MessageBox messageBox = new MessageBox(getActiveWorkbenchWindow().getShell(), SWT.ICON_WORKING);
                            // $NON-NLS-1$
                            messageBox.setText(Messages.getString("IntegratorAction.0"));
                            // $NON-NLS-1$
                            messageBox.setMessage(Messages.getString("IntegratorAction.1"));
                            messageBox.open();
                        } else {
                            MessageBox messageBox = new MessageBox(getActiveWorkbenchWindow().getShell(), SWT.ICON_ERROR);
                            // $NON-NLS-1$
                            messageBox.setText(Messages.getString("IntegratorAction.2"));
                            messageBox.setMessage(// $NON-NLS-1$
                            NLS.bind(// $NON-NLS-1$
                            Messages.getString("IntegratorAction.3"), new Object[] { checksum.toLowerCase(), expectedChecksum.toLowerCase() }));
                            messageBox.open();
                        }
                    } catch (NoSuchAlgorithmException e) {
                        LogUtil.logError(IntegratorPlugin.PLUGIN_ID, "NoSuchAlgorithmException while initializing a message digest", e, // $NON-NLS-1$
                        true);
                    }
                } else {
                    PerformOperationManager.getInstance().firePerformOperation(operation);
                }
                if (operation.getOperation() == OperationType.SIGN) {
                    MessageBox messageBox = new MessageBox(getActiveWorkbenchWindow().getShell(), SWT.NONE);
                    // $NON-NLS-1$
                    messageBox.setText(Messages.getString("DummyAction.13"));
                    // $NON-NLS-1$
                    messageBox.setMessage(Messages.getString("DummyAction.14") + wizard.signature());
                    messageBox.open();
                }
            } catch (IOException ex) {
                LogUtil.logError(ex);
            }
            break;
        case Window.CANCEL:
            break;
    }
    return (null);
}
Also used : InputStream(java.io.InputStream) NoSuchAlgorithmException(de.flexiprovider.api.exceptions.NoSuchAlgorithmException) IOException(java.io.IOException) IMetaKeyGenerator(org.jcryptool.crypto.flexiprovider.descriptors.meta.interfaces.IMetaKeyGenerator) AlgorithmDescriptor(org.jcryptool.crypto.flexiprovider.descriptors.algorithms.AlgorithmDescriptor) MessageBox(org.eclipse.swt.widgets.MessageBox) SecureRandomDescriptor(org.jcryptool.crypto.flexiprovider.descriptors.algorithms.SecureRandomDescriptor) BlockCipherDescriptor(org.jcryptool.crypto.flexiprovider.descriptors.algorithms.BlockCipherDescriptor) IDataObject(org.jcryptool.core.operations.dataobject.IDataObject) MessageDigest(de.flexiprovider.api.MessageDigest) WizardDialog(org.eclipse.jface.wizard.WizardDialog)

Example 4 with SecureRandomDescriptor

use of org.jcryptool.crypto.flexiprovider.descriptors.algorithms.SecureRandomDescriptor in project core by jcryptool.

the class StartHandler method execute.

public IStatus execute(final ActionView view, final ActionItem startItem, final Shell shell, IProgressMonitor monitor) {
    ActionCascade ac = view.getActionCascade();
    final TableViewer viewer = view.getViewer();
    // $NON-NLS-1$
    LogUtil.logInfo("Running Action Cascade " + ac.getName());
    boolean start = false;
    for (final ActionItem a : ac.getAllItems()) {
        int steps = ac.getSize();
        // Start the execution at the first selected element
        if (a == startItem) {
            start = true;
            monitor.beginTask(a.getActionName(), steps);
        } else
            steps--;
        if (start) {
            if (monitor.isCanceled()) {
                return Status.CANCEL_STATUS;
            }
            try {
                boolean executed = false;
                // Set focus on moved row. Just look and feel ...
                display.asyncExec(new Runnable() {

                    public void run() {
                        viewer.setSelection(new StructuredSelection(a), true);
                    }
                });
                OperationsPlugin op = OperationsPlugin.getDefault();
                CommandInfo[] commands = op.getAlgorithmsManager().getShadowAlgorithmCommands();
                // Try to find an CryptoAlgorithm-Plug-in (Classic or Modern)
                for (int i = 0, length = commands.length; i < length; i++) {
                    if (commands[i].getHandler() != null && a.getPluginId().equals(commands[i].getCommandId())) {
                        ((ShadowAlgorithmHandler) commands[i].getHandler()).run(convert(a));
                        executed = true;
                    }
                }
                // Try to find a FlexiProvider algorithm
                if (!executed) {
                    // $NON-NLS-1$
                    LogUtil.logInfo("Trying to execute FlexiProvider algorithm");
                    for (RegistryType rt : RegistryType.values()) {
                        if (rt.getName().equals(a.getPluginId())) {
                            AlgorithmDescriptor descriptor = new AlgorithmDescriptor(a.getActionName(), rt, null);
                            if (a.getParam("algorithm type").equals(RegistryType.BLOCK_CIPHER.getName())) {
                                // $NON-NLS-1$
                                descriptor = new BlockCipherDescriptor(descriptor.getAlgorithmName(), a.getParam("mode"), a.getParam("padding scheme"), null, // $NON-NLS-1$ //$NON-NLS-2$
                                null);
                            } else if (a.getParam("algorithm type").equals(RegistryType.SECURE_RANDOM.getName())) {
                                // $NON-NLS-1$
                                // TODO Get property "alphabet" from item
                                byte[][] alphabet = null;
                                if (alphabet == null) {
                                    descriptor = new SecureRandomDescriptor(descriptor.getAlgorithmName(), // $NON-NLS-1$
                                    Integer.parseInt(a.getParam("random size")));
                                }
                            }
                            final IFlexiProviderOperation operation = new IntegratorOperation(descriptor);
                            operation.setInput(Messages.InputType);
                            operation.setOutput(Messages.StartHandler_6);
                            // $NON-NLS-1$
                            operation.setSignature(a.getParam("signature"));
                            if ("encrypt".equals(a.getActionType())) {
                                // $NON-NLS-1$
                                operation.setOperation(OperationType.ENCRYPT);
                            } else if ("decrypt".equals(a.getActionType())) {
                                // $NON-NLS-1$
                                operation.setOperation(OperationType.DECRYPT);
                            } else if ("sign".equals(a.getActionType())) {
                                // $NON-NLS-1$
                                operation.setOperation(OperationType.SIGN);
                            } else if ("verify".equals(a.getActionType())) {
                                // $NON-NLS-1$
                                operation.setOperation(OperationType.VERIFY);
                            } else {
                                operation.setOperation(OperationType.UNKNOWN);
                            }
                            // $NON-NLS-1$
                            String alias = a.getParam("key alias");
                            if (alias != null) {
                                operation.setKeyStoreAlias(new KeyStoreAlias(alias));
                            }
                            // $NON-NLS-1$
                            String password = a.getParam("key password");
                            if (password != null) {
                                operation.setPassword(password.toCharArray());
                            }
                            display.asyncExec(new Runnable() {

                                public void run() {
                                    PerformOperationManager.getInstance().firePerformOperation(operation);
                                }
                            });
                            executed = true;
                        }
                    }
                }
                if (!executed) {
                    throw new Exception(Messages.StartHandler_2 + a.getPluginId());
                }
            } catch (final Exception e) {
                if (ActionsUIPlugin.getDefault().getPreferenceStore().getBoolean(PreferenceConstants.P_IGNORE_ERRORS)) {
                    // $NON-NLS-1$
                    LogUtil.logError(ActionsUIPlugin.PLUGIN_ID, a.getActionName() + ": " + e.getMessage(), e, false);
                    if (!ActionsUIPlugin.getDefault().getPreferenceStore().getBoolean(PreferenceConstants.P_DONT_SHOW_MESSAGES)) {
                        display.syncExec(new Runnable() {

                            public void run() {
                                MessageDialog.openWarning(shell, Messages.StartHandler_3, e.getMessage());
                            }
                        });
                    }
                } else {
                    display.asyncExec(new Runnable() {

                        public void run() {
                            MessageDialog.openError(shell, Messages.StartHandler_3, e.getMessage() + // $NON-NLS-1$
                            Messages.StartHandler_4);
                        }
                    });
                    return Status.CANCEL_STATUS;
                }
            } finally {
                monitor.worked(ac.getSize() - steps);
            }
        }
    }
    monitor.done();
    return Status.OK_STATUS;
}
Also used : KeyStoreAlias(org.jcryptool.crypto.keystore.backend.KeyStoreAlias) RegistryType(org.jcryptool.crypto.flexiprovider.types.RegistryType) ShadowAlgorithmHandler(org.jcryptool.core.operations.algorithm.ShadowAlgorithmHandler) ActionItem(org.jcryptool.actions.core.types.ActionItem) StructuredSelection(org.eclipse.jface.viewers.StructuredSelection) IStructuredSelection(org.eclipse.jface.viewers.IStructuredSelection) AlgorithmDescriptor(org.jcryptool.crypto.flexiprovider.descriptors.algorithms.AlgorithmDescriptor) ActionCascade(org.jcryptool.actions.core.types.ActionCascade) OperationsPlugin(org.jcryptool.core.operations.OperationsPlugin) ExecutionException(org.eclipse.core.commands.ExecutionException) SecureRandomDescriptor(org.jcryptool.crypto.flexiprovider.descriptors.algorithms.SecureRandomDescriptor) CommandInfo(org.jcryptool.core.operations.CommandInfo) BlockCipherDescriptor(org.jcryptool.crypto.flexiprovider.descriptors.algorithms.BlockCipherDescriptor) IntegratorOperation(org.jcryptool.crypto.flexiprovider.integrator.IntegratorOperation) TableViewer(org.eclipse.jface.viewers.TableViewer) IFlexiProviderOperation(org.jcryptool.crypto.flexiprovider.descriptors.IFlexiProviderOperation)

Aggregations

SecureRandomDescriptor (org.jcryptool.crypto.flexiprovider.descriptors.algorithms.SecureRandomDescriptor)4 AlgorithmDescriptor (org.jcryptool.crypto.flexiprovider.descriptors.algorithms.AlgorithmDescriptor)3 BlockCipherDescriptor (org.jcryptool.crypto.flexiprovider.descriptors.algorithms.BlockCipherDescriptor)3 IOException (java.io.IOException)2 ActionItem (org.jcryptool.actions.core.types.ActionItem)2 MessageDigest (de.flexiprovider.api.MessageDigest)1 NoSuchAlgorithmException (de.flexiprovider.api.exceptions.NoSuchAlgorithmException)1 File (java.io.File)1 FileInputStream (java.io.FileInputStream)1 InputStream (java.io.InputStream)1 OutputStream (java.io.OutputStream)1 ExecutionException (org.eclipse.core.commands.ExecutionException)1 IStructuredSelection (org.eclipse.jface.viewers.IStructuredSelection)1 StructuredSelection (org.eclipse.jface.viewers.StructuredSelection)1 TableViewer (org.eclipse.jface.viewers.TableViewer)1 WizardDialog (org.eclipse.jface.wizard.WizardDialog)1 MessageBox (org.eclipse.swt.widgets.MessageBox)1 PartInitException (org.eclipse.ui.PartInitException)1 ICommandService (org.eclipse.ui.commands.ICommandService)1 ActionCascade (org.jcryptool.actions.core.types.ActionCascade)1