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.indivica.olis.Driver.java

License:Open Source License

public static String signData(String data) {
    X509Certificate cert = null;//from ww  w.  j a  va  2 s .c o  m
    PrivateKey priv = null;
    KeyStore keystore = null;
    String pwd = "Olis2011";
    String result = null;
    try {
        Security.addProvider(new BouncyCastleProvider());

        keystore = KeyStore.getInstance("PKCS12", "SunJSSE");
        // Load the keystore
        keystore.load(new FileInputStream(OscarProperties.getInstance().getProperty("olis_keystore")),
                pwd.toCharArray());

        Enumeration e = keystore.aliases();
        String name = "";

        if (e != null) {
            while (e.hasMoreElements()) {
                String n = (String) e.nextElement();
                if (keystore.isKeyEntry(n)) {
                    name = n;
                }
            }
        }

        // Get the private key and the certificate
        priv = (PrivateKey) keystore.getKey(name, pwd.toCharArray());
        cert = (X509Certificate) keystore.getCertificate(name);

        // I'm not sure if this is necessary

        Certificate[] certChain = keystore.getCertificateChain(name);
        ArrayList<Certificate> certList = new ArrayList<Certificate>();
        certList.add(cert);
        CertStore certs = null;

        certs = CertStore.getInstance("Collection", new CollectionCertStoreParameters(certList), "BC");

        // Encrypt data
        CMSSignedDataGenerator sgen = new CMSSignedDataGenerator();

        // What digest algorithm i must use? SHA1? MD5? RSA?...
        DefaultSignedAttributeTableGenerator attributeGenerator = new DefaultSignedAttributeTableGenerator();
        sgen.addSigner(priv, cert, CMSSignedDataGenerator.DIGEST_SHA1, attributeGenerator, null);

        // I'm not sure this is necessary
        sgen.addCertificatesAndCRLs(certs);

        // I think that the 2nd parameter need to be false (detached form)
        CMSSignedData csd = sgen.generate(new CMSProcessableByteArray(data.getBytes()), true, "BC");

        byte[] signedData = csd.getEncoded();
        byte[] signedDataB64 = Base64.encode(signedData);

        result = new String(signedDataB64);

    } catch (Exception e) {
        MiscUtils.getLogger().error("Can't sign HL7 message for OLIS", e);
    }
    return result;
}

From source file:com.jlocksmith.util.CertificateUtil.java

License:Open Source License

/**
 * Generate PKCS10 CSR/*from  ww w  . j  ava 2 s.c  o  m*/
 * 
 * @param cert X590 Certificate
 * @param privateKey Private Key
 * @param path File Path
 * 
 * @return String
 * @throws Exception
 */
public static void generatePKCS10CSR(X509Certificate cert, PrivateKey privateKey, String path)
        throws Exception {
    X509Name subject = new X509Name(cert.getSubjectDN().toString());

    PKCS10CertificationRequest csr = new PKCS10CertificationRequest(cert.getSigAlgName(), subject,
            cert.getPublicKey(), null, privateKey);

    // Verify CSR
    csr.verify();

    // Get Base 64 encoding of CSR
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    DEROutputStream dos = new DEROutputStream(baos);
    dos.writeObject(csr.getDERObject());
    String sTmp = new String(Base64.encode(baos.toByteArray()));

    // CSR Header
    String csrText = BEGIN_CERT_REQUEST + "\n";

    // Wrap lines
    for (int iCnt = 0; iCnt < sTmp.length(); iCnt += CERT_REQ_LINE_LENGTH) {
        int iLineLength;

        if ((iCnt + CERT_REQ_LINE_LENGTH) > sTmp.length()) {
            iLineLength = sTmp.length() - iCnt;
        } else {
            iLineLength = CERT_REQ_LINE_LENGTH;
        }

        csrText += sTmp.substring(iCnt, iCnt + iLineLength) + "\n";
    }

    // CSR Footer
    csrText += END_CERT_REQUEST + "\n";

    // Write it out to file
    FileWriter fw = null;

    try {
        fw = new FileWriter(path);
        fw.write(csrText);
    } catch (Exception err) {
        throw err;
    } finally {
        if (fw != null) {
            try {
                fw.close();
            } catch (IOException ex) {
            }
        }
    }
}

From source file:com.joyent.http.signature.google.httpclient.RequestHttpSigner.java

License:Open Source License

