List of usage examples for org.bouncycastle.util.encoders Base64 encode
public static byte[] encode(byte[] data)
From source file:net.sf.jguard.ext.authentication.callbacks.CallbackHandlerUtils.java
License:Open Source License
/** * construct a header value to simulate a Basic authentication with the provided credentials. * * @param login// w w w. ja v a2 s .co m * @param password * @param encoding encoding destination scheme. if encoding is null, ISO_8859-1 is used (ISO_LATIN_1). * @return header containing login and pasword in base 64, separated by a colon and encoded. */ public static String buildBasicAuthHeader(String login, String password, String encoding) { if (encoding == null) { encoding = CallbackHandlerUtils.ISO_8859_1; } StringBuffer decodedString = new StringBuffer(); decodedString.append(login); decodedString.append(" : "); decodedString.append(password); String encodedString; try { encodedString = new String(Base64.encode(decodedString.toString().getBytes(encoding))); } catch (UnsupportedEncodingException e) { encodedString = new String(Base64.encode(decodedString.toString().getBytes())); } StringBuffer header = new StringBuffer(); header.append(CallbackHandlerUtils.BASIC); header.append(encodedString); header.append(DOUBLE_EQUALS); return header.toString(); }
From source file:net.sf.keystore_explorer.crypto.csr.pkcs10.Pkcs10Util.java
License:Open Source License
/** * DER encode a CSR and PEM the encoding. * * @return The PEM'd encoding//w w w . j a v a 2 s . co m * @param csr * The CSR * @throws CryptoException * If a problem occurs getting the PEM encoded CSR */ public static String getCsrEncodedDerPem(PKCS10CertificationRequest csr) throws CryptoException { try { // Base 64 encoding of CSR ByteArrayOutputStream baos = new ByteArrayOutputStream(); DEROutputStream deros = new DEROutputStream(baos); deros.writeObject(csr.toASN1Structure().toASN1Primitive()); String tmp = new String(Base64.encode(baos.toByteArray())); // Header String csrStr = BEGIN_CSR_FORM_1 + "\n"; // Limit line lengths between header and footer for (int i = 0; i < tmp.length(); i += MAX_PRINTABLE_ENC_LINE_LENGTH) { int lineLength; if ((i + MAX_PRINTABLE_ENC_LINE_LENGTH) > tmp.length()) { lineLength = (tmp.length() - i); } else { lineLength = MAX_PRINTABLE_ENC_LINE_LENGTH; } csrStr += tmp.substring(i, (i + lineLength)) + "\n"; } // Footer csrStr += END_CSR_FORM_1 + "\n"; return csrStr; } catch (IOException ex) { throw new CryptoException(res.getString("NoPemPkcs10Csr.exception.message"), ex); } }
From source file:net.sf.keystore_explorer.crypto.csr.spkac.Spkac.java
License:Open Source License
/** * Output SPKAC.// w w w . j a v a 2 s . c o m * * @param os * Output stream * @throws IOException * If an I/O problem occurs * @throws SpkacException * If output fails */ public void output(OutputStream os) throws IOException, SpkacException { OutputStreamWriter osw = null; try { osw = new OutputStreamWriter(os); outputProperty(osw, SPKAC_PROPERTY, new String(Base64.encode(createSignedPublicKeyAndChallenge().getEncoded(ASN1Encoding.DER)))); outputProperty(osw, CN_PROPERTY, subject.getCN()); outputProperty(osw, OU_PROPERTY, subject.getOU()); outputProperty(osw, O_PROPERTY, subject.getO()); outputProperty(osw, L_PROPERTY, subject.getL()); outputProperty(osw, ST_PROPERTY, subject.getST()); outputProperty(osw, C_PROPERTY, subject.getC()); } catch (IOException ex) { throw new SpkacException(res.getString("NoOutputSpkac.exception.message"), ex); } finally { IOUtils.closeQuietly(osw); } }
From source file:net.sf.keystore_explorer.crypto.signing.JarSigner.java
License:Open Source License
/** * Sign a JAR file outputting the signed JAR to a different file. * * @param jarFile//ww w. jav a 2s . c om * JAR file to sign * @param signedJarFile * Output file for signed JAR * @param privateKey * Private key to sign with * @param certificateChain * Certificate chain for private key * @param signatureType * Signature type * @param signatureName * Signature name * @param signer * Signer * @param digestType * Digest type * @param tsaUrl * TSA URL * @throws IOException * If an I/O problem occurs while signing the JAR file * @throws CryptoException * If a crypto problem occurs while signing the JAR file */ public static void sign(File jarFile, File signedJarFile, PrivateKey privateKey, X509Certificate[] certificateChain, SignatureType signatureType, String signatureName, String signer, DigestType digestType, String tsaUrl, Provider provider) throws IOException, CryptoException { JarFile jar = null; JarOutputStream jos = null; try { // Replace illegal characters in signature name signatureName = convertSignatureName(signatureName); // Create Jar File accessor for JAR to be signed jar = new JarFile(jarFile); // Write manifest content to here StringBuilder sbManifest = new StringBuilder(); // Write out main attributes to manifest String manifestMainAttrs = getManifestMainAttrs(jar, signer); sbManifest.append(manifestMainAttrs); // Write out all entries' attributes to manifest String entryManifestAttrs = getManifestEntriesAttrs(jar); if (entryManifestAttrs.length() > 0) { // Only output if there are any sbManifest.append(entryManifestAttrs); sbManifest.append(CRLF); } // Write signature file to here StringBuilder sbSf = new StringBuilder(); // Write out digests to manifest and signature file // Sign each JAR entry... for (Enumeration<?> jarEntries = jar.entries(); jarEntries.hasMoreElements();) { JarEntry jarEntry = (JarEntry) jarEntries.nextElement(); if (!jarEntry.isDirectory()) // Ignore directories { if (!ignoreJarEntry(jarEntry)) // Ignore some entries (existing signature files) { // Get the digest of the entry as manifest attributes String manifestEntry = getDigestManifestAttrs(jar, jarEntry, digestType); // Add it to the manifest string buffer sbManifest.append(manifestEntry); // Get the digest of manifest entries created above byte[] mdSf = DigestUtil.getMessageDigest(manifestEntry.getBytes(), digestType); byte[] mdSf64 = Base64.encode(mdSf); String mdSf64Str = new String(mdSf64); // Write this digest as entries in signature file sbSf.append(createAttributeText(NAME_ATTR, jarEntry.getName())); sbSf.append(CRLF); sbSf.append(createAttributeText(MessageFormat.format(DIGEST_ATTR, digestType.jce()), mdSf64Str)); sbSf.append(CRLF); sbSf.append(CRLF); } } } // Manifest file complete - get base 64 encoded digest of its content for inclusion in signature file byte[] manifest = sbManifest.toString().getBytes(); byte[] digestMf = DigestUtil.getMessageDigest(manifest, digestType); String digestMfStr = new String(Base64.encode(digestMf)); // Get base 64 encoded digest of manifest's main attributes for inclusion in signature file byte[] mainfestMainAttrs = manifestMainAttrs.getBytes(); byte[] digestMfMainAttrs = DigestUtil.getMessageDigest(mainfestMainAttrs, digestType); String digestMfMainAttrsStr = new String(Base64.encode(digestMfMainAttrs)); // Write out Manifest Digest, Created By and Signature Version to start of signature file sbSf.insert(0, CRLF); sbSf.insert(0, CRLF); sbSf.insert(0, createAttributeText(MessageFormat.format(DIGEST_MANIFEST_ATTR, digestType.jce()), digestMfStr)); sbSf.insert(0, CRLF); sbSf.insert(0, createAttributeText( MessageFormat.format(DIGEST_MANIFEST_MAIN_ATTRIBUTES_ATTR, digestType.jce()), digestMfMainAttrsStr)); sbSf.insert(0, CRLF); sbSf.insert(0, createAttributeText(CREATED_BY_ATTR, signer)); sbSf.insert(0, CRLF); sbSf.insert(0, createAttributeText(SIGNATURE_VERSION_ATTR, SIGNATURE_VERSION)); // Signature file complete byte[] sf = sbSf.toString().getBytes(); // Create output stream to write signed JAR jos = new JarOutputStream(new FileOutputStream(signedJarFile)); // Write JAR files from JAR to be signed to signed JAR writeJarEntries(jar, jos, signatureName); // Write manifest to signed JAR writeManifest(manifest, jos); // Write signature file to signed JAR writeSignatureFile(sf, signatureName, jos); // Create signature block and write it out to signed JAR byte[] sigBlock = createSignatureBlock(sf, privateKey, certificateChain, signatureType, tsaUrl, provider); writeSignatureBlock(sigBlock, signatureType, signatureName, jos); } finally { IOUtils.closeQuietly(jar); IOUtils.closeQuietly(jos); } }
From source file:net.sf.keystore_explorer.crypto.signing.JarSigner.java
License:Open Source License
private static String getDigestManifestAttrs(JarFile jar, JarEntry jarEntry, DigestType digestType) throws IOException, CryptoException { InputStream jis = null;//w w w. j a v a 2 s . c o m try { // Get input stream to JAR entry's content jis = jar.getInputStream(jarEntry); // Get the digest of content in Base64 byte[] md = DigestUtil.getMessageDigest(jis, digestType); byte[] md64 = Base64.encode(md); String md64Str = new String(md64); // Write manifest entries for JARs digest StringBuilder sbManifestEntry = new StringBuilder(); sbManifestEntry.append(createAttributeText(NAME_ATTR, jarEntry.getName())); sbManifestEntry.append(CRLF); sbManifestEntry .append(createAttributeText(MessageFormat.format(DIGEST_ATTR, digestType.jce()), md64Str)); sbManifestEntry.append(CRLF); sbManifestEntry.append(CRLF); return sbManifestEntry.toString(); } finally { IOUtils.closeQuietly(jis); } }
From source file:net.sf.keystore_explorer.crypto.signing.MidletSigner.java
License:Open Source License
/** * Sign a JAD file outputting the modified JAD to a different file. * * @param jadFile/*from w ww .j a v a2s . co m*/ * JAD file * @param outputJadFile * Output JAD file * @param jarFile * JAR file * @param privateKey * Private RSA key to sign with * @param certificateChain * Certificate chain for private key * @param certificateNumber * Certificate number * @throws IOException * If an I/O problem occurs while signing the MIDlet * @throws CryptoException * If a crypto problem occurs while signing the MIDlet */ public static void sign(File jadFile, File outputJadFile, File jarFile, RSAPrivateKey privateKey, X509Certificate[] certificateChain, int certificateNumber) throws IOException, CryptoException { Properties jadProperties = readJadFile(jadFile); Properties newJadProperties = new Properties(); // Copy over existing attrs (excepting digest and any certificates at // provided number) for (Enumeration enumPropNames = jadProperties.propertyNames(); enumPropNames.hasMoreElements();) { String propName = (String) enumPropNames.nextElement(); // Ignore digest attr if (propName.equals(MIDLET_JAR_RSA_SHA1_ATTR)) { continue; } // Ignore certificates at provided number if (propName.startsWith(MessageFormat.format(SUB_MIDLET_CERTIFICATE_ATTR, certificateNumber))) { continue; } newJadProperties.put(propName, jadProperties.getProperty(propName)); } // Get certificate attrs for (int i = 0; i < certificateChain.length; i++) { X509Certificate certificate = certificateChain[i]; String base64Cert = null; try { base64Cert = new String(Base64.encode(certificate.getEncoded())); } catch (CertificateEncodingException ex) { throw new CryptoException(res.getString("Base64CertificateFailed.exception.message"), ex); } String midletCertificateAttr = MessageFormat.format(MIDLET_CERTIFICATE_ATTR, certificateNumber, (i + 1)); newJadProperties.put(midletCertificateAttr, base64Cert); } // Get signed Base 64 SHA-1 digest of JAR file as attr byte[] signedJarDigest = signJarDigest(jarFile, privateKey); String base64SignedJarDigest = new String(Base64.encode(signedJarDigest)); newJadProperties.put(MIDLET_JAR_RSA_SHA1_ATTR, base64SignedJarDigest); // Sort properties alphabetically TreeMap<String, String> sortedJadProperties = new TreeMap<String, String>(); for (Enumeration names = newJadProperties.propertyNames(); names.hasMoreElements();) { String name = (String) names.nextElement(); String value = newJadProperties.getProperty(name); sortedJadProperties.put(name, value); } // Write out new JAD properties to JAD file FileWriter fw = null; try { fw = new FileWriter(outputJadFile); for (Iterator itrSorted = sortedJadProperties.entrySet().iterator(); itrSorted.hasNext();) { Map.Entry property = (Map.Entry) itrSorted.next(); fw.write(MessageFormat.format(JAD_ATTR_TEMPLATE, property.getKey(), property.getValue())); fw.write(CRLF); } } finally { IOUtils.closeQuietly(fw); } }
From source file:net.sf.keystore_explorer.utilities.pem.PemUtil.java
License:Open Source License
/** * Encode the supplied information as PEM. * * @param pemInfo// w w w .ja v a 2 s . c om * PEM Information * @return PEM encoding */ public static String encode(PemInfo pemInfo) { StringBuffer sbPem = new StringBuffer(); // Ouput header sbPem.append("-----BEGIN "); sbPem.append(pemInfo.getType()); sbPem.append("-----"); sbPem.append("\n"); // Output any header attributes PemAttributes attributes = pemInfo.getAttributes(); if (attributes != null && attributes.size() > 0) { for (PemAttribute attribute : attributes.values()) { sbPem.append(attribute); sbPem.append('\n'); } // Empty line separator between attributes and content sbPem.append('\n'); } // Output content String base64 = new String(Base64.encode(pemInfo.getContent())); // Limit line lengths for (int i = 0; i < base64.length(); i += MAX_PRINTABLE_ENCODING_LINE_LENGTH) { int lineLength; if (i + MAX_PRINTABLE_ENCODING_LINE_LENGTH > base64.length()) { lineLength = base64.length() - i; } else { lineLength = MAX_PRINTABLE_ENCODING_LINE_LENGTH; } sbPem.append(base64.substring(i, i + lineLength)); sbPem.append("\n"); } // Output footer sbPem.append("-----END "); sbPem.append(pemInfo.getType()); sbPem.append("-----"); sbPem.append("\n"); return sbPem.toString(); }
From source file:net.sportics.dni.rt.client.microedition.net.SrtsApi.java
License:Open Source License
final String encodePassword(final String sid, final String password) { try {/*w ww .j av a 2s . c o m*/ final Digest digester = new SHA256Digest(); final byte[] asArray = Strings.toUTF8ByteArray(password); digester.update(asArray, 0, asArray.length); final int length = digester.getDigestSize(); final byte[] digest = new byte[length]; digester.doFinal(digest, 0); final byte[] hex = Hex.encode(digest); final String hexString = new String(hex, USASCII_ENC); final String auth = sid + ":" + hexString; LOG.debug("pwd as auth: " + auth); final byte[] asBytes = auth.getBytes(USASCII_ENC); final byte[] base64 = Base64.encode(asBytes); final String base64String = new String(base64, USASCII_ENC); LOG.debug("auth as base64: " + base64String); return base64String; } catch (final UnsupportedEncodingException e) { throw new RuntimeException("Unsupported encoding US-ASCII"); } }
From source file:nl.uva.vlet.grid.ssl.PrivateKeyReader.java
License:Apache License
public static String getPEM(PrivateKey inKey) { byte bytes[] = getEncoded(inKey); StringBuffer buffer = new StringBuffer(); if (inKey instanceof RSAPrivateKey) { buffer.append("-----BEGIN RSA PRIVATE KEY-----\n"); String keyPEM = new String(Base64.encode(bytes)); for (int i = 0; i < keyPEM.length(); i += 64) { if (keyPEM.length() < i + 64) buffer.append(keyPEM.substring(i, keyPEM.length())); else/*from w w w . j ava 2 s. c o m*/ buffer.append(keyPEM.substring(i, i + 64)); buffer.append("\n"); } buffer.append("-----END RSA PRIVATE KEY-----\n"); return buffer.toString(); } else { throw new IllegalArgumentException((new StringBuilder()).append( "Trying to get PEM format string of non-RSA private key, while only RSA is supported. Class was: ") .append(inKey.getClass().getName()).toString()); } }
From source file:no.difi.oxalis.as2.util.SignedMimeMessage.java
License:EUPL
public Mic calculateMic(SMimeDigestMethod algorithm) { try {/*from w w w. j a v a 2 s . c o m*/ MessageDigest messageDigest = BCHelper.getMessageDigest(algorithm.getAlgorithm()); MimeMultipart mimeMultipart = (MimeMultipart) mimeMessage.getContent(); BodyPart bodyPart = mimeMultipart.getBodyPart(0); ByteArrayOutputStream baos = new ByteArrayOutputStream(); bodyPart.writeTo(baos); // Writes the entire contents of first multipart, including the MIME headers byte[] content = baos.toByteArray(); messageDigest.update(content); String digestAsString = new String(Base64.encode(messageDigest.digest())); return new Mic(digestAsString, algorithm); } catch (NoSuchAlgorithmException e) { throw new IllegalStateException(algorithm.getIdentifier() + " not found", e); } catch (IOException e) { throw new IllegalStateException("Unable to read data from digest input. " + e.getMessage(), e); } catch (MessagingException e) { throw new IllegalStateException("Unable to handle mime body part. " + e.getMessage(), e); } }