Conversão de base64 para ASCII

9 respostas
M

Prezados,
sou novo no Java e já estou precisando de fazer a conversão de dados que estão no formato base64 para ASCII. Eu já fiz algumas tentativas, a partir de informações que busquei na internet, mas sem sucesso. Assim sendo, gostaria de pedir a ajuda de vocês para que eu possa fazer isso usando Java.

Eu tentei usar as informações do site http://java-espresso.blogspot.com.br/2011/10/base64-encoding-and-decoding-in-java.html, no qual trabalha com <import org.apache.commons.codec.binary;>

Salvei um arquivo ?CommonUtil.java? e, também, ?TestBase64.java?.

Porém, ao tentar compilar usando o comando apareceu a seguinte mensagem de erro:

.\CommonUtil.java:3: error: package org.apache.commons.codec does not exist

import org.apache.commons.codec.binary;

^

.\CommonUtil.java:14: error: cannot find symbol

return Base64.encodeBase64String(stringToEncodeBytes);

^

symbol:   variable Base64

location: class CommonUtil

.\CommonUtil.java:18: error: cannot find symbol

byte [] decodedBytes = Base64.decodeBase64(stringToDecode);

^

symbol:   variable Base64

location: class CommonUtil

3 errors

Alguém poderia, por favor, me ajudar com esta tarefa de converter base64 para ASCII usando Java?
Muito obrigado!

9 Respostas

dyeimys
.\CommonUtil.java:3: error: package org.apache.commons.codec does not exist

Este aqui está explicando tudo Não existe o pacote org.apache.commons.codec.
Capaz que a solução é você adicionar este pacote/biblioteca em sua aplicação este não é nativo (Pelo que me parece)

M

Obrigado, dyeimys, pela resposta!

Mas eu não sei inserir o pacote/biblioteca na aplicação…ainda estou começando no Java.

dyeimys

Bom dia,
Poste o inicio do seu codigo (Contendo o nome do pacote e as importações), Por exemplo:

package videolocadora;


import java.math.MathContext;
import java.util.Date;
import javax.xml.crypto.Data;

public class VideoLocadora { 


}

Poste também as linhas 3,14 e 18 que são as linhas que estão dando erro no complilador!
Assim pode ficar mais fácil de tentar de ajudar

M

Eu achei na internet um código intitulado "DatatypeConverter.java", mostrado a seguir:

-------------------------------- Início do código DatatypeConverter.java -------------------------------------------------

[code]/*
* Copyright 2003, 2004 The Apache Software Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.

*/
package javax.xml.bind;

import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.Calendar;

import javax.xml.namespace.NamespaceContext;
import javax.xml.namespace.QName;

