Example usage for org.bouncycastle.util.encoders Base64 encode

List of usage examples for org.bouncycastle.util.encoders Base64 encode

Introduction

In this page you can find the example usage for org.bouncycastle.util.encoders Base64 encode.

Prototype

public static byte[] encode(byte[] data) 

Source Link

Document

encode the input data producing a base 64 encoded byte array.

Usage

From source file:com.logicoy.pdmp.pmpi.crypto.EncryptionClient.java

License:Apache License

public String getAES256Cipher(String inputText, String password, boolean decrypt) {
    KeyIVGenerator derivedFromPassword = new KeyIVGenerator(password);
    // Set up key and IV these are derived from the password, using MD5 very simple. See class details.

    try {/*from   w w w  .  j  a  v  a 2 s  . c  o  m*/
        byte[] buffer;
        //Sting to encrypt
        if (!decrypt) {
            buffer = inputText.getBytes(Charset.forName("UTF-8"));
        } else {
            buffer = Base64.decode(inputText);
        }

        // Aes Encryption
        BlockCipher blockCipher = new AESEngine();

        // Mode CBC
        blockCipher = new CBCBlockCipher(blockCipher);

        BlockCipherPadding padding = new PKCS7Padding();

        // Get our Cipher.
        PaddedBufferedBlockCipher cipher = new PaddedBufferedBlockCipher(blockCipher, padding);

        // Initialize the cipher.
        cipher.init(!decrypt, new ParametersWithIV(new KeyParameter(derivedFromPassword.getKey()),
                derivedFromPassword.getIV()));
        //byte[] bytes_output = cipher.doFinal(buffer,0);
        byte bytes_output[] = new byte[cipher.getOutputSize(buffer.length)];
        int len = cipher.processBytes(buffer, 0, buffer.length, bytes_output, 0);
        int noOfBytesCopied = cipher.doFinal(bytes_output, len);

        if (!decrypt) {
            //Return base 64 encrypted text.
            return new String(Base64.encode(bytes_output), Charset.forName("UTF-8"));
            //return Convert.ToBase64String(bytes_output, Base64FormattingOptions.InsertLineBreaks);
        } else {
            //Return plain text.
            return new String(bytes_output, Charset.forName("UTF-8"));
        }

    } catch (Exception e) {
        logger.severe(" Failure attempting to AES256 encrypt/decrypt the xml " + e.toString());
        e.printStackTrace();
        throw new RuntimeException(" Failure attempting AES256 " + (decrypt ? "decryption" : "encryption")
                + " :" + e.getMessage());
    } finally {
        derivedFromPassword.Clean();
    }

}

From source file:com.logicoy.pdmp.pmpi.crypto.EncryptionClient.java

License:Apache License

public String rsaEncryptPassword(String publicKeyInPEM, String password) {
    String encrypted = "";
    try {//from  w w  w.  jav  a2 s.c  o  m
        RSAKeyParameters rsaPublicKey;
        Reader reader = new StringReader(publicKeyInPEM);
        PemObject pemObj = new PemReader(reader).readPemObject();

        rsaPublicKey = (RSAKeyParameters) PublicKeyFactory.createKey(pemObj.getContent());

        byte[] bytesToEncrypt = password.getBytes(Charset.forName("UTF-8"));

        PKCS1Encoding encryptEngine = new PKCS1Encoding(new RSAEngine());
        encryptEngine.init(true, rsaPublicKey);
        encrypted = new String(
                Base64.encode(encryptEngine.processBlock(bytesToEncrypt, 0, bytesToEncrypt.length)),
                Charset.forName("UTF-8"));

    } catch (Exception ex) {
        logger.severe(" Failure attempting to encrypt via RSA.  \r\n PublicKeyInPEM:" + publicKeyInPEM
                + "\r\n Exception : " + ex.toString());
        throw new RuntimeException(
                " Failure attempting to encrypt the RSA encrypted password. See Interface log for more details. Message : "
                        + ex.getMessage());
    }
    return encrypted;

}

From source file:com.mansoor.uncommon.configuration.Convertors.encryption.SymmetricKeyConverter.java

License:Apache License

/**
 * Encrypts the input value using Symmetric Key.
 *
 * @param input input to be encrypted/* ww w.j ava  2  s.c om*/
 * @return encrypted String
 */
