Java Mail MimeUtility encodeText UnsupportedEncodingException BASE64 - java

As part of my J2EE application's email service, I encode into BASE64
body = MimeUtility.encodeText(orig_mail_body,"UTF-8","BASE64");
but in some circumstances it's throwing an exception:
java.io.UnsupportedEncodingException: Unknown transfer encoding: BASE64
at javax.mail.internet.MimeUtility.encodeWord(MimeUtility.java:565)
at javax.mail.internet.MimeUtility.encodeText(MimeUtility.java:373)
I've been trying to uncover why I get this particular message, but to no avail.
Can someone illuminate me?

It seems like the only valid values for the 'encoding' argument are "B" or "Q"; so my code should be:
body = MimeUtility.encodeText(orig_mail_body,"UTF-8","B");

if you're using java 8 now there is a class that can solve that.
byte[] bytes = orig_mail_body.getBytes();
Base64.Encoder encoder = Base64.getEncoder();
String encode = encoder.encodeToString(bytes);
System.out.print(encode);
with spring: org.springframework.security.crypto.codec
public static String base64Encode(String token) {
byte[] encodedBytes = Base64.encode(token.getBytes());
return new String(encodedBytes, Charset.forName("UTF-8"));
}
public static String base64Decode(String token) {
byte[] decodedBytes = Base64.decode(token.getBytes());
return new String(decodedBytes, Charset.forName("UTF-8"));
}
with apache commons
org.apache.commons.codec.binary.Base64;
byte[] encodedBytes = Base64.encodeBase64("Test".getBytes());
System.out.println("encodedBytes " + new String(encodedBytes));
byte[] decodedBytes = Base64.decodeBase64(encodedBytes);
System.out.println("decodedBytes " + new String(decodedBytes));
Salud

Related

platform.win32.Win32Exception: The data is invalid | Java

I was writing this code to restore the user's saved chrome passwords and display them on the console.
I was able to decode Base64 encoded. But I am failing in decrying from this Crypt32Util.cryptUnprotectData any help ...
I am a beginner. :)
Main.java
import java.io.FileReader;
import java.util.Base64;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import com.sun.jna.platform.win32.Crypt32Util;
public class Main {
public static void main(String[] args) {
String name = System.getProperty("user.home");
name += "\\AppData\\Local\\Google\\Chrome\\User Data\\";
String masterKey = "";
String localState = name + "Local State";
try {
Object object = new JSONParser().parse(new FileReader(localState));
System.out.println("Success");
JSONObject jsonObject = (JSONObject) object;
JSONObject tempJsonObject = (JSONObject) jsonObject.get("os_crypt");
Base64.Decoder decoder = Base64.getDecoder();
String encryptedKey = (String) tempJsonObject.get("encrypted_key");
String decryptedKey = new String(decoder.decode(encryptedKey));
String encryptedMasterKey = decryptedKey.substring(5);
System.out.println(encryptedMasterKey);
masterKey = new String(Crypt32Util.cryptUnprotectData(encryptedMasterKey.getBytes()));
System.out.println(masterKey);
} catch (Exception e) {
e.printStackTrace();
}
}
}
Output
Success
[value of **encryptedMasterKey**]
com.sun.jna.platform.win32.Win32Exception: The data is invalid.
at com.sun.jna.platform.win32.Crypt32Util.cryptUnprotectData(Crypt32Util.java:144)
at com.sun.jna.platform.win32.Crypt32Util.cryptUnprotectData(Crypt32Util.java:117)
at com.sun.jna.platform.win32.Crypt32Util.cryptUnprotectData(Crypt32Util.java:104)
at com.main.Main.main(Main.java:26)
decoder.decode() returns binary data. You cannot create a String from binary data.
If you want a byte[] with the first 5 bytes from the byte[] returned by decoder.decode(), use Arrays.copyOfRange():
String encryptedKey = (String) tempJsonObject.get("encrypted_key");
Base64.Decoder decoder = Base64.getDecoder();
byte[] decodedKey = decoder.decode(encryptedKey);
byte[] encryptedMasterKey = Arrays.copyOfRange(decodedKey, 0, 5);
byte[] masterKey = Crypt32Util.cryptUnprotectData(encryptedMasterKey);
However, I doubt that is correct. Why do you believe the master password could be encrypted to only 5 bytes, and what is all the rest then?
It's far more likely that all the bytes are encrypted version of the master key:
String encryptedKey = (String) tempJsonObject.get("encrypted_key");
byte[] masterKey = Crypt32Util.cryptUnprotectData(Base64.getDecoder().decode(encryptedKey));
The answer of #Andreas is almost correct
I used this code which gave me an exception
String encryptedKey = (String) tempJsonObject.get("encrypted_key");
Base64.Decoder decoder = Base64.getDecoder();
byte[] decodedKey = decoder.decode(encryptedKey);
byte[] encryptedMasterKey = Arrays.copyOfRange(decodedKey, 0, 5);
byte[] masterKey = Crypt32Util.cryptUnprotectData(encryptedMasterKey);
So it just changed some values in
String encryptedKey = (String) tempJsonObject.get("encrypted_key");
Base64.Decoder decoder = Base64.getDecoder();
byte[] decodedKey = decoder.decode(encryptedKey);
byte[] encryptedMasterKey = Arrays.copyOfRange(decodedKey, 5, decodedKey.length);
byte[] masterKey = Crypt32Util.cryptUnprotectData(encryptedMasterKey);
It worked But now I have to understand its key format :)
Thanks, Andreas