/**

This is a helper class for customized datatypes. It provides a
* set of static methods which may be useful in custom methods for
* parsing and printing values.


*

The JAXB provider is responsible to initialize the
* DatatypeConverter class by invoking
* {@link #setDatatypeConverter(DatatypeConverterInterface)} as soon
* as possible.


*
* @author JSR-31
* @since JAXB1.0
*/
public final class DatatypeConverter {
private static DatatypeConverterInterface converter;

/**

This method must be invoked by the JAXB provider to set the actual
* instance, which is invoked by the static methods. Subsequent
* invocations of the method are ignored: First come, first wins.


* @throws IllegalArgumentException The parameter was null.
*/
public static void setDatatypeConverter(DatatypeConverterInterface pConverter) {
if (pConverter == null) {
throw new IllegalArgumentException("The parameter must not be null.");
}
synchronized (DatatypeConverter.class) {
if (converter == null) {
converter = pConverter;
}
}
}

/**

Parses the lexical representation and converts it into a String.


*
* @param pLexicalXSDString The input string being parsed.
* @return The unmodified input string.
* @see javax.xml.bind.ParseConversionEvent
*/
public static String parseString(String pLexicalXSDString) {
return converter.parseString(pLexicalXSDString);
}

/**

Parses the lexical representation of the given integer value
* (arbitrary precision) and converts it into an instance of
* {@link java.math.BigInteger}.


* @param pLexicalXSDInteger The input string being parsed.
* @return The input string converted into an instance of {@link BigInteger}.
* @see javax.xml.bind.ParseConversionEvent
*/
public static BigInteger parseInteger(String pLexicalXSDInteger) {
return converter.parseInteger(pLexicalXSDInteger);
}

/**

Parses the lexical representation of the given 32 bit integer value
* and converts it into a primitive int value.


* @param pLexicalXSDInt The input string being parsed.
* @return The input string converted into a primitive int.
* @see javax.xml.bind.ParseConversionEvent
*/
public static int parseInt(String pLexicalXSDInt) {
return converter.parseInt(pLexicalXSDInt);
}

/**

Parses the lexical representation of the given 64 bit integer value
* and converts it into a primitive long value.


* @param pLexicalXSDLong The input string being parsed.
* @return The input string converted into a primitive long.
* @see javax.xml.bind.ParseConversionEvent
*/
public static long parseLong(String pLexicalXSDLong) {
return converter.parseLong(pLexicalXSDLong);
}

/**

Parses the lexical representation of the given 16 bit integer value
* and converts it into a primitive short value.


* @param pLexicalXSDShort The input string being parsed.
* @return The input string converted into a primitive short.
* @see javax.xml.bind.ParseConversionEvent
*/
public static short parseShort(String pLexicalXSDShort) {
return converter.parseShort(pLexicalXSDShort);
}

/**

Parses the lexical representation of the given decimal value
* (arbitrary precision) and converts it into an instance of
* {@link java.math.BigDecimal}.


* @param pLexicalXSDDecimal The input string being parsed.
* @return The input string converted into an instance of {@link java.math.BigDecimal}.
* @see javax.xml.bind.ParseConversionEvent
*/
public static BigDecimal parseDecimal(String pLexicalXSDDecimal) {
return converter.parseDecimal(pLexicalXSDDecimal);
}

/**

Parses the lexical representation of the given 32 bit floating
* point value and converts it into a primitive float value.


* @param pLexicalXSDFloat The input string being parsed.
* @return The input string converted into a primitive float.
* @see javax.xml.bind.ParseConversionEvent
*/
public static float parseFloat(String pLexicalXSDFloat) {
return converter.parseFloat(pLexicalXSDFloat);
}

/**

Parses the lexical representation of the given 64 bit floating
* point value and converts it into a primitive double value.


* @param pLexicalXSDDouble The input string being parsed.
* @return The input string converted into a primitive double.
* @see javax.xml.bind.ParseConversionEvent
*/
public static double parseDouble(String pLexicalXSDDouble) {
return converter.parseDouble(pLexicalXSDDouble);
}

/**

Parses the lexical representation of the given boolean value
* and converts it into a primitive boolean value.


* @param pLexicalXSDBoolean The input string being parsed.
* @return The input string converted into a primitive boolean.
* @see javax.xml.bind.ParseConversionEvent
*/
public static boolean parseBoolean(String pLexicalXSDBoolean) {
return converter.parseBoolean(pLexicalXSDBoolean);
}

/**

Parses the lexical representation of the given 8 bit integer value
* and converts it into a primitive byte value.


* @param pLexicalXSDByte The input string being parsed.
* @return The input string converted into a primitive byte.
* @see javax.xml.bind.ParseConversionEvent
*/
public static byte parseByte(String pLexicalXSDByte) {
return converter.parseByte(pLexicalXSDByte);
}

/**

Parses the lexical representation of the given qualified name
* and converts it into an instance of {@link javax.xml.namespace.QName}.
* The {@link javax.xml.namespace.QName} consists of a namespace URI
* and a local name.


* @param pLexicalXSDQName The input string being parsed, an optional
* namespace prefix, followed by the local name, if any. If a prefix
* is present, they are separated by a colon.
* @param pNamespaceContext The namespace context is used to query
* mappings between prefixes and namespace URI's.
* @return The input string converted into an instance of
* {@link javax.xml.namespace.QName}.
* @see javax.xml.bind.ParseConversionEvent
*/
public static QName parseQName(String pLexicalXSDQName,
NamespaceContext pNamespaceContext) {
return converter.parseQName(pLexicalXSDQName, pNamespaceContext);
}

/**

Parses the lexical representation of the given dateTime value
* and converts it into an instance of {@link java.util.Calendar}.
* Valid lexical representations of a dateTime value include
*


* YYYY-MM-DDThh:mm:ss
* YYYY-MM-DDThh:mm:ss.sss
* YYYY-MM-DDThh:mm:ssZ
* YYYY-MM-DDThh:mm:ss-01:00
*

* The former examples are all specified in UTC time. The last example
* uses a negatice offset of one hour to UTC.


* @param pLexicalXSDDateTime The input string being parsed.
* @return The input string converted into an instance of
* {@link java.util.Calendar}.
* @see javax.xml.bind.ParseConversionEvent
*/
public static Calendar parseDateTime(String pLexicalXSDDateTime) {
return converter.parseDateTime(pLexicalXSDDateTime);
}

/**

Parses the lexical representation of the given byte array, which
* is encoded in base 64.


* @param pLexicalXSDBase64Binary The input string being parsed, a
* base 64 encoded array of bytes.
* @return The decoded byte array.
* @see javax.xml.bind.ParseConversionEvent
*/
[color=red] public static byte[] parseBase64Binary(String pLexicalXSDBase64Binary) {
return converter.parseBase64Binary(pLexicalXSDBase64Binary);[/color]

}

/**

Parses the lexical representation of the given byte array, which
* is encoded in hex digits.


* @param pLexicalXSDHexBinary The input string being parsed, an
* array of bytes encoded in hex digits.
* @return The decoded byte array.
* @see javax.xml.bind.ParseConversionEvent
*/
public static byte[] parseHexBinary(String pLexicalXSDHexBinary) {
return converter.parseHexBinary(pLexicalXSDHexBinary);
}

/**

Parses the lexical representation of the given 32 bit
* unsignet integer value and converts it into a primitive long
* value.


* @param pLexicalXSDUnsignedInt The input string being parsed.
* @return The input string converted into a primitive long.
* @see javax.xml.bind.ParseConversionEvent
*/
public static long parseUnsignedInt(String pLexicalXSDUnsignedInt) {
return converter.parseUnsignedInt(pLexicalXSDUnsignedInt);
}

/**

Parses the lexical representation of the given 16 bit
* unsignet integer value and converts it into a primitive int
* value.


* @param pLexicalXSDUnsignedShort The input string being parsed.
* @return The input string conve
* rted into a primitive int.
* @see javax.xml.bind.ParseConversionEvent
*/
public static int parseUnsignedShort(String pLexicalXSDUnsignedShort) {
return converter.parseUnsignedShort(pLexicalXSDUnsignedShort);
}

/**

Parses the lexical representation of the given time value
* and converts it into an instance of {@link java.util.Calendar}.
* Valid lexical representations of a time value include
*


* hh:mm:ss
* hh:mm:ss.sss
* hh:mm:ssZ
* hh:mm:ss-01:00
*

* The former examples are all specified in UTC time. The last example
* uses a negatice offset of one hour to UTC.


* @param pLexicalXSDTime The input string being parsed.
* @return The input string converted into an instance of
* {@link java.util.Calendar}.
* @see javax.xml.bind.ParseConversionEvent
*/
public static Calendar parseTime(String pLexicalXSDTime) {
return converter.parseTime(pLexicalXSDTime);
}

/**

Parses the lexical representation of the given date value
* and converts it into an instance of {@link java.util.Calendar}.
* Valid lexical representations of a date value include
*


* YYYY-MM-DD
* YYYY-MM-DDZ
* YYYY-MM-DD-01:00
*

* The former examples are all specified in UTC time. The last example
* uses a negatice offset of one hour to UTC.


* @param pLexicalXSDDate The input string being parsed.
* @return The input string converted into an instance of
* {@link java.util.Calendar}.
* @see javax.xml.bind.ParseConversionEvent
*/
public static Calendar parseDate(String pLexicalXSDDate) {
return converter.parseDate(pLexicalXSDDate);
}

/**

Returns the lexical representation of the input string, which is
* the unmodified input string.


* @param pLexicalXSDAnySimpleType An input string in lexical representation.
* @return The unmodified input string.
* @see javax.xml.bind.ParseConversionEvent
*/
public static String parseAnySimpleType(String pLexicalXSDAnySimpleType) {
return converter.parseAnySimpleType(pLexicalXSDAnySimpleType);
}

/**

Returns a lexical representation of the given input string, which
* is the unmodified input string.


* @param pValue The input string.
* @return The unmodified input string.
* @see javax.xml.bind.PrintConversionEvent
*/
public static String printString(String pValue) {
return converter.printString(pValue);
}

/**

Returns a lexical representation of the given instance of
* {@link BigInteger}, which is an integer in arbitrary precision.


* @param pValue The integer value being converted.
* @return A lexical representation of the input value.
* @see javax.xml.bind.PrintConversionEvent
*/
public static String printInteger(BigInteger pValue) {
return converter.printInteger(pValue);
}

/**

Returns a lexical representation of the given primitive
* 32 bit integer.


* @param pValue The int value being converted.
* @return A lexical representation of the input value.
* @see javax.xml.bind.PrintConversionEvent
*/
public static String printInt(int pValue) {
return converter.printInt(pValue);
}

/**

Returns a lexical representation of the given primitive
* 64 bit integer.


* @param pValue The long value being converted.
* @return A lexical representation of the input value.
* @see javax.xml.bind.PrintConversionEvent
*/
public static String printLong(long pValue) {
return converter.printLong(pValue);
}

/**

Returns a lexical representation of the given primitive
* 16 bit integer.


* @param pValue The short value being converted.
* @return A lexical representation of the input value.
* @see javax.xml.bind.PrintConversionEvent
*/
public static String printShort(short pValue) {
return converter.printShort(pValue);
}

/**

Returns a lexical representation of the given instance of
* {@link BigDecimal}, which is a decimal number in arbitrary
* precision.


* @param pValue The decimal value being converted.
* @return A lexical representation of the input value.
* @see javax.xml.bind.PrintConversionEvent
*/
public static String printDecimal(BigDecimal pValue) {
return converter.printDecimal(pValue);
}

/**

Returns a lexical representation of the given primitive
* 32 bit floating point number.


* @param pValue The float value being converted.
* @return A lexical representation of the input value.
* @see javax.xml.bind.PrintConversionEvent
*/
public static String printFloat(float pValue) {
return converter.printFloat(pValue);
}

/**

Returns a lexical representation of the given primitive
* 64 bit floating point number.


* @param pValue The double value being converted.
* @return A lexical representation of the input value.
* @see javax.xml.bind.PrintConversionEvent
*/
public static String printDouble(double pValue) {
return converter.printDouble(pValue);
}

/**

Returns a lexical representation of the given primitive
* boolean value.


* @param pValue The boolean value being converted.
* @return A lexical representation of the input value.
* @see javax.xml.bind.PrintConversionEvent
*/
public static String printBoolean(boolean pValue) {
return converter.printBoolean(pValue);
}

/**

Returns a lexical representation of the given primitive
* 8 bit integer.


* @param pValue The byte value being converted.
* @return A lexical representation of the input value.
* @see javax.xml.bind.PrintConversionEvent
*/
public static String printByte(byte pValue) {
return converter.printByte(pValue);
}

/**

Returns a lexical representation of the given qualified
* name, which is a combination of namespace URI and local name.
* The lexical representation is an optional prefix, which is
* currently mapped to namespace URI of the qualified name,
* followed by a colon and the local name. If the namespace URI
* is the current default namespace URI, then the prefix and
* the colon may be omitted.


* @param pValue The qualified name being converted.
* @param pNamespaceContext A mapping of prefixes to namespace
* URI's which may be used to determine a valid prefix.
* @return A lexical representation of the qualified name.
* @see javax.xml.bind.PrintConversionEvent
*/
public static String printQName(QName pValue,
NamespaceContext pNamespaceContext) {
return converter.printQName(pValue, pNamespaceContext);
}

/**

Returns a lexical representation of the given dateTime
* value. Valid lexical representations include:
*


* YYYY-MM-DDThh:mm:ss
* YYYY-MM-DDThh:mm:ss.sss
* YYYY-MM-DDThh:mm:ssZ
* YYYY-MM-DDThh:mm:ss-01:00
*

* The former examples are all specified in UTC time. The last example
* uses a negatice offset of one hour to UTC.


* @param pValue The dateTime value being converted
* @return A lexical representation of the input value.
* @see javax.xml.bind.PrintConversionEvent
*/
public static String printDateTime(Calendar pValue) {
return converter.printDateTime(pValue);
}

/**

Returns a lexical representation of the given byte array.
* The lexical representation is obtained by application of the
* base 64 encoding.


* @param pValue The byte array being converted.
* @return The converted byte array.
* @see javax.xml.bind.PrintConversionEvent
*/
public static String printBase64Binary(byte[] pValue) {
return converter.printBase64Binary(pValue);
}

/**

Returns a lexical representation of the given byte array.
* The lexical representation is obtained by encoding any byte
* as two hex digits.


* @param pValue The byte array being converted.
* @return The converted byte array.
* @see javax.xml.bind.PrintConversionEvent
*/
public static String printHexBinary(byte[] pValue) {
return converter.printHexBinary(pValue);
}

/**

Returns a lexical representation of the given primitive,
* unsigned 32 bit integer.


* @param pValue The long value being converted.
* @return A lexical representation of the input value.
* @see javax.xml.bind.PrintConversionEvent
*/
public static String printUnsignedInt(long pValue) {
return converter.printUnsignedInt(pValue);
}

/**

Returns a lexical representation of the given primitive,
* unsigned 16 bit integer.


* @param pValue The short value being converted.
* @return A lexical representation of the input value.
* @see javax.xml.bind.PrintConversionEvent
*/
public static String printUnsignedShort(int pValue) {
return converter.printUnsignedShort(pValue);
}

/**

Returns a lexical representation of the given time
* value. Valid lexical representations include:
*


* hh:mm:ss
* hh:mm:ss.sss
* hh:mm:ssZ
* hh:mm:ss-01:00
*

* The former examples are all specified in UTC time. The last example
* uses a negatice offset of one hour to UTC.


* @param pValue The time value being converted
* @return A lexical representation of the input value.
* @see javax.xml.bind.PrintConversionEvent
*/
public static String printTime(Calendar pValue) {
return converter.printTime(pValue);
}

/**

Returns a lexical representation of the given date
* value. Valid lexical representations include:
*


* YYYY-MM-DD
* YYYY-MM-DDZ
* YYYY-MM-DD-01:00
*

* The former examples are all specified in UTC time. The last example
* uses a negatice offset of one hour to UTC.


* @param pValue The date value being converted
* @return A lexical representation of the input value.
* @see javax.xml.bind.PrintConversionEvent
*/
public static String printDate(Calendar pValue) {
return converter.printDate(pValue);
}

/**

Returns a lexical representation of the given input
* string, which is the unmodified input string.


* @param pValue The input string.
* @return The unmodified input string.
* @see javax.xml.bind.PrintConversionEvent
*/
public static String printAnySimpleType(String pValue) {
return converter.printAnySimpleType(pValue);
}
}

