Unpack ascii string with hex bitmap in jpos - iso8583

I have an ISO 8583 ascuu message with Bitmap Hex.
I tried to unpack it as follows:
String hexMsg="0110E23800018ED006060000000000000011168...M..."
byte[] bmsg = ISOUtil.hex2byte(hexMsg);
ISOMsg mes = new ISOMsg();
mes.setPackager(new ISO87BPackager());
mes.unpack(bmsg);
But I got into trouble because the message was not hex and it contains the character M, for example
I tried to keep the bitmap separate and hex the rest and again the problem was not solved:
can any body help?

Related

AES-256-CBC encryption algorithm in react-native

Hi am trying to check the compatability of encryption done on BE.
BE provided the below code `
$secret_key = VALUE1`;
$secret_iv = VALUE2;
$encrypt_method = "AES-256-CBC";
$key = hash('sha256', $secret_key);
$iv = substr(hash('sha256', $secret_iv), 0, 16);
openssl_encrypt($string, $encrypt_method, $key, 0, $iv)`
the openssl gave SNtvZ3Dpv1S88Ha6aVBdcg== when input string is abc
I tried few alogritham but I wasnt able to correctly match it with BE
he $key and $iv value I generated same as BE. but when it comes to encryption it doesnt give any result or saying Expected IV length is 16 but got 8
The following are the packages I tried
import Aes from 'react-native-aes-crypto';
Aes.encrypt(inputText, hash, _IV, 'aes-256-cbc').then(cipher => {
console.log('cipher', cipher); });
This throws an error Error: expected IV length of 16 but was 8
I checked the length of _IV and it is certanly 16
import CryptoAesCbc from 'react-native-crypto-aes-cbc';
CryptoAesCbc.encryptInBase64(
base64.encode(ivHash.substr(0, 16)),
base64.encode(hash),
'abc',
'128',
)
.then(encryptString => {
console.log('encryptString', encryptString);
})
.catch(error => {
console.log('error ', error);
});
This the encryptString value prints empty string
Please someone give me some insight into this.
FYI am checking in Android for the time being
EDIT 1
I red in some post about converting to _IV to hex
so I did this
Aes.encrypt(
inputText,
hash,
Buffer.from(_IV).toString('hex'),
'aes-256-cbc',
)
.then(cipherText => console.log('cipherText', cipherText))
.catch(error => console.log('error here', error));
It gave me wrong out out cipherText: yLvY847qCMHHGHdachjKGw==
Any help is appreciated
Thanks in advance
In the hash() function of the PHP code, the third parameter is false by default, so $key and $iv are returned as hex encoded strings and not as raw binary data.
For SHA256 with a digest output length of 32 bytes $key therefore has a length of 64 bytes, since $key is not explicitly truncated, unlike $iv.
Nevertheless, only the first 32 bytes of the 64 bytes are used for encryption, because OpenSSL/PHP silently truncates keys that are too large (and pads keys that are too short with 0x00 values) to achieve the specified length (32 bytes for AES-256-CBC).
On the CryptoJS side, both the hex encoding of key and IV must be taken into account as well as the truncation of the key.
A possible implementation with CryptoJS (referring to your solution in the chat) is:
var plaintext = "The quick brown fox";
var keyMaterial = "my key passphrase";
var ivMaterial = "my IV passphrase"
var truncHexKey = CryptoJS.SHA256(keyMaterial).toString().substr(0, 32); // hex encode and truncate
var truncHexIV = CryptoJS.SHA256(ivMaterial).toString().substr(0, 16); // hex encode and truncate
var key = CryptoJS.enc.Utf8.parse(truncHexKey);
var iv = CryptoJS.enc.Utf8.parse(truncHexIV);
var ciphertext = CryptoJS.AES.encrypt(plaintext, key, {iv: iv}); // default values: CBC, PKCS#7 padding
console.log('Ciphertext: ' + ciphertext.toString());
<script src="https://cdnjs.cloudflare.com/ajax/libs/crypto-js/4.0.0/crypto-js.min.js"></script>
which gives the same ciphertext as the PHP code.
In general, it should also be noted that the use of upper and lower case letters is not consistently implemented in hex encoding. However, like PHP's hash() function, CryptoJS uses lowercase letters, so this is not a problem here.

HMACSHA1 gives different output between JS and VB.Net

I'm trying to translate a JavaScript application of TOTP to VB.Net: http://blog.tinisles.com/2011/10/google-authenticator-one-time-password-algorithm-in-javascript/
I have encountered a problem during translation of the HMAC-part:
//Javascript:
var hmacObj = new jsSHA("Hello World!", 'HEX');
var hmac = hmacObj.getHMAC("secret", 'HEX', 'SHA-1', "HEX");
This is a codesnippet of my translation in VB.Net
'VB.Net:
Dim hmacObjTest As New HMACSHA1(System.Text.Encoding.UTF8.GetBytes("secret"))
Dim hmacTest As Byte() = hmacObjTest.ComputeHash(System.Text.Encoding.UTF8.GetBytes("Hello World!"))
Dim hmacHexTest As New StringBuilder()
For i As Integer = 0 To hmacTest.Length - 1
hmacHexTest.Append(hmacTest(i).ToString("x2"))
Next i
Dim strTest As String = "HMAC = " & hmacHexTest.ToString()
The problem is that i get different output from the two languages:
Output JS: 5efed98b0787c83f9cb0135ba283c390ca49320e //Tested from jsSha demo: http://caligatio.github.io/jsSHA/
Output VB.Net: 87b0154b8420c0b58869ca103f481e824d8876ea
The outputs are not at all the same like they are in this question: hmacsha1 output hex strings different between vb.net and python
Does anyone know where I might be doing something wrong?
Hashes don't work on strings - they work on the binary representation of the string. Now you use UTF-8 as encoding for the dotnet version, while the JavaScript version is very likely not to use UTF-8 - so you get different binary representations, resulting in different hashes.
Use either webttolkit or the hackish var utfstring = unescape(encodeURIComponent(rawstring)); to convert to UTF-8 before calcualting the hash.

Append binary data to serialized xml header

I need to append binary data to file but before this data is an xml header. Whole file wont be proper xml file but it must proper xml header like following:
<EncryptedFileHeader>
<Algorithm>name</Algorithm>
<KeySize>256</KeySize>
<SubblockLength>64</SubblockLength>
<CipherMode>ECB</CipherMode>
<sessionKey>sessionKey</sessionKey>
</EncryptedFileHeader>
*binary data*
The xml header I do with JAXB marshalling easily, and even easier would be to add this binary data in base64 and store in note inside xml. But this is a clue. I have to store it as binary to save this overhead 33% space used by base64.
So the question is how to add this data and of course later read this back (serialize/deserialize) ?
Another question is how to remove from the first line of document?
I tried to use:
marshaller.setProperty("com.sun.xml.bind.xmlDeclaration", Boolean.FALSE);
but it throws an exception:
javax.xml.bind.PropertyException: name: com.sun.xml.bind.xmlDeclaration value: false
at javax.xml.bind.helpers.AbstractMarshallerImpl.setProperty(AbstractMarshallerImpl.java:358)
at com.sun.xml.internal.bind.v2.runtime.MarshallerImpl.setProperty(MarshallerImpl.java:527)
Thanks
Actualy I solved this by serializing xml header with JAXB, then appending binary data (bytearray) to existing file.
Reading from file with buffered reader as follows:
BufferedReader reader = new BufferedReader(new FileReader("filepath"));
String line, results = "";
while ((line = reader.readLine()) != null) {
results += line;
}
reader.close();
String[] splited = results.split("</EncryptedFileHeader>");
splited[0] += "</EncryptedFileHeader>";
String s0 = splited[0];
String s1 = new String(splited[1]);
ByteArrayInputStream bais = new ByteArrayInputStream(s0.getBytes());
Now i got a problem with second splited string s1, which consist data from "byteArrayOutputStream.toByteArray();". Now I have to transfer data from this string to byte array. From:
'��A����g�X���
to something like:
[39, -63, -116, 65, -123, -114, 27, -115, -2, 103, -64, 88, -99, -96, -26, -12]
I tried (on the same machine):
byte[] bytes = s1.getBytes();
but bytes array is different and returns 34 bytes instead 16. I read a lot about encodings but still have no idea.
EDIT:
The problem with different number of bytes was due to the different representation of new line by character and byte streams.

Additional spaces in String having read text file to String using FileInputStream

I'm trying to read in a text file to a String variable. The text file has multiple lines.
Having printed the String to test the "read-in" code, there is an additional space between every character. As I am using the String to generate character bigrams, the spaces are making the sample text useless.
The code is
try {
FileInputStream fstream = new FileInputStream(textfile);
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
//Read corpus file line-by-line, concatenating each line to the String "corpus"
while ((strLine = br.readLine()) != null) {
corpus = (corpus.concat(strLine));
}
in.close(); //Close the input stream
}
catch (Exception e) { //Catch exception if any
System.err.println("Error test check: " + e.getMessage());
}
I'd be grateful for any advice.
Thanks.
Your text file is likely to be UTF-16 (Unicode) encoded. UTF-16 takes two or four bytes to represent each character. For most western text files, the "in-between" bytes are non-printable and will look like spaces.
You can use the second argument of InputStreamReader to specify the encoding.
Alternatively, modify the text file (iconv on Unix, Save As.. dialog in Notepad on Windows):

Encoding UTF8 string to ISO-8859-1 String (VB.NET)

I need to convert UTF8 string to ISO-8859-1 string using VB.NET.
Any example?
emphasized textI have tried Latin function and not runs. I receive incorrect string.
My case is that I need to send SMS using API.
Now I have this code:
baseurl = "http://www.myweb.com/api/sendsms.php"
client = New WebClient
client.Headers.Add("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.0.3705;)")
client.Encoding = System.Text.Encoding.GetEncoding("ISO-8859-1")
client.QueryString.Add("user", user)
client.QueryString.Add("password", pass)
client.QueryString.Add("alias", myAlias)
client.QueryString.Add("dest", mobile)
textoSms = Me.mmTexto.Text
textoSms = System.Web.HttpUtility.UrlEncode(textoSms)
client.QueryString.Add("message", textoSms)
data = client.OpenRead(baseurl)
reader = New StreamReader(data)
s = reader.ReadToEnd()
data.Close()
reader.Close()
But not runs...I receive incorrect messages. For example
if I write: mañana returns maa ana
If I write aigüa returns aiga
How about:
Dim converted as Byte() = Encoding.Convert(utf8, Encoding.UTF8, _
Encoding.GetEncoding(28591))
That assumes that when you say "UTF8 string" you mean "binary data which is the UTF-8 representation of some text". If you mean something else, please specify :)
Note that ISO-8859-1 only represents a tiny proportion of full Unicode. IIRC, you'll end up with "?" for any character from the source data which isn't available in ISO-8859-1.
The encoding ISO-8859-1 is more commonly called Latin-1. You can get this encoding by doing the following
Dim latin1 = Text.Encoding.GetEncoding(&H6FAF)
The full conversion can be done by the following
Public Function ConvertUtf8ToLatin1(Dim bytes As Byte()) As Bytes()
Dim latin1 = Text.Encoding.GetEncoding(&H6FAF)
Return Encoding.Convert(Encoding.UTF8, latin1, bytes)
End Function
EDIT
As Jon pointed out, it may be easier for people to remember the decimal number 28591 rather than the hex number &H6FAF.
Because System.Text.Encoding.GetEncoding("ISO-8859-1") does not support ñ is my guess, in that case you need to use another encoding type for you SMS.
Please read The Absolute Minimum Every Software Developer Absolutely, Positively Must Know About Unicode and Character Sets (No Excuses!)
http://msdn.microsoft.com/en-us/library/system.text.encoding.convert.aspx
Try this with the variable "input" as the UTF-8 String;
VB.NET:
Dim result As Byte() = Encoding.Convert(Encoding.UTF8, Encoding.GetEncoding("iso-8859-1"), input);
C#:
byte[] result = Encoding.Convert(Encoding.UTF8, Encoding.GetEncoding("iso-8859-1"), input);
Dont know if this should be posted here but i made a small function in C# to check if a string support the target encoding type.
Hope it can be of any help...
/// <summary>
/// Function for checking if a string can support the target encoding type
/// </summary>
/// <param name="text">The text to check</param>
/// <param name="targetEncoding">The target encoding</param>
/// <returns>True if the encoding supports the string and false if it does not</returns>
public bool SupportsEncoding(string text, Encoding targetEncoding)
{
var btext = Encoding.Unicode.GetBytes(text);
var bencodedtext = Encoding.Convert(Encoding.Unicode, targetEncoding, btext);
var checktext = targetEncoding.GetString(bencodedtext);
return checktext == text;
}
//Call the function demo with ISO-8859-1/Latin-1
if (SupportsEncoding("some text...", Encoding.GetEncoding("ISO-8859-1")))
{
//The encoding is supported
}
else
{
//The encoding is not supported
}