/**
 * Signs an arbitrary URL using the Manta-compatible HTTP signature
 * method.//  w w  w.  ja  v a2  s  . c o  m
 *
 * Deprecated: Use method provided inside the Java Manta SDK.
 *
 * @param uri URI with no query pointing to a downloadable resource
 * @param method HTTP request method to be used in the signature
 * @param expires epoch time in seconds when the resource will no longer
 *                be available
 * @return a signed version of the input URI
 * @throws IOException thrown when we can't sign or read char data
 */
@Deprecated
public URI signURI(final URI uri, final String method, final long expires) throws IOException {
    Objects.requireNonNull(method, "Method must be present");
    Objects.requireNonNull(uri, "URI must be present");

    if (uri.getQuery() != null && !uri.getQuery().isEmpty()) {
        throw new IllegalArgumentException("Query must be empty");
    }

    final String charset = "UTF-8";
    final String algorithm = signer.get().getHttpHeaderAlgorithm().toUpperCase();
    final String keyId = String.format("/%s/keys/%s", getLogin(),
            KeyFingerprinter.md5Fingerprint(getKeyPair()));
    final String keyIdEncoded = URLEncoder.encode(keyId, charset);

    StringBuilder sigText = new StringBuilder();
    sigText.append(method).append("\n").append(uri.getHost()).append("\n").append(uri.getPath()).append("\n")
            .append("algorithm=").append(algorithm).append("&").append("expires=").append(expires).append("&")
            .append("keyId=").append(keyIdEncoded);

    StringBuilder request = new StringBuilder();
    final byte[] sigBytes = sigText.toString().getBytes(StandardCharsets.US_ASCII);
    final byte[] signed = signer.get().sign(getLogin(), getKeyPair(), sigBytes);
    final String encoded = new String(Base64.encode(signed), charset);
    final String urlEncoded = URLEncoder.encode(encoded, charset);

    request.append(uri).append("?").append("algorithm=").append(algorithm).append("&").append("expires=")
            .append(expires).append("&").append("keyId=").append(keyIdEncoded).append("&").append("signature=")
            .append(urlEncoded);

    return URI.create(request.toString());
}

From source file:com.joyent.http.signature.Signer.java

License:Open Source License

/**
 * Generate a signature for an authorization HTTP header.
 *
 * @param login Account/login name//from ww w. j  a  va  2s .  c o m
 * @param keyPair public/private keypair
 * @param date Date as RFC 822 compliant string
 * @return value to Authorization header
 */
public String createAuthorizationHeader(final String login, final KeyPair keyPair, final String date) {
    Objects.requireNonNull(login, "Login must be present");
    Objects.requireNonNull(keyPair, "Keypair must be present");

    try {
        signature.initSign(keyPair.getPrivate());
        final String signingString = String.format(AUTHZ_SIGNING_STRING, date);
        signature.update(signingString.getBytes(StandardCharsets.UTF_8));
        final byte[] signedDate = signature.sign();
        final byte[] encodedSignedDate = Base64.encode(signedDate);
        final String fingerprint = KeyFingerprinter.md5Fingerprint(keyPair);

        return String.format(AUTHZ_HEADER, login, fingerprint, httpHeaderAlgorithm,
                new String(encodedSignedDate, StandardCharsets.US_ASCII));
    } catch (final InvalidKeyException e) {
        throw new CryptoException("invalid key", e);
    } catch (final SignatureException e) {
        throw new CryptoException("invalid signature", e);
    }
}

From source file:com.joyent.manta.client.UriSigner.java

License:Open Source License

/**
 * Signs an arbitrary URL using the Manta-compatible HTTP signature
 * method.//from  w w w .  j a v  a 2 s  .  co m
 *
 * @param uri URI with no query pointing to a downloadable resource
 * @param method HTTP request method to be used in the signature
 * @param expires epoch time in seconds when the resource will no longer
 *                be available
 * @return a signed version of the input URI
 * @throws IOException thrown when we can't sign or read char data
 */