How to convert a byte string to String? [duplicate]

I'm trying to decode a simple Base64 string, but am unable to do so. I'm currently using the org.apache.commons.codec.binary.Base64 package.
The test string I'm using is: abcdefg, encoded using PHP YWJjZGVmZw==.
This is the code I'm currently using:
Base64 decoder = new Base64();
byte[] decodedBytes = decoder.decode("YWJjZGVmZw==");
System.out.println(new String(decodedBytes) + "\n") ;
The above code does not throw an error, but instead doesn't output the decoded string as expected.
Modify the package you're using:
import org.apache.commons.codec.binary.Base64;
And then use it like this:
byte[] decoded = Base64.decodeBase64("YWJjZGVmZw==");
System.out.println(new String(decoded, "UTF-8") + "\n");
The following should work with the latest version of Apache common codec
byte[] decodedBytes = Base64.getDecoder().decode("YWJjZGVmZw==");
System.out.println(new String(decodedBytes));
and for encoding
byte[] encodedBytes = Base64.getEncoder().encode(decodedBytes);
System.out.println(new String(encodedBytes));
If you don't want to use apache, you can use Java8:
byte[] decodedBytes = Base64.getDecoder().decode("YWJjZGVmZw==");
System.out.println(new String(decodedBytes) + "\n");
Commonly base64 it is used for images. if you like to decode an image (jpg in this example with org.apache.commons.codec.binary.Base64 package):
byte[] decoded = Base64.decodeBase64(imageJpgInBase64);
FileOutputStream fos = null;
fos = new FileOutputStream("C:\\output\\image.jpg");
fos.write(decoded);
fos.close();

Bouncycastle in Java odd encryption and decryption results

