es.gob.afirma.core.misc.Base64类的使用及代码示例

x33g5p2x  于2022-01-17 转载在 其他  
字(12.0k)|赞(0)|评价(0)|浏览(118)

本文整理了Java中es.gob.afirma.core.misc.Base64类的一些代码示例,展示了Base64类的具体用法。这些代码示例主要来源于Github/Stackoverflow/Maven等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。Base64类的具体详情如下:
包路径:es.gob.afirma.core.misc.Base64
类名称:Base64

Base64介绍

[英]Encodes and decodes to and from Base64 notation.

Homepage: http://iharder.net/base64.

Example:
String encoded = Base64.encode( myByteArray );
byte[] myByteArray = Base64.decode( encoded );

The options parameter, which appears in a few places, is used to pass several pieces of information to the encoder. In the "higher level" methods such as encodeBytes( bytes, options ) the options parameter can be used to indicate such things as not inserting linefeeds, and encoding using the URL-safe and Ordered dialects.

Note, according to RFC3548, Section 2.1, implementations should not add line feeds unless explicitly told to do so. I've got Base64 set to this behavior now, although earlier versions broke lines by default.

The constants defined in Base64 can be OR-ed together to combine options, so you might make a call like this:
String encoded = Base64.encodeBytes( mybytes, Base64.DO_BREAK_LINES );

to compress the data before encoding it and then making the output have newline characters.

Also...
String encoded = Base64.encodeBytes( crazyString.getBytes() );

I am placing this code in the Public Domain. Do with it as you will. This software comes with no guarantees or warranties but with plenty of well-wishing instead! Please visit http://iharder.net/base64 periodically to check for updates or to contribute improvements.
[中]对Base64符号进行编码和解码。
主页:http://iharder.net/base64
例子:
String encoded = Base64.encode( myByteArray );
byte[] myByteArray = Base64.decode( encoded );
选项参数出现在几个地方,用于将多条信息传递给编码器。在“更高级别”的方法中,例如encodeBytes(bytes,options),options参数可用于指示不插入换行符,以及使用URL安全和有序方言进行编码。
注意,根据RFC3548,第2.1节,除非明确要求添加换行符,否则实现不应该添加换行符。我现在已经将Base64设置为这种行为,尽管早期版本在默认情况下会中断。
Base64中定义的常量可以合并或合并在一起以组合选项,因此您可以进行如下调用:
String encoded = Base64.encodeBytes( mybytes, Base64.DO_BREAK_LINES );
在编码数据之前压缩数据,然后使输出具有换行符。
而且
String encoded = Base64.encodeBytes( crazyString.getBytes() );
我将此代码置于公共域中。你想怎么做就怎么做。这个软件没有任何保证或保证,但却有很多美好的愿望!请定期访问http://iharder.net/base64,检查更新或作出改进。

代码示例

代码示例来源:origin: es.gob.afirma/afirma-core

/** Descodifica datos en Base64.
 * @param str Cadena de caracteres en formato Base64
 * @return Datos descodificados
 * @throws java.io.IOException si ocurre cualquier error */
public static byte[] decode(final String str) throws java.io.IOException {
  return decode(str, false);
}

代码示例来源:origin: es.gob.afirma/afirma-keystores-filters

/** {@inheritDoc} */
  @Override
  public boolean matches(final X509Certificate cert) {
    try {
      return this.certEncoded.equals(Base64.encode(cert.getEncoded()));
    } catch (final CertificateEncodingException e) {
      Logger.getLogger("es.gob.afirma").warning( //$NON-NLS-1$
          "No se ha podido codificar el certificado en base 64. Se ignorara: " + e  //$NON-NLS-1$
        );
      return false;
    }
  }
}

代码示例来源:origin: es.gob.afirma/afirma-core-massive