-------------------------------- Fimdo código DatatypeConverter.java -------------------------------------------------

Eu entendi o código acima como uma biblioteca. Assim sendo, fiz o seguinte código intitulado "testeBase64":

-------------------------------- Início do código testeBase64 ------------------------------------------------------------

import DatatypeConverter.*;

public class testeBase64 {
public static void main(String[] args) {

//String em base64 para ser convertida:
String encoded = "TWFyeSBoYWQgYSBsaXR0bGUgbGFtYi4u";

//Fazendo a conversão de base64 para ASCII:
byte[] retorno = parseBase64Binary(encoded);

}
}

-------------------------------- Fim do código testeBase64 ------------------------------------------------------------

Depois, eu utilizei o comando "javac testeBase64.java", mas apareceu a seguinte mensagem de erro:

testeBase64.java:1: error: package DatatypeConverter does not exist
import DatatypeConverter.*;
^
testeBase64.java:8: error: cannot find symbol
byte[] retorno = parseBase64Binary(encoded);
^
symbol: method parseBase64Binary(String)
location: class testeBase64
2 errors

Ou seja, não sei como utilizar ou incorporar a função "parseBase64Binary", contida no arquivo "DatatypeConverter.java", em outro código.

Como faço para testar a função citada?
Muito obrigado!