public String toString(final SymmetricKeyWrapper input) {
    String enc = null;
    try {
        final IvParameterSpec ips = new IvParameterSpec(new byte[16]);
        cipher.init(Cipher.ENCRYPT_MODE, keySpec, ips);
        final byte[] bytes = input.getPlainText().getBytes();
        final byte[] cipherText = cipher.doFinal(bytes);
        enc = new String(Base64.encode(cipherText));
    } catch (Exception e) {
        Throwables.propertyConversionException("encryption failed", e);
    }
    return enc;
}

From source file:com.mansoor.uncommon.configuration.Convertors.encryption.X509CertConverter.java

License:Apache License

/**
 * Encrypts the value using public key/*from   w  ww  .j  a v  a  2s  . c  o  m*/
 *
 * @param input value to be encrypted
 * @return encrypted String
 */
public String toString(final X509Wrapper input) {
    final String enc;
    try {
        cipher.init(Cipher.ENCRYPT_MODE, publicKey);
        final byte[] cipherText = cipher.doFinal(input.getPlainText().getBytes());
        enc = new String(Base64.encode(cipherText));
    } catch (Exception e) {
        throw new IllegalStateException("Encryption failed", e);
    }
    return enc;
}

From source file:com.miguelpazo.signature.test.SignDataTest.java

public String signDataWithPfx(String data, File certPfx, String pass, File dataSignedFile) throws Exception {
    KeyStore ks = KeyStore.getInstance("pkcs12");
    ks.load(new FileInputStream(certPfx), pass.toCharArray());
    String alias = (String) ks.aliases().nextElement();

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

    Signature signature = Signature.getInstance("SHA1WithRSA", "BC");
    signature.initSign(key);//from  ww w  .j a  v a 2  s  .co  m
    //        signature.update(Base64.encode(data.getBytes()));
    signature.update(data.getBytes());

    //Build CMS
    X509Certificate cert = (X509Certificate) ks.getCertificate(alias);
    List certList = new ArrayList();
    CMSTypedData msg = new CMSProcessableByteArray(signature.sign());
    certList.add(cert);

    Store certs = new JcaCertStore(certList);
    CMSSignedDataGenerator gen = new CMSSignedDataGenerator();
    ContentSigner sha1Signer = new JcaContentSignerBuilder("SHA1WithRSA").setProvider("BC").build(key);
    gen.addSignerInfoGenerator(new JcaSignerInfoGeneratorBuilder(
            new JcaDigestCalculatorProviderBuilder().setProvider("BC").build()).build(sha1Signer, cert));
    gen.addCertificates(certs);

    CMSSignedData sigData = gen.generate(msg, false);
    byte[] dataSigned = Base64.encode(sigData.getEncoded());
    String envelopedData = new String(dataSigned);

    certUtil.exportToFile(envelopedData, dataSignedFile);

    byte[] b = (byte[]) sigData.getSignedContent().getContent();
    String dataEncrypt = new String(Base64.encode(b));

    System.out.println("content => " + dataEncrypt);

    PublicKey pubKey = cert.getPublicKey();
    String dataFinal = certUtil.decryptData(pubKey, dataEncrypt);

    System.out.println(dataEncrypt);
    //        System.out.println(dataFinal);

    return envelopedData;
}

From source file:com.myapp.Test.java

License:Open Source License

/**
 * @param args/*  w w w  . j a v  a2s.  co m*/
 */
public static void main(String[] args) throws Throwable {
    InetAddress netaddr = InetAddress.getLocalHost();
    NetworkInterface intf = NetworkInterface.getByInetAddress(netaddr);
    byte[] address = intf.getHardwareAddress();
    if (intf.isVirtual()) {
        byte[] paddress = intf.getParent().getHardwareAddress();
        if (paddress != null) {
            address = paddress;
            intf = intf.getParent();
        }
    }
    if (address == null) {
        System.out.println("Unable to generate License Request..");
        return;
    }
    if (address.length == 0) {
        System.out.println("Unable to generate License Request..");
        return;
    }
    String str = new String(Base64.encode(address), "UTF-8");

    System.out.println("Machine Address \"" + str + "\". If this is shown as \"\" then we have a problem.");
}

From source file:com.orange.atk.sign.apk.SignedJarBuilder.java

License:Apache License