So I have been working with the Bouncycastle libraries in an attempt to connect with a remote server. This process has been problematic from the get go and now I'm close to getting everything working but some odd things are happening.
When I first started building out the encryption process I was told to use AES 256 with PKCS7Padding. After some nagging I was provided with a c++ example of the server code. It turned out that the IV is 256 bit so I had to use the RijndaelEngine instead. Also in order for this to work correctly I have to use ZeroBytePadding.
Here is my code:
socket = new Socket(remoteIP, port);
outputStream = new PrintWriter(socket.getOutputStream());
inputStream = new BufferedReader(new InputStreamReader(socket.getInputStream()));
byte[] base_64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".getBytes("UTF-8");
Security.addProvider(new BouncyCastleProvider());
public String AESEncrypt(String out) throws IOException, DataLengthException, IllegalStateException, InvalidCipherTextException {
byte[] EncKey = key;
byte randKey;
Random randNumber = new Random();
randKey = base_64[randNumber.nextInt(base_64.length)];
EncKey[randKey&0x1f] = randKey;
RijndaelEngine rijndaelEngine = new RijndaelEngine(256);
PaddedBufferedBlockCipher cipher = new PaddedBufferedBlockCipher(new CBCBlockCipher(rijndaelEngine), new ZeroBytePadding());
ParametersWithIV keyParameter = new ParametersWithIV(new KeyParameter(EncKey), iv);
cipher.init(true, keyParameter);
byte[] txt = out.getBytes();
byte[] encoded = new byte[cipher.getOutputSize(txt.length)];
int len = cipher.processBytes(txt, 0, txt.length, encoded, 0);
cipher.doFinal(encoded, len);
char keyChar = (char) randKey;
String encString = new String(Base64.encode(encoded));
encString = encString.substring(0, encString.length()-1) + randKey;
return encString;
}
public void AESDecrypt(String in) throws DataLengthException, IllegalStateException, IOException, InvalidCipherTextException {
byte[] decKey = key;
byte[] msg = in.getBytes();
byte randKey = msg[msg.length-1];
decKey[randKey&0x1f] = randKey;
byte[] trimMsg = new byte[msg.length-1];
System.arraycopy(msg, 0, trimMsg, 0, trimMsg.length);
in = new String(trimMsg);
RijndaelEngine rijndaelEngine = new RijndaelEngine(256);
PaddedBufferedBlockCipher cipher = new PaddedBufferedBlockCipher(new CBCBlockCipher(rijndaelEngine), new ZeroBytePadding());
ParametersWithIV keyParameter = new ParametersWithIV(new KeyParameter(decKey), iv);
cipher.init(false, keyParameter);
byte[] encoded = Base64.decode(in.trim());
byte[] decoded = new byte[cipher.getOutputSize(encoded.length)];
int len = cipher.processBytes(encoded, 0, encoded.length, decoded, 0);
cipher.doFinal(decoded, len);
String decString = new String(decoded);
}
Here is a test function I am using to send and receive messages:
public void serverTest() throws DataLengthException, IllegalStateException, InvalidCipherTextException, IOException {
//out = AESEncrypt(out);
outputStream.write(out + "\n");
outputStream.flush();
String msg = "";
while ((msg = inputStream.readLine()) != null) {
AESDecrypt(msg);
}
}
The key and iv don't change with the exception of the last byte in the key. If I am encrypting I get a random base64 char and change the last byte to that. If its decryption I get the last byte from the message and set the last value of the key to it for decryption.
In the c++ example there was an unencrypted message and two encrypted messages. I could deal with those fine.
Here is the problem, when I send my message to the remote server "encrypted" the app waits for a response until the connection times out but never gets one. If I send the message unencrypted I get either 7 responses which I can successfully decrypt and finally
org.bouncycastle.util.encoders.DecoderException: unable to decode base64 string:
String index out of range: -4 at org.bouncycastle.util.encoders.Base64.decode(Unknown Source)
or my last line before the error will look like this:
?"??n?i???el????s???!_S=??ah????CR??l6??]?{?l??Y?????Gn???+?????9!'??gU&4>??{X????G?.$c=??0?5??GP???_Q5????8??Z\?~???<Kr?????[2\ ???a$?C??z%?W???{?.?????eR?j????~?B"$??"z??W;???<?Yu??Y*???Z?K?e!?????f?;O(?Zw0B??g<???????????,)?L>???A"?????<?????W??#\???f%??j ?EhY/?? ?5R?34r???#?1??I??????M
If I set the encryption/decryption to use PKCS7Padding I get no response when my message is encrypted still but with decryption from the server I get between 2 to 6 responses and then
org.bouncycastle.crypto.InvalidCipherTextException: pad block corrupted
I am at a loss with this. I don't know what I might be doing wrong so I have come here. I'm hoping the so community can point out my errors and guide me in the right direction.
I have a bit of an update I found my error in the encryption. I wasn't placing the random base64 value at the end of the encrypted string correctly so now I am doing like this.
encString += (char)randKey;
I can get response from the server now. Now the problem is I will some times get one or two readable lines but the rest are all garbage. I asked the individuals who run the server about it and they said in some c# code that they reference the have
return UTF8Encoding.UTF8.GetString(resultArray);
and thats all I have to go off of. I have tried UTF-8 encoding any place where I do getBytes or new String, and I have tried making the BurrferReader stream UTF-8 but it's still garbage.
Have you seedn the BCgit? this has bouncycastle code and examples. I am using the Csharp version in this repository. https://github.com/bcgit/bc-java
All crypto primitive examples are stored here: https://github.com/bcgit/bc-java/tree/master/core/src/test/java/org/bouncycastle/crypto/test
Try this code for testing Aes-CBC
private void testNullCBC()
throws InvalidCipherTextException
{
BufferedBlockCipher b = new BufferedBlockCipher(new CBCBlockCipher(new AESEngine()));
KeyParameter kp = new KeyParameter(Hex.decode("5F060D3716B345C253F6749ABAC10917"));
b.init(true, new ParametersWithIV(kp, new byte[16]));
byte[] out = new byte[b.getOutputSize(tData.length)];
int len = b.processBytes(tData, 0, tData.length, out, 0);
len += b.doFinal(out, len);
if (!areEqual(outCBC1, out))
{
fail("no match on first nullCBC check");
}
b.init(true, new ParametersWithIV(null, Hex.decode("000102030405060708090a0b0c0d0e0f")));
len = b.processBytes(tData, 0, tData.length, out, 0);
len += b.doFinal(out, len);
if (!areEqual(outCBC2, out))
{
fail("no match on second nullCBC check");
}
}