M

Oi, dyeimys! Obrigado mais uma vez!

Na abordagem anterior, na qual eu tentei incorporar o "import org.apache.commons.codec.binary; ", o código é o seguinte:

import java.util.Arrays;  
      
	import org.apache.commons.codec.binary;  
      
    /** 
     * @author java-espresso 
     * This class has two methods one encodes a string in Base64Encoding  
     * and other decodes the same. 
     */  
    public class CommonUtil {  
      
     public static String base64Encode(String stringToEncode){  
      byte [] stringToEncodeBytes = stringToEncode.getBytes();  
      return Base64.encodeBase64String(stringToEncodeBytes);  
     }  
       
     public static String base64Decode(String stringToDecode){  
      byte [] decodedBytes = Base64.decodeBase64(stringToDecode);  
      return new String(decodedBytes);  
     }  
       
    }
M

Desculpe! Houve um erro ao copiar o código.

import java.util.Arrays;  
      
    import org.apache.commons.codec.binary;  
      
    /** 
     * @author java-espresso 
     * This class has two methods one encodes a string in Base64Encoding  
     * and other decodes the same. 
     */  
    public class CommonUtil {  
      
     public static String base64Encode(String stringToEncode){  
      byte [] stringToEncodeBytes = stringToEncode.getBytes();  
      return Base64.encodeBase64String(stringToEncodeBytes);  
     }  
       
     public static String base64Decode(String stringToDecode){  
      byte [] decodedBytes = Base64.decodeBase64(stringToDecode);  
      return new String(decodedBytes);  
     }  
       
    }
dyeimys

Caro MPRT pelo tenho visto que este é um Projeto, para que você consiga rodar o sistema você tem que compilar todo o projeto (Não somente a classe principal)
Tem um tópico aqui que te ajudará ->Compilar na unha
Documentação java -> Package
Após intender isto se tiver mais duvidas poste novamente.

PS. Você quer apenas um programa para Converter Hexa em ASCII?

M

Oi, dyeimys! Eu analisarei as informações que você me forneceu!

Eu preciso de um código em Java para transformar os dados que estou lendo em base64 para ASCII. Não é um software ou algo assim, é o código mesmo.

Depois, postarei os resultados que obtiver!
Obrigado!

dyeimys

Pronto, isto faz o que você precisa

import java.io.UnsupportedEncodingException;
import java.math.BigInteger;

public class Convert {

    public static void main(String[] args) throws UnsupportedEncodingException {
        String hexa = "4f206a6176612065682073696d706c6573206520636f6d706c65746f";
        BigInteger big = new BigInteger(hexa, 16);
        System.out.println(new String(big.toByteArray(), "ASCII"));
    }
}

Só compilar e rodar…

Criado 18 de setembro de 2012
Ultima resposta 20 de set. de 2012
Respostas 9
Participantes 2