/** Writes a .SF file with a digest to the manifest. */
private void writeSignatureFile(OutputStream out) throws IOException, GeneralSecurityException {
    Manifest sf = new Manifest();
    Attributes main = sf.getMainAttributes();
    main.putValue("Signature-Version", "1.0");
    main.putValue("Created-By", "1.0 (Android)");

    Base64 base64 = new Base64();
    MessageDigest md = MessageDigest.getInstance(DIGEST_ALGORITHM);
    PrintStream print = new PrintStream(new DigestOutputStream(new ByteArrayOutputStream(), md), true, "UTF-8");

    // Digest of the entire manifest
    mManifest.write(print);/*from   w w w.  j a v a  2  s  .  co  m*/
    print.flush();
    main.putValue(DIGEST_MANIFEST_ATTR, new String(base64.encode(md.digest()), "ASCII"));

    Map<String, Attributes> entries = mManifest.getEntries();
    for (Map.Entry<String, Attributes> entry : entries.entrySet()) {
        // Digest of the manifest stanza for this entry.
        print.print("Name: " + entry.getKey() + "\r\n");
        for (Map.Entry<Object, Object> att : entry.getValue().entrySet()) {
            print.print(att.getKey() + ": " + att.getValue() + "\r\n");
        }
        print.print("\r\n");
        print.flush();

        Attributes sfAttr = new Attributes();
        sfAttr.putValue(DIGEST_ATTR, new String(base64.encode(md.digest()), "ASCII"));
        sf.getEntries().put(entry.getKey(), sfAttr);
    }
    CountOutputStream cout = new CountOutputStream(out);
    sf.write(cout);

    // A bug in the java.util.jar implementation of Android platforms
    // up to version 1.6 will cause a spurious IOException to be thrown
    // if the length of the signature file is a multiple of 1024 bytes.
    // As a workaround, add an extra CRLF in this case.
    if ((cout.size() % 1024) == 0) {
        cout.write('\r');
        cout.write('\n');
    }
}

From source file:com.password.locker.crypto.SecureCryptoImpl.java

License:Open Source License

@Override
public byte[] encrypt(final byte[] plain) {
    synchronized (encryption) {
        try {/*  www. j av a  2 s . c o  m*/
            byte[] data = Base64.encode(plain);
            return encryption.doFinal(data);
        } catch (IllegalBlockSizeException e) {
            ExceptionUtils.fatalError(SecureCryptoImpl.class, e);
        } catch (BadPaddingException e) {
            ExceptionUtils.fatalError(SecureCryptoImpl.class, e);
        }
        return plain;
    }
}

From source file:com.password.locker.crypto.SecureCryptoImpl.java

License:Open Source License

@Override
public String encrypt(final String plain) {
    try {/* w  ww .ja  v  a 2s.  c  o m*/
        byte[] ciphertext = encrypt(plain.getBytes(Constants.ENCODING));
        return new String(Base64.encode(ciphertext), Constants.ENCODING);
    } catch (UnsupportedEncodingException e) {
        ExceptionUtils.fatalError(SecureCryptoImpl.class, e);
    }
    return plain;
}

From source file:com.rapidminer.cryptography.file.AbstractPBFileCryptographyOperator.java

License:Open Source License

@Override
public void doWork() throws OperatorException {

    // first check if output file exists and if overriding is allowed
    if (isParameterSet(PARAMETER_FILE_OUTPUT) && getParameterAsFile(PARAMETER_FILE_OUTPUT).exists()
            && !getParameterAsBoolean(PARAMETER_OVERRIDE)) {
        throw new UserError(this, "file.output_file_already_exists");
    }/*w  w w .j  a va 2s.  co  m*/

    // read input file
    byte[] fileContent = readInputFile();

    // in case of decryption and base64 encoding, decode first
    if (!isEncrypting() && getParameterAsBoolean(PARAMETER_BASE64)) {
        try {
            fileContent = Base64.decode(fileContent);
        } catch (DecoderException e) {
            throw new UserError(this, e, "file.base64_decoding_failed");
        }
    }

    // transform file
    fileContent = transformFile(configureEncryptor(), fileContent);

    // in case of encryption and base64 encoding, decode encrypted output
    if (isEncrypting() && getParameterAsBoolean(PARAMETER_BASE64)) {
        try {
            fileContent = Base64.encode(fileContent);
        } catch (DecoderException e) {
            throw new UserError(this, e, "file.base64_encoding_failed");
        }
    }

    // write encrypted file to output
    try (OutputStream fileOutput = fileOutputHandler.openSelectedFile()) {
        ByteArrayInputStream byteInput = new ByteArrayInputStream(fileContent);
        Tools.copyStreamSynchronously(byteInput, fileOutput, true);
    } catch (IOException e) {
        throw new UserError(this, e, 303, getParameterAsFile(PARAMETER_FILE_OUTPUT), e.getMessage());
    }
}