Decoding a Base64 string in Java

I'm trying to decode a simple Base64 string, but am unable to do so. I'm currently using the org.apache.commons.codec.binary.Base64 package.
The test string I'm using is: abcdefg, encoded using PHP YWJjZGVmZw==.
This is the code I'm currently using:
Base64 decoder = new Base64();
byte[] decodedBytes = decoder.decode("YWJjZGVmZw==");
System.out.println(new String(decodedBytes) + "\n") ;
The above code does not throw an error, but instead doesn't output the decoded string as expected.
Modify the package you're using:
import org.apache.commons.codec.binary.Base64;
And then use it like this:
byte[] decoded = Base64.decodeBase64("YWJjZGVmZw==");
System.out.println(new String(decoded, "UTF-8") + "\n");
The following should work with the latest version of Apache common codec
byte[] decodedBytes = Base64.getDecoder().decode("YWJjZGVmZw==");
System.out.println(new String(decodedBytes));
and for encoding
byte[] encodedBytes = Base64.getEncoder().encode(decodedBytes);
System.out.println(new String(encodedBytes));
If you don't want to use apache, you can use Java8:
byte[] decodedBytes = Base64.getDecoder().decode("YWJjZGVmZw==");
System.out.println(new String(decodedBytes) + "\n");
Commonly base64 it is used for images. if you like to decode an image (jpg in this example with org.apache.commons.codec.binary.Base64 package):
byte[] decoded = Base64.decodeBase64(imageJpgInBase64);
FileOutputStream fos = null;
fos = new FileOutputStream("C:\\output\\image.jpg");
fos.write(decoded);
fos.close();

3DES - Decrypt encrypted text (by JAVA) in C#

Here is the situation:
The encrypted text is done in JAVA (which we have no JAVA background at all)
The method is 3DES
The padded is PKCS#5
Base 64
The decryption will be in C#, and here is the code:
public static string DecryptString(string Message, string Passphrase)
{
byte[] Results;
UTF8Encoding UTF8 = new UTF8Encoding();
MD5CryptoServiceProvider HashProvider = new MD5CryptoServiceProvider();
byte[] TDESKey = HashProvider.ComputeHash(UTF8.GetBytes(Passphrase));
TripleDESCryptoServiceProvider TDESAlgorithm = new TripleDESCryptoServiceProvider();
TDESAlgorithm.Key = TDESKey;
TDESAlgorithm.Mode = CipherMode.ECB;
TDESAlgorithm.Padding = PaddingMode.PKCS7;
byte[] DataToDecrypt = Convert.FromBase64String(Message);
try
{
ICryptoTransform Decryptor = TDESAlgorithm.CreateDecryptor();
Results = Decryptor.TransformFinalBlock(DataToDecrypt, 0, DataToDecrypt.Length);
}
finally
{
TDESAlgorithm.Clear();
HashProvider.Clear();
}
return UTF8.GetString(Results);
}
However, when tried to decrypt, got the error message: BAD DATA
Where am I missing here?
Thanks in advance.
Added, and here's how the encryption works:
<cffunction name="getToken" returntype="String" output="false">
<cfscript>
plainText = getPlainText();
rawSecretKey = CreateObject("java","sun.misc.BASE64Decoder").decodeBuffer(variables.encryptionKey);
secretKeySpec = CreateObject("java","javax.crypto.spec.SecretKeySpec").init(rawSecretKey,"DESEDE");
cipher = CreateObject("java","javax.crypto.Cipher").getInstance("DESEDE");
cipher.init(Cipher.ENCRYPT_MODE, secretkeySpec);
encrypted = cipher.doFinal(plainText.getBytes()); // a byte array (a binary in CF)
return URLEncodedFormat(ToString(ToBase64(encrypted)));
</cfscript>
</cffunction>
Update:
This issue has been resolved. The problem was that the key needed to be converted from Base64.
The answer:
Instead of:
byte[] TDESKey = HashProvider.ComputeHash(UTF8.GetBytes(Passphrase));
Do this:
byte[] TDESKey = Convert.FromBase64String(Passphrase);
That solves this issue.

Categories