public URI signURI(final URI uri, final String method, final long expires) throws IOException {
    Validate.notNull(method, "Method must not be null");
    Validate.notNull(uri, "URI must not be null");

    Validate.isTrue(StringUtils.isEmpty(uri.getQuery()), "Query must be null or empty. URI: %s", uri);

    final ThreadLocalSigner signer = authConfig.getSigner();

    final String charset = "UTF-8";
    final String algorithm = signer.get().getHttpHeaderAlgorithm().toUpperCase();
    final String keyId = String.format("/%s/keys/%s", authConfig.getMantaUser(),
            KeyFingerprinter.md5Fingerprint(authConfig.getKeyPair()));

    final String keyIdEncoded = URLEncoder.encode(keyId, charset);

    StringBuilder sigText = new StringBuilder();
    sigText.append(method).append(StringUtils.LF).append(uri.getHost()).append(StringUtils.LF)
            .append(uri.getRawPath()).append(StringUtils.LF).append("algorithm=").append(algorithm).append("&")
            .append("expires=").append(expires).append("&").append("keyId=").append(keyIdEncoded);

    StringBuilder request = new StringBuilder();
    final byte[] sigBytes = sigText.toString().getBytes(StandardCharsets.UTF_8);

    // first parameter isn't actually used for anything, just checked for nullness
    final byte[] signed = signer.get().sign("", authConfig.getKeyPair(), sigBytes);

    final String encoded = new String(Base64.encode(signed), charset);
    final String urlEncoded = URLEncoder.encode(encoded, charset);

    request.append(uri).append("?").append("algorithm=").append(algorithm).append("&").append("expires=")
            .append(expires).append("&").append("keyId=").append(keyIdEncoded).append("&").append("signature=")
            .append(urlEncoded);

    return URI.create(request.toString());
}

From source file:com.jwm123.loggly.reporter.TripleDesCipher.java

License:Apache License

public String encode(String str)
        throws IllegalBlockSizeException, BadPaddingException, UnsupportedEncodingException {
    return new String(Base64.encode(encrypter.doFinal(str.getBytes("UTF8"))));
}

From source file:com.jwm123.loggly.reporter.TripleDesCipher.java

License:Apache License

private void getKey() throws NoSuchAlgorithmException, IOException {
    File keyFile = appDir.getFileDir(keyPath);
    if (keyFile.exists()) {
        key = Base64.decode(FileUtils.readFileToString(keyFile));
    } else {/*from   w w  w . j  ava2  s.  c om*/
        KeyGenerator generator = KeyGenerator.getInstance("DESede");
        SecretKey desKey = generator.generateKey();
        key = desKey.getEncoded();
        FileUtils.writeStringToFile(keyFile, new String(Base64.encode(key)));
    }

}

From source file:com.leon.utils.sign.v2.SignApk.java

License:Apache License

/**
 * Add the hash(es) of every file to the manifest, creating it if
 * necessary./* w  ww .  ja v  a  2 s .c  o m*/
 */
private static Manifest addDigestsToManifest(JarFile jar, int hashes)
        throws IOException, GeneralSecurityException {
    Manifest input = jar.getManifest();
    Manifest output = new Manifest();
    Attributes main = output.getMainAttributes();
    if (input != null) {
        main.putAll(input.getMainAttributes());
    } else {
        main.putValue("Manifest-Version", "1.0");
        main.putValue("Created-By", "1.0 (Android SignApk)");
    }

    MessageDigest md_sha1 = null;
    MessageDigest md_sha256 = null;
    if ((hashes & USE_SHA1) != 0) {
        md_sha1 = MessageDigest.getInstance("SHA1");
    }
    if ((hashes & USE_SHA256) != 0) {
        md_sha256 = MessageDigest.getInstance("SHA256");
    }

    byte[] buffer = new byte[4096];
    int num;

    // We sort the input entries by name, and add them to the
    // output manifest in sorted order.  We expect that the output
    // map will be deterministic.

    TreeMap<String, JarEntry> byName = new TreeMap<String, JarEntry>();

    for (Enumeration<JarEntry> e = jar.entries(); e.hasMoreElements();) {
        JarEntry entry = e.nextElement();
        byName.put(entry.getName(), entry);
    }

    for (JarEntry entry : byName.values()) {
        String name = entry.getName();
        if (!entry.isDirectory() && (stripPattern == null || !stripPattern.matcher(name).matches())) {
            InputStream data = jar.getInputStream(entry);
            while ((num = data.read(buffer)) > 0) {
                if (md_sha1 != null)
                    md_sha1.update(buffer, 0, num);
                if (md_sha256 != null)
                    md_sha256.update(buffer, 0, num);
            }

            Attributes attr = null;
            if (input != null)
                attr = input.getAttributes(name);
            attr = attr != null ? new Attributes(attr) : new Attributes();
            // Remove any previously computed digests from this entry's attributes.
            for (Iterator<Object> i = attr.keySet().iterator(); i.hasNext();) {
                Object key = i.next();
                if (!(key instanceof Attributes.Name)) {
                    continue;
                }
                String attributeNameLowerCase = ((Attributes.Name) key).toString().toLowerCase(Locale.US);
                if (attributeNameLowerCase.endsWith("-digest")) {
                    i.remove();
                }
            }
            // Add SHA-1 digest if requested
            if (md_sha1 != null) {
                attr.putValue("SHA1-Digest", new String(Base64.encode(md_sha1.digest()), "ASCII"));
            }
            // Add SHA-256 digest if requested
            if (md_sha256 != null) {
                attr.putValue("SHA-256-Digest", new String(Base64.encode(md_sha256.digest()), "ASCII"));
            }
            output.getEntries().put(name, attr);
        }
    }

    return output;
}