try {
  signs[i] = signer.sign(
    Base64.decode(hashes[i]),
    this.algorithm,
    keyEntry.getPrivateKey(),
signsB64[i] = Base64.encode(signs[i]);

代码示例来源:origin: es.gob.afirma/afirma-crypto-xmlsignature

if (Base64.isBase64(data) && (XMLConstants.BASE64_ENCODING.equals(encoding) || (encoding != null ? encoding : "").toLowerCase().equals("base64"))) { //$NON-NLS-1$ //$NON-NLS-2$
      LOGGER.info("El documento se ha indicado como Base64, se insertara como tal en el XML"); //$NON-NLS-1$
      final byte[] decodedData = Base64.decode(new String(data));
      final MimeHelper mimeTypeHelper = new MimeHelper(decodedData);
      final String tempMimeType = mimeTypeHelper.getMimeType();
      dataElement.setTextContent(Base64.encode(data));
      wasEncodedToBase64 = true;
dataElement.setAttributeNS(null, ENCODING_STR, encoding);
dataElement.setTextContent(Base64.encode(digestValue));
isBase64 = true;

代码示例来源:origin: es.gob.afirma/afirma-core

if (Base64.isBase64(dataSource.getBytes())) {
  Logger.getLogger("es.gob.afirma").info("El contenido a obtener es Base64"); //$NON-NLS-1$ //$NON-NLS-2$
  try {
    return Base64.decode(dataSource.replace("_", "/").replace("-", "+")); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$

代码示例来源:origin: es.gob.afirma/afirma-core

this.policyIdentifierHash =  Base64.encode(
      MessageDigest.getInstance(this.policyIdentifierHashAlgorithm).digest(
          AOUtil.getDataFromInputStream(new URL(identifier).openStream())));
if (!Base64.isBase64(identifierHash.getBytes())) {
  throw new IllegalArgumentException("La huella digital de la politica debe estar en formato Base64"); //$NON-NLS-1$

代码示例来源:origin: es.gob.afirma/afirma-core

final byte[] decodabet = getDecodabet( options );
        outBuffPosn += decode4to3( b4, 0, outBuff, outBuffPosn, options );
        b4Posn = 0;

代码示例来源:origin: es.gob.afirma/afirma-core

final String documentId = Base64.encode(data, true);
  cerChainParamContent = Base64.encode(certChain[0].getEncoded(), true);
try {
  triphaseData = TriphaseData.parser(
    Base64.decode(preSignResult, 0, preSignResult.length, true)
  );
try {
  pkcs1 = new AOPkcs1Signer().sign(
      Base64.decode(tri.getProperty(PROPERTY_NAME_PRESIGN)),
      algorithm,
      key,
  throw new AOException("Error al decodificar la prefirma de los datos", e); //$NON-NLS-1$
tri.addProperty(PROPERTY_NAME_PKCS1_SIGN, Base64.encode(pkcs1));
final String preResultAsBase64 = Base64.encode(
  triphaseData.toString().getBytes(),
  true
  return Base64.decode(stringTrimmedResult.substring((SUCCESS + " NEWID=").length()), true); //$NON-NLS-1$

代码示例来源:origin: es.gob.afirma/afirma-core

/** Descodifica datos en Base64.
 * @param str Cadena de caracteres en formato Base64
 * @param urlSafe Si se establece a <code>true</code> indica que los datos est&aacute;n con un alfabeto Base64
 *                susceptible de ser usado en URL, seg&uacute;n se indica en la seccti&oacute;n 4 de la RFC3548,
 *                si se establece a <code>false</code> los datos deben estar en Base64 normal
 * @return Datos descodificados
 * @throws java.io.IOException si ocurre cualquier error */
public static byte[] decode(final String str, final boolean urlSafe) throws java.io.IOException {
  if( str == null ){
    throw new IllegalArgumentException("Input string was null"); //$NON-NLS-1$
  }
  final byte[] bytes = str.getBytes(PREFERRED_ENCODING);
  return decode( bytes, 0, bytes.length, urlSafe);
}

代码示例来源:origin: es.gob.afirma/afirma-crypto-cadestri-client

final String documentId = Base64.encode(docId, true);
  triphaseData = TriphaseData.parser(Base64.decode(preSignResult, 0, preSignResult.length, true));
final String preResultAsBase64 = Base64.encode(TriphaseDataSigner.doSign(
  new AOPkcs1Signer(),
  algorithm,
  return Base64.decode(stringTrimmedResult.substring((SUCCESS + " NEWID=").length()), true); //$NON-NLS-1$

代码示例来源:origin: es.gob.afirma/afirma-crypto-batch-client

private static String getCertChainAsBase64(final Certificate[] certChain) throws CertificateEncodingException {
  final StringBuilder sb = new StringBuilder();
  for (final Certificate cert : certChain) {
    sb.append(Base64.encode(cert.getEncoded(), true));
    sb.append(";"); //$NON-NLS-1$
  }
  final String ret = sb.toString();
  // Quitamos el ";" final
  return ret.substring(0, ret.length()-1);
}

代码示例来源:origin: es.gob.afirma/afirma-core

/** Convierte una cadena Base64 en un objeto de propiedades.
 * @param base64 Base64 que descodificado es un fichero de propiedades en texto plano.
 * @return Objeto de propiedades.
 * @throws IOException Si hay problemas en el proceso. */
public static Properties base642Properties(final String base64) throws IOException {
  final Properties p = new Properties();
  if (base64 == null || base64.isEmpty()) {
    return p;
  }
  p.load(
  new InputStreamReader(
      new ByteArrayInputStream(Base64.decode(base64)
  ),
  DEFAULT_ENCODING)
  );
  return p;
}

代码示例来源:origin: es.gob.afirma/afirma-core

preSign = Base64.decode(base64PreSign);
signConfig.addProperty(PROPERTY_NAME_PKCS1_SIGN, Base64.encode(pkcs1sign));

代码示例来源:origin: es.gob.afirma/afirma-core

/** Convierte un objeto de propiedades en una cadena Base64 URL SAFE.
 * @param p Objeto de propiedades a convertir.
 * @return Base64 URL SAFE que descodificado es un fichero de propiedades en texto plano.
 * @throws IOException Si hay problemas en la conversi&oacute;n a Base64. */
public static String properties2Base64(final Properties p) throws IOException {
  if (p == null) {
    return ""; //$NON-NLS-1$
  }
  final ByteArrayOutputStream baos = new ByteArrayOutputStream();
  final OutputStreamWriter osw = new OutputStreamWriter(baos, DEFAULT_ENCODING);
  p.store(osw, ""); //$NON-NLS-1$
  return Base64.encode(baos.toByteArray(), true);
}

代码示例来源:origin: es.gob.afirma/afirma-core

protected static String getDefaultKeyStoreLib(final Map<String, String> params) {

    // Si se ha especificado un almacen, se usara ese
    String ksValue = null;
    if (params.get(KEYSTORE_OLD_PARAM) != null) {
      ksValue = params.get(KEYSTORE_OLD_PARAM);
    }
    else if (params.get(KEYSTORE_PARAM) != null) {
      try {
        ksValue = new String(Base64.decode(params.get(KEYSTORE_PARAM)));
      }
      catch (final Exception e) {
        // Interpretamos que no era Base64 y no se ha pasado un almacen valido
      }
    }

    if (ksValue == null) {
      return null;
    }

    final int separatorPos = ksValue.indexOf(':');
    if (separatorPos != -1 && separatorPos < ksValue.length() - 1) {
      return ksValue.substring(separatorPos + 1).trim();
    }
    return null;
  }
}

代码示例来源:origin: es.gob.afirma/afirma-core

/** Compone un texto con los certificados de la cadena indicada codificados en Base64 de tipo <i>URL-Safe</i> concatenados
 * usando el separador por defecto.
 * @param certChain Cadena de certificados.
 * @param extraParams Par&aacute;metros adicionales de la firma, para comprobar si hay que incluir la cadena
 *                     completa de certificados o solo el certificado del firmante.
 * @return Texto con los certificados de la cadena codificados en Base64 de tipo <i>URL-Safe</i> y concatenados
 *         usando el separador por defecto.
 * @throws CertificateEncodingException Si hay problemas obteniendo la codificaci&oacute;n de alg&uacute;n certificado. */
public static String prepareCertChainParam(final Certificate[] certChain, final Properties extraParams) throws CertificateEncodingException {
  if (certChain == null || certChain.length < 1) {
    throw new IllegalArgumentException(
      "La cadena de certificados no puede ser nula ni vacia" //$NON-NLS-1$
    );
  }
  if (extraParams == null || Boolean.parseBoolean(extraParams.getProperty(INCLUDE_ONLY_SIGNNING_CERTIFICATE, Boolean.FALSE.toString()))) {
    return Base64.encode(certChain[0].getEncoded(), true);
  }
  final StringBuilder sb = new StringBuilder();
  for (final Certificate cert : certChain) {
    sb.append(Base64.encode(cert.getEncoded(), true));
    sb.append(PARAM_NAME_CERT_SEPARATOR);
  }
  final String ret = sb.toString();
  return ret.substring(0, ret.length() - PARAM_NAME_CERT_SEPARATOR.length());
}

代码示例来源:origin: es.gob.afirma/afirma-crypto-core-xml

/** Crea un X509Certificate a partir de un certificado en Base64.
 * @param b64Cert Certificado en Base64. No debe incluir <i>Bag Attributes</i>.
 * @return Certificado X509 o <code>null</code> si no se pudo crear. */
public static X509Certificate createCert(final String b64Cert) {
  if (b64Cert == null || b64Cert.isEmpty()) {
    LOGGER.severe("Se ha proporcionado una cadena nula o vacia, se devolvera null"); //$NON-NLS-1$
    return null;
  }
  final X509Certificate cert;
  try (
    final InputStream isCert = new ByteArrayInputStream(Base64.decode(b64Cert));
  ) {
    cert = (X509Certificate) CertificateFactory.getInstance("X.509").generateCertificate(isCert); //$NON-NLS-1$
    try {
      isCert.close();
    }
    catch (final Exception e) {
      LOGGER.warning("Error cerrando el flujo de lectura del certificado: " + e); //$NON-NLS-1$
    }
  }
  catch (final Exception e) {
    LOGGER.severe("No se pudo decodificar el certificado en Base64, se devolvera null: " + e); //$NON-NLS-1$
    return null;
  }
  return cert;
}

代码示例来源:origin: es.gob.afirma/afirma-crypto-pdf

.append(" </pdfIf>\n") //$NON-NLS-1$
.append(" <sign>\n") //$NON-NLS-1$
.append(Base64.encode(getSign())).append('\n')
.append(" </sign>\n") //$NON-NLS-1$
.append(" <timestamp>\n") //$NON-NLS-1$
.append(this.timestamp != null ? Base64.encode(getTimestamp()) : "").append('\n') //$NON-NLS-1$
.append(" </timestamp>\n") //$NON-NLS-1$
.append(" <signTime>\n") //$NON-NLS-1$

代码示例来源:origin: es.gob.afirma/afirma-crypto-pdf

static com.aowagie.text.Image getImage(final String imagebase64Encoded) {
  if (imagebase64Encoded == null || imagebase64Encoded.isEmpty()) {
    return null;
  }
  final byte[] image;
  try {
    image = Base64.decode(imagebase64Encoded);
  }
  catch (final Exception e) {
    LOGGER.severe("Se ha proporcionado una imagen de rubrica que no esta codificada en Base64: " + e); //$NON-NLS-1$
    return null;
  }
  try {
    return new Jpeg(image);
  }
  catch (final Exception e) {
    LOGGER.info("Se ha proporcionado una imagen de rubrica que no esta codificada en JPEG: " + e); //$NON-NLS-1$
  }
  return null;
}

代码示例来源:origin: es.gob.afirma/afirma-core-firmaweb

bos.write(Base64.encode(baos.toByteArray()).getBytes());
bos.flush();

相关文章