I would like to sign some data (the MESSAGE byte array) on my Java Card and then return the signature in a response APDU. My code works fine (or at least I think it does and it returns 9000) without the line apdu.sendBytes(BAS, sSignLen), but when I uncomment it I get an unknown error (0xC000002B (Unknown error.)).
When I try to send other data in a response APDU it works flawlessly.
apdu.setIncomingAndReceive();
Util.arrayCopyNonAtomic(MESSAGE, (short) 0, buffer, (short) 0, (short) MESSAGE.length);
apdu.setOutgoingAndSend((short) 0, (short) MESSAGE.length);
Here is my code. What am I doing wrong or missing? Thank you!
public class TestApplet extends Applet {
...
private final static byte SIGN = (byte) 0x01;
...
private final static byte[] MESSAGE = new byte[] { 'M', 'e', 's', 's', 'a', 'g', 'e' };
final static short BAS = 0;
public void process(APDU apdu) {
if (this.selectingApplet())
return;
byte buffer[] = apdu.getBuffer();
...
switch (buffer[ISO7816.OFFSET_INS]) {
case SIGN:
try {
ECDSAKeyPair = Secp256k1Domain.getKeyPairParameter();
ECDSAKeyPair.genKeyPair();
ECDSAPublicKey = (ECPublicKey) ECDSAKeyPair.getPublic();
ECDSAPrivateKey = (ECPrivateKey) ECDSAKeyPair.getPrivate();
ECDSASignature = Signature.getInstance(Signature.ALG_ECDSA_SHA, false);
short signLen = 0;
byte[] signatureArray = new byte[70];
ECDSASignature.init(ECDSAPrivateKey, Signature.MODE_SIGN);
signLen = ECDSASignature.sign(MESSAGE, BAS, (short) MESSAGE.length, signatureArray, BAS);
apdu.setIncomingAndReceive();
Util.arrayCopyNonAtomic(signatureArray, (short) 0, buffer, (short) 0, (short) signatureArray.length);
apdu.setOutgoingAndSend((short) 0, (short) signatureArray.length);
} catch (CryptoException c) {
short reason = c.getReason();
ISOException.throwIt((short) ((short) (0x9C00) | reason));
}
break;
...
return;
}
}
It's probably that signLen is larger than the Ne value (incorrectly called Le in the JavaCard specifications). You are also abusing the Le value to mean (short) MESSAGE.length by the way. Ne indicates the maximum number of bytes that are expected to be send back.
Related
I'm developing a piece of code in which I need to create an RSA key pair.
My java card is an FM1280-ID006 card which has written in its information sheet that It supports java card 2.2.2 specification. When I try to create an RSA key pair
KeyPair(KeyPair.ALG_RSA,KeyBuilder.LENGTH_RSA_2048)
and install it on the card above, nothing unusual happens and I'm done successfully (90 00).
but as I call the method genKeyPair(), something happens in the card which I do not understand why. I use GPShell as below:
send_apdu -sc 1 -APDU 8000000000 // initialize
Command --> 8000000000
Wrapped command --> 8000000000
send_APDU() returns 0x8010002F (A communications error with the smart card has been detected. Retry the operation.)
It is worthy to mention that this problem on key pair creation does not happen when creating a 1024 key pair
KeyPair(KeyPair.ALG_RSA,KeyBuilder.LENGTH_RSA_1024)
and it is successfully created and used by RSA cipher and so on as:
send_apdu -sc 1 -APDU 8000000000 // initialize
Command --> 8000000000
Wrapped command --> 8000000000
Response <-- 9000
send_APDU() returns 0x80209000 (9000: Success. No error.)
command time: 3432 ms
Does my card support KeyPair 2048 as the information sheet says supporting javacard 2.2.2?
Appendix 1: Java Code:
package net.sourceforge.globalplatform.jc.hasincard;
import javacard.framework.*;
import javacard.security.*;
import javacardx.crypto.*;
import java.security.acl.Owner;
import java.util.Random;
public class HasinCardApplet extends Applet {
final static byte APPLET_CLA = (byte)0x80;
final static byte INITIALIZE = (byte)0x00;
final static byte INSERT_MESSAGE = (byte)0x01;
final static byte CHECK_MESSAGE = (byte)0x02;
final static byte GET_HASH = (byte)0x03;
final static byte GET_SIGN = (byte)0x04;
final static byte VERIFY_SIGN = (byte)0x05;
final static byte VERIFY_PIN = (byte)0x06;
final static byte CHANGE_PIN = (byte)0x07;
final static byte UNLOCK_PIN = (byte)0x08;
final static byte TEST = (byte)0x09;
final static short SW_MESSAGE_NOT_INSERTED = (short)0x6300;
final static short SW_KEY_IS_INITIALIZED = (short)0x6301;
final static short SW_HASH_NOT_SET = (short)0x6302;
final static short SW_SIGN_NOT_SET = (short)0x6303;
final static short SW_CARD_IS_LOCKED = (short)0x6304;
final static short SW_VERIFICATION_FAILED = (short)0x6305;
final static short SW_PIN_VERIFICATION_REQUIRED = (short)0x6306;
final static short SW_NEW_PIN_TOO_LONG = (short)0x6307;
final static short SW_NEW_PIN_TOO_SHORT = (short)0x6308;
final static short SW_PUK_VERIFICATION_REJECTED = (short)0x6309;
final static short SW_PUK_VERIFICATION_FAILED = (short)0x630A;
final static byte PIN_TRY_LIMIT = (byte)3;
final static byte MAX_PIN_SIZE = (byte)16;
final static byte MIN_PIN_SIZE = (byte)4;
final static byte PUK_LEN = (byte)16;
final static byte PUK_TRY_LIMIT = (byte)3;
private static byte[] Message;
private static byte[] Hash;
private static byte[] Sign;
private short message_len = 0;
private short hash_len = 0;
private short sign_len = 0;
private static boolean key_initialization_flag = false;
private static boolean insert_message_flag = false;
private static boolean hash_set_flag = false;
private static boolean sign_set_flag = false;
MessageDigest mDigest;
KeyPair rsaKey;
Cipher rsaCipher;
OwnerPIN userPin;
RandomData rnd;
byte[] PUK;
boolean init_flag;
byte puk_try_count;
private HasinCardApplet (byte[] bArray,short bOffset,byte bLength)
{
Message = new byte[512];
Hash = new byte[512];
Sign = new byte[512];
userPin = new OwnerPIN(PIN_TRY_LIMIT, MAX_PIN_SIZE);
rsaKey = new KeyPair(KeyPair.ALG_RSA,KeyBuilder.LENGTH_RSA_2048);
rsaCipher = Cipher.getInstance(Cipher.ALG_RSA_PKCS1, false);
mDigest = MessageDigest.getInstance(MessageDigest.ALG_SHA_256,false);
rnd = RandomData.getInstance(RandomData.ALG_SECURE_RANDOM);
PUK = new byte[PUK_LEN];
generate_random(PUK, (byte) 16);
init_flag = false;
puk_try_count = (byte) 0;
byte[] InstParam = new byte[(byte)64];
byte iLen = bArray[bOffset];
bOffset = (short) (bOffset+iLen+1);
byte cLen = bArray[bOffset];
bOffset = (short) (bOffset+cLen+1);
byte aLen = bArray[bOffset];
Util.arrayCopy(bArray,(short) (bOffset +1),InstParam,(short)0,(short)aLen);
byte CPassLen = InstParam[0];
byte IPassLen = InstParam[CPassLen+1];
userPin.update(InstParam,(short)1,CPassLen);
register();
}
public static void install(byte[] bArray, short bOffset, byte bLength)
{
new HasinCardApplet(bArray, bOffset, bLength);
}
public boolean select()
{
Util.arrayFillNonAtomic(Message, (short) 0, (short)512, (byte) 0x00);
Util.arrayFillNonAtomic(Hash, (short) 0, (short)512, (byte) 0x00);
Util.arrayFillNonAtomic(Sign, (short) 0, (short)512, (byte) 0x00);
return true;
}
public void deselect()
{
}
public void process(APDU apdu)
{
if (selectingApplet())
{
if(!init_flag) {
send_puk(apdu);
}
return;
}
byte[] buffer = apdu.getBuffer();
if (buffer[ISO7816.OFFSET_CLA] == APPLET_CLA) {
switch (buffer[ISO7816.OFFSET_INS]) {
case VERIFY_PIN:
verify_pin(apdu);
break;
case CHANGE_PIN:
change_pin(apdu);
break;
case UNLOCK_PIN:
unlock_pin(apdu);
break;
case INITIALIZE:
initialize();
break;
case INSERT_MESSAGE:
insert_message(apdu);
break;
case CHECK_MESSAGE:
check_message(apdu);
break;
case GET_HASH:
hash_message();
get_hash(apdu);
break;
case GET_SIGN:
hash_message();
sign_message();
get_sign(apdu);
break;
case VERIFY_SIGN:
verify_sign(apdu);
break;
case TEST:
test(apdu);
break;
default:
ISOException.throwIt(ISO7816.SW_INS_NOT_SUPPORTED);
}
} else {
ISOException.throwIt(ISO7816.SW_CLA_NOT_SUPPORTED);
}
}
private void initialize() {
if ( ! userPin.isValidated() )
ISOException.throwIt(SW_PIN_VERIFICATION_REQUIRED);
if(key_initialization_flag) {
ISOException.throwIt(SW_KEY_IS_INITIALIZED);
}
rsaKey.genKeyPair();
key_initialization_flag = true;
init_flag = true;
}
private void insert_message(APDU apdu) {
byte[] buffer = apdu.getBuffer();
if ( ! userPin.isValidated() )
ISOException.throwIt(SW_PIN_VERIFICATION_REQUIRED);
if(buffer[ISO7816.OFFSET_P1] == (byte) 0x01) {
// reset Message
message_len = 0;
}
short LC = apdu.setIncomingAndReceive();
Util.arrayCopy(buffer, (short) (ISO7816.OFFSET_CDATA), Message, message_len, LC);
message_len = (short) (message_len + LC);
insert_message_flag = true;
}
private void check_message(APDU apdu) {
byte[] buffer = apdu.getBuffer();
if ( ! userPin.isValidated() )
ISOException.throwIt(SW_PIN_VERIFICATION_REQUIRED);
if(insert_message_flag) {
apdu.setIncomingAndReceive();
Util.arrayCopy(Message, (short) 0, buffer, (short) 0, message_len);
apdu.setOutgoingAndSend((short) 0, message_len);
} else {
ISOException.throwIt(SW_MESSAGE_NOT_INSERTED);
}
}
private void hash_message() {
if ( ! userPin.isValidated() )
ISOException.throwIt(SW_PIN_VERIFICATION_REQUIRED);
if(insert_message_flag) {
mDigest.reset();
hash_len = mDigest.doFinal(Message, (short) 0, message_len, Hash, (short) 0);
hash_set_flag = true;
} else {
ISOException.throwIt(SW_MESSAGE_NOT_INSERTED);
}
}
private void sign_message() {
if ( ! userPin.isValidated() )
ISOException.throwIt(SW_PIN_VERIFICATION_REQUIRED);
if(insert_message_flag) {
rsaCipher.init(rsaKey.getPrivate(), Cipher.MODE_ENCRYPT);
sign_len = rsaCipher.doFinal(Hash, (short) 0, hash_len, Sign, (short) 0);
sign_set_flag = true;
} else {
ISOException.throwIt(SW_MESSAGE_NOT_INSERTED);
}
}
private void get_hash(APDU apdu) {
if ( ! userPin.isValidated() )
ISOException.throwIt(SW_PIN_VERIFICATION_REQUIRED);
if(hash_set_flag) {
byte[] buffer = apdu.getBuffer();
Util.arrayCopy(Hash, (short) 0, buffer, (short) 0, hash_len);
apdu.setOutgoingAndSend((short) 0, hash_len);
} else {
ISOException.throwIt(SW_HASH_NOT_SET);
}
}
private void get_sign(APDU apdu) {
if ( ! userPin.isValidated() )
ISOException.throwIt(SW_PIN_VERIFICATION_REQUIRED);
if(sign_set_flag) {
byte[] buffer = apdu.getBuffer();
Util.arrayCopy(Sign, (short) 0, buffer, (short) 0, sign_len);
apdu.setOutgoingAndSend((short) 0, sign_len);
} else {
ISOException.throwIt(SW_SIGN_NOT_SET);
}
}
private void verify_sign(APDU apdu) {
byte[] buffer = apdu.getBuffer();
if ( ! userPin.isValidated() )
ISOException.throwIt(SW_PIN_VERIFICATION_REQUIRED);
apdu.setIncomingAndReceive();
rsaCipher.init(rsaKey.getPublic(), Cipher.MODE_DECRYPT);
short LC = rsaCipher.doFinal(Sign, (short) 0, sign_len, buffer, (short)0);
apdu.setOutgoingAndSend((short)0,LC);
}
private void verify_pin(APDU apdu) {
byte[] buffer = apdu.getBuffer();
if(userPin.getTriesRemaining() == (byte)0)
ISOException.throwIt(SW_CARD_IS_LOCKED);
short LC = (byte)(apdu.setIncomingAndReceive());
if ( userPin.check(buffer, ISO7816.OFFSET_CDATA, (byte)LC) == false )
ISOException.throwIt(SW_VERIFICATION_FAILED);
}
private void change_pin(APDU apdu) {
byte[] buffer = apdu.getBuffer();
if(userPin.getTriesRemaining() == (byte)0)
ISOException.throwIt(SW_CARD_IS_LOCKED);
if ( ! userPin.isValidated() )
ISOException.throwIt(SW_PIN_VERIFICATION_REQUIRED);
short LC = (byte)(apdu.setIncomingAndReceive());
if(LC > MAX_PIN_SIZE)
ISOException.throwIt(SW_NEW_PIN_TOO_LONG);
if(LC < MIN_PIN_SIZE)
ISOException.throwIt(SW_NEW_PIN_TOO_SHORT);
userPin.update(buffer, (short) ISO7816.OFFSET_CDATA, (byte)LC);
}
private void unlock_pin(APDU apdu){
if(puk_try_count >= PUK_TRY_LIMIT){
ISOException.throwIt(SW_PUK_VERIFICATION_REJECTED);
}
byte[] buffer = apdu.getBuffer();
apdu.setIncomingAndReceive();
if (Util.arrayCompare(PUK, (short) 0, buffer, (short) (ISO7816.OFFSET_CDATA), (short) PUK_LEN) == 0) {
userPin.resetAndUnblock();
puk_try_count = (byte) 0;
return;
} else {
puk_try_count = (byte)(puk_try_count + (byte)1);
ISOException.throwIt(SW_PUK_VERIFICATION_FAILED);
}
}
private void generate_random(byte[] buffer,byte len){
rnd.generateData(buffer, (short) 0, (short) len);
}
private void send_puk(APDU apdu){
apdu.setIncomingAndReceive();
byte[] buffer = apdu.getBuffer();
Util.arrayCopy(PUK,(short)0,buffer,(short)0,(short)PUK_LEN);
apdu.setOutgoingAndSend((short) 0, (short) PUK_LEN);
}
}
Appendix 2: GPShell 1.4.4 APDUs:
mode_211
enable_trace
establish_context
enable_trace
enable_timer
card_connect
command time: 15 ms
select -AID E0E1E2E3E4E501
Command --> 00A4040007E0E1E2E3E4E501
Wrapped command --> 00A4040007E0E1E2E3E4E501
Response <-- 26759506800664A82A242E481CD645C59000
command time: 78 ms
send_apdu -sc 1 -APDU 80060000083132333400000000 // verify userPin
Command --> 80060000083132333400000000
Wrapped command --> 80060000083132333400000000
Response <-- 9000
send_APDU() returns 0x80209000 (9000: Success. No error.)
command time: 16 ms
send_apdu -sc 1 -APDU 8000000000 // initialize
Command --> 8000000000
Wrapped command --> 8000000000
send_APDU() returns 0x8010002F (A communications error with the smart card has been detected. Retry the operation.)
I wrote the below simple program to generate a RSA key pair and transfer the public key to outside the card in the APDU response:
public class CryptoRSA extends Applet {
//Abbreviations
private static final boolean NO_EXTERNAL_ACCESS = false;
//Switch case parameters for selecting instruction = INS in apdu command
private static final byte GENERATE_KEY_PAIR = (byte) 0xC0;
//Create object of keys
RSAPrivateKey thePrivateKey = (RSAPrivateKey) KeyBuilder.buildKey(KeyBuilder.TYPE_RSA_PRIVATE, KeyBuilder.LENGTH_RSA_512, NO_EXTERNAL_ACCESS);
RSAPublicKey thePublickKey = (RSAPublicKey) KeyBuilder.buildKey(KeyBuilder.TYPE_RSA_PUBLIC, KeyBuilder.LENGTH_RSA_512, NO_EXTERNAL_ACCESS);
KeyPair theKeyPair = new KeyPair(thePublickKey, thePrivateKey);
public static void install(byte[] bArray, short bOffset, byte bLength) {
new CryptoRSA();
}
protected CryptoRSA() {
register();
}
public void process(APDU apdu) {
if (selectingApplet()) {
return;
}
byte[] buffer = apdu.getBuffer();
short privateKeySize = 0;
short publicKeySize = 0;
byte[] publicArray;
byte[] privateArray;
try {
switch (buffer[ISO7816.OFFSET_INS]) {
case GENERATE_KEY_PAIR:
theKeyPair.genKeyPair();
PrivateKey thePrivateKey = theKeyPair.getPrivate();
PublicKey thePublicKey = theKeyPair.getPublic();
publicKeySize = thePrivateKey.getSize();
privateKeySize = thePrivateKey.getSize();
byte[] publicKey = JCSystem.makeTransientByteArray((short) (publicKeySize), JCSystem.CLEAR_ON_DESELECT);
((RSAPublicKey) thePrivateKey).getExponent(publicKey, (short) publicKeySize);
Util.arrayCopyNonAtomic(publicKey, (short) 0, buffer, (short) 0, (short) (publicKeySize ));
apdu.setOutgoingAndSend((short) 0, (short) (publicKeySize));
break;
default:
ISOException.throwIt(ISO7816.SW_INS_NOT_SUPPORTED);
}
} catch (Exception e) {
if (e instanceof CryptoException) {
short r = ((CryptoException) e).getReason();
ISOException.throwIt(r);
} else {
ISOException.throwIt((short) 0x8888);
}
}
}
}
But when I send the related APDU command to the card, I receive 0x8888 as below:
OSC:: opensc-tool.exe -s 00a40400060102030405dd -s 00c00000
Using reader with a card: ACS CCID USB Reader 0
Sending: 00 A4 04 00 06 01 02 03 04 05 DD
Received (SW1=0x90, SW2=0x00)
Sending: 00 C0 00 00
Received (SW1=0x88, SW2=0x88)
getSize() returns the bit length of the key, not the byte length. You are probably running out of RAM.
2.((RSAPublicKey) thePrivateKey).getExponent(publicKey, (short) publicKeySize);
This won't work! You are asking for the exponent to be stored at offset publicKeySize in array publicKey -- that is, at the very end of the array, where there are precisely 0 bytes left to store it.
By the way, the next time you come across a problem like this you can use ISOException to send debugging data to the outside world. For instance, ISOException.throwIt(privateKeySize) would have found problem 1.
Hi I want to convert Stream to Byte and for this I am using the below code for converting.
void photoChooserTask_Completed(object sender, PhotoResult e)
{
if (e.TaskResult == TaskResult.OK)
{
var imageSrc = new BitmapImage();
imageSrc.SetSource(e.ChosenPhoto);
imgUploadedInsurance.Source = imageSrc;
_BitmapImage.SetSource(e.ChosenPhoto);
image = Converter.StreamToByte(e.ChosenPhoto);
}
}
Below method is used for converting which is returning 0 byte
public static byte[] StreamToByte(Stream input)
{
//byte[] buffer = new byte[16 * 1024];
byte[] buffer = new byte[input.Length];
using (MemoryStream ms = new MemoryStream())
{
int read;
while ((read = input.Read(buffer, 0, buffer.Length)) > 0)
{
ms.Write(buffer, 0, read);
}
// input.CopyTo(ms);
return ms.ToArray();
}
}
You souldn't return ms.ToArray(), but buffer. Here's my version of the method that will work:
public static byte[] StreamToByte(Stream input)
{
byte[] buffer = new byte[input.Length];
input.Read(buffer, 0, buffer.Length);
return buffer;
}
I am trying to SCP from a remote host using JSch. I have successfully copied file form remote host in java STS IDE. However, when I tried to run it in groovy script which I am executing using SOAP UI, I get following error.
Fri Jun 07 16:53:02 IST 2013:INFO:Exception : groovy.lang.MissingMethodException: No signature of method: java.lang.Byte.minus() is applicable for argument types: (java.lang.String) values: [0]
Possible solutions: minus(java.lang.Number), minus(java.lang.Character), plus(java.lang.String), plus(java.lang.Character), plus(java.lang.Number), times(groovy.lang.Closure)
My code is:
import com.jcraft.jsch.*;
import java.io.*;
import java.lang.*;
FileOutputStream fos=null;
try{
String user="soapui";
String host="192.168.1.1";
String rfile="//bin//output.txt";
String lfile="E://temp1.txt";
String prefix=null;
if(new File(lfile).isDirectory()){
prefix=lfile+File.separator;
}
JSch jsch=new JSch();
Session session=jsch.getSession(user, host, 22);
// username and password will be given via UserInfo interface.
UserInfo ui=new MyUserInfo();
session.setUserInfo(ui);
session.connect();
// exec 'scp -f rfile' remotely
String command="scp -f "+rfile;
Channel channel=session.openChannel("exec");
((ChannelExec)channel).setCommand(command);
// get I/O streams for remote scp
OutputStream out=channel.getOutputStream();
InputStream ins=channel.getInputStream();
channel.connect();
byte[] buf=new byte[10240];
// send '\0'
buf[0]=0; out.write(buf, 0, 1); out.flush();
while(true){
int c=checkAck(ins);
if(c!='C'){
break;
}
// read '0644 '
ins.read(buf, 0, 5);
long filesize=0L;
while(true){
if(ins.read(buf, 0, 1)<0){
// error
break;
}
if(buf[0]==' ')break;
//char c1='0';
//long tmp=Long.valueOf(buf[0]-'0');
**filesize=filesize*10L+(long)(buf[0]-'0');**
}
String file=null;
for(int i=0;;i++){
ins.read(buf, i, 1);
if(buf[i]==(byte)0x0a){
file=new String(buf, 0, i);
break;
}
}
log.info("filesize="+filesize+", file="+file);
// send '\0'
buf[0]=0; out.write(buf, 0, 1); out.flush();
// read a content of lfile
fos=new FileOutputStream(prefix==null ? lfile : prefix+file);
int foo;
while(true){
if(buf.length<filesize) foo=buf.length;
else foo=(int)filesize;
foo=ins.read(buf, 0, foo);
if(foo<0){
// error
break;
}
fos.write(buf, 0, foo);
filesize-=foo;
if(filesize==0L) break;
}
fos.close();
fos=null;
log.info("Closing Stream");
if(checkAck(ins)!=0){
System.exit(0);
}
// send '\0'
buf[0]=0; out.write(buf, 0, 1); out.flush();
}
session.disconnect();
System.exit(0);
}
catch(Exception e){
log.info("Exception : " + e);
try{if(fos!=null)fos.close();}catch(Exception ee){}
}
static int checkAck(InputStream ins) throws IOException{
int b=ins.read();
// b may be 0 for success,
// 1 for error,
// 2 for fatal error,
// -1
if(b==0) return b;
if(b==-1) return b;
if(b==1 || b==2){
StringBuffer sb=new StringBuffer();
int c;
while(c!='\n') {
c=ins.read();
sb.append((char)c);
}
if(b==1){ // error
System.out.print(sb.toString());
}
if(b==2){ // fatal error
System.out.print(sb.toString());
}
}
return b;
}
public class MyUserInfo implements UserInfo{
public String getPassword(){ return passwd;}
public boolean promptYesNo(String str){return true;}
String passwd="123";
public String getPassphrase(){return null;}
public boolean promptPassphrase(String message){return true;}
public boolean promptPassword(String message){return true;}
public void showMessage(String s){};
}
What I have debugged is that on line filesize=filesize*10L+(long)(buf[0]-'0'); of code, groovy fails and generates the exception groovy.lang.MissingMethodException: No signature of method: java.lang.Byte.minus(). Please suggest some solution to this issue.
In groovy, '0' is a String constant, not a char or byte. You can't subtract a String from a byte. Convert it to a char or use the first byte:
byte b = 51 // ASCII '3'
assert b - ('0' as char) == 3
assert b - '0'.bytes[0] == 3
A better way to get a digit from a byte is to use Character.digit(). For example:
filesize = filesize * 10L + Character.digit(buf[0], 10)
I am working on implementing a SAMLSLO through HTTP-REDIRECT binding mechanism. Using deflate-inflate tools gives me a DataFormatException with incorrect header check.
I tried this as a stand-alone. Though I did not get DataFormatException here I observed the whole message is not being returned.
import java.io.UnsupportedEncodingException;
import java.util.logging.Level;
import java.util.zip.DataFormatException;
import java.util.zip.Deflater;
import java.util.zip.Inflater;
public class InflateDeflate {
public static void main(String[] args) {
String source = "This is the SAML String";
String outcome=null;
byte[] bytesource = null;
try {
bytesource = source.getBytes("UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
int byteLength = bytesource.length;
Deflater compresser = new Deflater();
compresser.setInput(bytesource);
compresser.finish();
byte[] output = new byte[byteLength];
int compressedDataLength = compresser.deflate(output);
outcome = new String(output);
String trimmedoutcome = outcome.trim();
//String trimmedoutcome = outcome; // behaves the same way as trimmed;
// Now try to inflate it
Inflater decompresser = new Inflater();
decompresser.setInput(trimmedoutcome.getBytes());
byte[] result = new byte[4096];
int resultLength = 0;
try {
resultLength = decompresser.inflate(result);
} catch (DataFormatException e) {
e.printStackTrace();
}
decompresser.end();
System.out.println("result length ["+resultLength+"]");
String outputString = null;
outputString = new String(result, 0, resultLength);
String returndoc = outputString;
System.out.println(returndoc);
}
}
Surprisingly I get the result as [22] bytes, the original is [23] bytes and the 'g' is missing after inflating.
Am I doing something fundamentally wrong here?
Java's String is a CharacterSequence (a character is 2 bytes). Using new String(byte[]) may not correctly convert your byte[] to a String representation. At least you should specify a character encoding new String(byte[], "UTF-8") to prevent invalid character conversions.
Here's an example of compressing and decompressing:
import java.util.zip.Deflater;
import java.util.zip.InflaterInputStream;
...
byte[] sourceData; // bytes to compress (reuse byte[] for compressed data)
String filename; // where to write
{
// compress the data
Deflater deflater = new Deflater(Deflater.DEFAULT_COMPRESSION);
deflater.setInput(sourceData);
deflater.finish();
int compressedSize = deflater.deflate(data, 0, sourceData.length, Deflater.FULL_FLUSH);
// write the data
OutputStream stream = new FileOutputStream(filename);
stream.write(data, 0, compressedSize);
stream.close();
}
{
byte[] uncompressedData = new byte[1024]; // where to store the data
// read the data
InputStream stream = new InflaterInputStream(new FileInputStream(filename));
// read data - note: may not read fully (or evenly), read from stream until len==0
int len, offset = 0;
while ((len = stream.read(uncompressedData , offset, uncompressedData .length-offset))>0) {
offset += len;
}
stream.close();
}