From source file:com.leon.utils.sign.v2.SignApk.java

License:Apache License

/** Write a .SF file with a digest of the specified manifest. */
private static void writeSignatureFile(Manifest manifest, OutputStream out, int hash,
        boolean additionallySignedUsingAnApkSignatureScheme) throws IOException, GeneralSecurityException {
    Manifest sf = new Manifest();
    Attributes main = sf.getMainAttributes();
    main.putValue("Signature-Version", "1.0");
    main.putValue("Created-By", "1.0 (Android SignApk)");
    if (additionallySignedUsingAnApkSignatureScheme) {
        // Add APK Signature Scheme v2 signature stripping protection.
        // This attribute indicates that this APK is supposed to have been signed using one or
        // more APK-specific signature schemes in addition to the standard JAR signature scheme
        // used by this code. APK signature verifier should reject the APK if it does not
        // contain a signature for the signature scheme the verifier prefers out of this set.
        main.putValue(ApkSignerV2.SF_ATTRIBUTE_ANDROID_APK_SIGNED_NAME,
                ApkSignerV2.SF_ATTRIBUTE_ANDROID_APK_SIGNED_VALUE);
    }/*from  w w  w.j a  va 2s  .  c o m*/

    MessageDigest md = MessageDigest.getInstance(hash == USE_SHA256 ? "SHA256" : "SHA1");
    PrintStream print = new PrintStream(new DigestOutputStream(new ByteArrayOutputStream(), md), true, "UTF-8");

    // Digest of the entire manifest MANIFEST.MF??????Base64?
    manifest.write(print);
    print.flush();
    main.putValue(hash == USE_SHA256 ? "SHA-256-Digest-Manifest" : "SHA1-Digest-Manifest",
            new String(Base64.encode(md.digest()), "ASCII"));

    Map<String, Attributes> entries = manifest.getEntries();//manifestMANIFEST.MFManifest
    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();
        //MANIFEST.MF??????Base64?
        Attributes sfAttr = new Attributes();
        sfAttr.putValue(hash == USE_SHA256 ? "SHA-256-Digest" : "SHA1-Digest",
                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.logicoy.pdmp.pmpi.crypto.EncryptionClient.java

License:Apache License

public String generatePassword() {
    //There is a max length that the password can be based on the size of the RSA key.
    //PMPI recommends everyone uses 2048 bit RSA keys.  But if a PMP uses a shorter key
    //then you have to be careful how many bytes you make your password. Each byte can be
    //thought off as one ascii character.
    int min_bytes = 50;
    int max_bytes = 64;
    SecureRandom rngCsp = new SecureRandom();
    byte[] howmanybytes = new byte[1];
    rngCsp.nextBytes(howmanybytes);/*  ww w. j  a  v  a2  s  . c  om*/
    Random r = new Random(howmanybytes[0]);
    //byte[] randomNumber = new byte[r.Next(min_bytes,max_bytes)]; C#DIFF
    //byte[] randomNumber = new byte[r.nextInt(max_bytes)];
    byte[] randomNumber = new byte[(r.nextInt(max_bytes - min_bytes) + min_bytes)];
    rngCsp.nextBytes(randomNumber);

    //Base 64 so that all bytes can be represented in text.
    String password = new String(Base64.encode(randomNumber));

    logger.info("password length = " + password.length());
    return password;
}