this is my first post! So if anything is wrong please tell me, i am new to android developing! Here is my question:
I am trying to generate HMAC-SHA1 with input is Hexstring for example the input key is "2cb1b780138bc273459232edda0e4b96" and input value is HexString too but way longer than the key, all the value and the key are Hexstring not character or normal string, so how can i achieve this? I searched a lot but all the result came to use the value and the key in normal string like "The quick brown fox jumps over the lazy dog"
I tried using convertHextoString code to change my HexString into Character string and put in the function like you did but the converted String from convertHextoString appear to have many SPECIAL CHARACTERS such as "\n" or ":" or "%" and so on and i think that is the problem why i got the wrong output. Here is my convertHextoString function
public String convertHexToString(String hex){
StringBuilder sb = new StringBuilder();
StringBuilder temp = new StringBuilder();
//49204c6f7665204a617661 split into two characters 49, 20, 4c...
for( int i=0; i<hex.length()-1; i+=2 ){
//grab the hex in pairs
String output = hex.substring(i, (i + 2));
//convert hex to decimal
int decimal = Integer.parseInt(output, 16);
//convert the decimal to character
sb.append((char)decimal);
temp.append(decimal);
}
System.out.println("Decimal : " + temp.toString());
return sb.toString();
}
and the function to HMAC:
static String hash_hmac(String type, String value, String key) {
try { Log.i("Hien - value - hmac",value);
javax.crypto.Mac mac = javax.crypto.Mac.getInstance(type);
javax.crypto.spec.SecretKeySpec secret = new javax.crypto.spec.SecretKeySpec(key.getBytes(), type);
mac.init(secret);
byte[] digest = mac.doFinal(value.getBytes());
StringBuilder sb = new StringBuilder(digest.length*2);
String s;
for (byte b : digest){
s = Integer.toHexString(b & 0xff);
if(s.length() == 1) sb.append('0');
sb.append(s);
}
return sb.toString();} catch (Exception e) { android.util.Log.v("TAG","Exception ["+e.getMessage()+"]", e); } return ""; }
Please help!
Related
I am using an Android Cilico F750 and the dedicated RFID reader is CF-RS103.
The RFID tag type is MIFARE Ultralight type C.
When read with a dedicated card reader the id of tag is: 2054270212(10 digit).
But when read with Android phone the id is: 36139312876727556(17digit) and reversed id is: 1316602805183616 (16digit).
Does anyone know why this happens and if its possible to convert the 10digit id to 17digit id or vice versa.
I use intents to detect tag and to resolve intent I use this:
public void resolveIntent(Intent intent){
String action = intent.getAction();
if(NfcAdapter.ACTION_TAG_DISCOVERED.equals(action)
||NfcAdapter.ACTION_TECH_DISCOVERED.equals(action)
||NfcAdapter.ACTION_NDEF_DISCOVERED.equals(action))
{
Parcelable[] rawMsgs = intent.getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES);
NdefMessage[] msgs;
if(rawMsgs!=null)
{
msgs= new NdefMessage[rawMsgs.length];
for(int i=0; i<rawMsgs.length; i++)
{
msgs[i]=(NdefMessage) rawMsgs[i];
}
}
else
{
byte[] empty = new byte[0];
byte[] id = intent.getByteArrayExtra(NfcAdapter.EXTRA_ID);
Tag tag = (Tag) intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
byte[] payload = dumpTagData(tag).getBytes();
NdefRecord record = new NdefRecord(NdefRecord.TNF_UNKNOWN,empty,id,payload);
NdefMessage msg = new NdefMessage(new NdefRecord[]{record});
msgs= new NdefMessage[] {msg};
}
displayMsgs(msgs);
}}
And this are my helper functions:
private void displayMsgs(NdefMessage[] msgs)
{
if(msgs==null || msgs.length==0) {
return;
}
StringBuilder builder = new StringBuilder();
List<ParsedNdefRecord> records= NdefMessageParser.parse(msgs[0]);
final int size = records.size();
for(int i=0;i<size;i++)
{
ParsedNdefRecord record = records.get(i);
String str = record.str();
builder.append(str).append("\n");
}
text.setText(builder.toString());
}
private String dumpTagData(Tag tag) {
StringBuilder sb = new StringBuilder();
byte[] id = tag.getId();
sb.append("ID (hex): ").append(toHex(id)).append('\n');
sb.append("ID (reversed hex):").append(toReversedHex(id)).append('\n');
sb.append("ID (dec): ").append(toDec(id)).append('\n');
sb.append("ID (reversed dec):").append(toReversedDec(id)).append('\n');
String prefix = "android.nfc.tech.";
sb.append("Technologies: ");
for (String tech: tag.getTechList()) {
sb.append(tech.substring(prefix.length()));
sb.append(", ");
}
sb.delete(sb.length() - 2, sb.length());
for (String tech: tag.getTechList()) {
if (tech.equals(MifareClassic.class.getName())) {
sb.append('\n');
String type = "Unknown";
try {
MifareClassic mifareTag = MifareClassic.get(tag);
switch (mifareTag.getType()) {
case MifareClassic.TYPE_CLASSIC:
type = "Classic";
break;
case MifareClassic.TYPE_PLUS:
type = "Plus";
break;
case MifareClassic.TYPE_PRO:
type = "Pro";
break;
}
sb.append("Mifare Classic type: ");
sb.append(type);
sb.append('\n');
sb.append("Mifare size: ");
sb.append(mifareTag.getSize() + " bytes");
sb.append('\n');
sb.append("Mifare sectors: ");
sb.append(mifareTag.getSectorCount());
sb.append('\n');
sb.append("Mifare blocks: ");
sb.append(mifareTag.getBlockCount());
} catch (Exception e) {
sb.append("Mifare classic error: " + e.getMessage());
}
}
if (tech.equals(MifareUltralight.class.getName())) {
sb.append('\n');
MifareUltralight mifareUlTag = MifareUltralight.get(tag);
String type = "Unknown";
switch (mifareUlTag.getType()) {
case MifareUltralight.TYPE_ULTRALIGHT:
type = "Ultralight";
break;
case MifareUltralight.TYPE_ULTRALIGHT_C:
type = "Ultralight C";
break;
}
sb.append("Mifare Ultralight type: ");
sb.append(type);
}
}
return sb.toString();
}
private String toHex(byte[] bytes) {
StringBuilder sb = new StringBuilder();
for (int i = bytes.length - 1; i >= 0; --i) {
int b = bytes[i] & 0xff;
if (b < 0x10)
sb.append('0');
sb.append(Integer.toHexString(b));
if (i > 0) {
sb.append(" ");
}
}
return sb.toString();
}
private String toReversedHex(byte[] bytes) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < bytes.length; ++i) {
if (i > 0) {
sb.append(" ");
}
int b = bytes[i] & 0xff;
if (b < 0x10)
sb.append('0');
sb.append(Integer.toHexString(b));
}
return sb.toString();
}
private long toDec(byte[] bytes) {
long result = 0;
long factor = 1;
for (int i = 0; i < bytes.length; ++i) {
long value = bytes[i] & 0xffl;
result += value * factor;
factor *= 256l;
}
return result;
}
private long toReversedDec(byte[] bytes) {
long result = 0;
long factor = 1;
for (int i = bytes.length - 1; i >= 0; --i) {
long value = bytes[i] & 0xffl;
result += value * factor;
factor *= 256l;
}
return result;
}`
EDIT: I managed to resolve this issue by truncating the 7-byte HEX ID to 4-bytes.
And then formating the decimal ID if its total lenght is less than 10 digits with this statement that basically adds zeroes from left side if DEC ID is smaller than 10 digits:
String strFinal=String.format("%010d", Long.parseLong(str));
This document that describes how the ID is converted from HEX8 TO DEC10 helped me alot aswell: https://www.batag.com/download/rfidreader/LF/RAD-A200-R00-125kHz.8H10D.EM.V1.1.pdf
And a huge thanks to #Andrew and #Karam for helping me resolve this!
The card reader on the PC is configured wrong, it is configured by default to display the ID as 10 digit decimal number (4 byte) when the card has a 7 byte ID.
It thus has to loose some data, it is doing this by truncating the ID to the first 4 bytes of the 7 byte ID
Use the software on the PC change the output format to something suitable for the ID size on the Mifare Ultralight C cards (8 Hex?)
or
Use Mifare Classic cards instead as these had 4 byte ID
or
truncate the 7 byte ID to 4 bytes e.g. change bytes.length to 4 (a hard coding to the first 4 bytes in the 7 byte ID) in your code and handle the fact that there is a very large number (around 16.7 million) of Mifare Ultralight C cards that will seem to have the same "ID" as you want to display it
This is because the spec's give by a seller on Amazon https://www.amazon.co.uk/Chafon-CF-RS103-Multiple-Support-Compatible-Black/dp/B017VXVZ66 (I cannot find any details on the manufacturer's site)
It says "Default output 10 digit Dec, control output format through software. "
"Support with windows,linux and android system, but can only set output format in windows pcs.No programming and software required, just plug and play. "
The only sensible answer is move everything to use a 7 byte ID.
I don't know why are you trying always to convert to decimal?
and please try to explain more about the code you use to read the UID.
about your numbers and to convert 17 digits to 10 digits; I convert both of them to Hex:
36139312876727556(17digit) in Hex : 8064837A71AD04.
2054270212(10 digit) in Hex: 7A71AD04
as you notice you can just tirm first three bytes to get the 10 digits.
and I do belive the both of them are not the UID. but the 7bytes as sayed Andrew, and you already read it in the your photo : (04:B5:71:7A:83:64:80)
So I think the answer is that because you are converting a 7 byte ID to decimal you are getting variable lengths of numbers because of the conversion to decimal.
"The byte data type is an 8-bit signed two's complement integer. It has a minimum value of -128 and a maximum value of 127 (inclusive)."
From https://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html
Could generate a decimal number with 1,2 or 3 characters thus as decimal the id can vary in length.
It also looks like that conversion is going wrong as in theory it should have negative numbers in there as well.
It is much better to handle it as a hex string if you want it to be human readable.
The correct method in Java to convert the 2 pages of the ID to hex is
StringBuilder Uid;
for (int i = 0; i < result.length; i++) {
// byte 4 is a check byte
if (i == 3) continue;
Uid.append(String.format("%02X ", result[i]));
}
Note as per the spec sheet of the card https://www.nxp.com/docs/en/data-sheet/MF0ICU2_SDS.pdf (Section 7.3.1)
There is check byte that is part of the ID, while this will always be the same on the same card and will still give you a unique ID it is technically not part of the ID.
Or if not reading at a low level then
https://developer.android.com/reference/android/nfc/Tag#getId()
will get you the id.
Note that the "36139312876727556(17digit) and reversed id" when converted to hex and reversed actual is 7 bytes and start with the right number.
The 10 digit just looks like the first 4 bytes of the 7 byte number also reversed.
In anroid emoji convert to unicode time alwasy get output U+5c but we give emoji string "\uD83D\uDE21" this method it's working
String a = emojiconEditText.getText().toString().trim();
String text = new String(
StringEscapeUtils.escapeJava(a).getBytes(),
StandardCharsets.UTF_8
);
int codepoint = text.codePointAt(0);
String yourUnicode = "U+"+Integer.toHexString(codepoint);
You can encode/decode emojis to the following unicode UTF-8, UTF-16 and U+<hex> using the below:
try {
//I am assuming you are getting unicode from an inputbox
String emoji = emojiconEditText.getText().toString().trim();
//I am also assuming you are getting emoji in hexadecimal form `U+<hexdigits>`
String unicodeHexEmoji = "U+";
StringBuilder sb = new StringBuilder();
//Firstly you want to encode emojis to unicode types by converting to byte array
byte[] utf8Bytes = emoji.getBytes("UTF-8"); // "\\uf0\\u9f\\u98\\u80"
byte[] utf16Bytes = emoji.getBytes("UTF-16"); // "\\ud83d\\ude00"
//convert emoji to hex
for (byte b : utf16Bytes ) {
sb.append(String.format("%02x", b));
}
//we are converting our current emoji to hex just for the purpose of this example
unicodeHexEmoji += sb; //yields "U+feffd83dde21";
byte[] utfHexBytes = getByteFromHex(unicodeHexEmoji.replace("U+","")); // "\\ud83d\\ude00"
//NB: we removed "U+" because its only a prefix denoting that the string is a <hex>
//Decoding our unicodes back to emoji string
String emojiUTF_8 = new String(utf8Bytes,"UTF-8");
String emojiUTF_16 = new String(utf16Bytes,"UTF-16");
String emojiUTF_hex = new String(utfHexBytes,"UTF-16");
Log.d("Tag", "emojiUTF_8 : "+ emojiUTF_8);
Log.d("Tag", "emojiUTF_16 : "+ emojiUTF_16)
Log.d("Tag", "emojiUTF_hex : "+ emojiUTF_hex)
//output
//emojiUTF-8 : đŸ˜€
//emojiUTF-16 : đŸ˜€
//emojiUTF-hex : đŸ˜¡
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
...
public byte[] getByteFromHex(String hexString){
//To convert hex string to byte array, you need to first get the length
//of the given string and include it while creating a new byte array.
byte[] val = new byte[hexString.length() / 2];
for (int i = 0; i < val.length; i++) {
int index = i * 2;
int j = Integer.parseInt(hexString.substring(index, index + 2), 16);
val[i] = (byte) j;
}
return val;
}
Hi I have a csv that looks like this:
r1c1|r1c2|r1c3
r2c1|r2c2|r2c3
As you can see it is delimited by the character "|"
In my application, I am trying to explode this using input stream. Here is my code:
String line = "";
String cvsSplitBy = "|";
try {
File initialFile = new File(myfile.txt);
InputStream targetStream = new FileInputStream(initialFile);
BufferedReader reader = new BufferedReader(new InputStreamReader(targetStream));
while ((line = reader.readLine()) != null) {
String[] RowData = line.split(cvsSplitBy);
String c0 = RowData[0];
String c1 = RowData[1];
String c2 = RowData[2];
Toast.makeText(mainactivity.this, c2, Toast.LENGTH_LONG).show();
}
}catch (IOException ex) {
// handle exception
}
Unfortunately, this appears to return each character in the csv as a row. The toast example above returns 1 then 2.
Any ideas how to return the proper column, anyone?
split() splits string around matches of the given regular expression, therefore use of special character (and vertical bar is one of these) requires escaping to strip its "powers".
String cvsSplitBy = "\\|"
See docs: http://docs.oracle.com/javase/7/docs/api/java/lang/String.html
I work with my custom USB Device. I get from it bytes array. I want to display this array as hex string so I convert it firstly into Long like this :
byte[] receivedTag = connector.receive(512);
String tag = null;
if (receivedTag != null) {
long tagValue = ByteBuffer.wrap(receivedTag).getLong();
Next I want to convert it into hex String :
tag = Long.toHexString(tagValue);
however I've got problem here. Received Tag has something about 400 bytes (I've checked it on debug) , but when I convert it , tag is only 16 chars long(8 bytes, there are correct). Why is that ?
public static String bytesToHex(byte[] in) {
final StringBuilder builder = new StringBuilder();
for(byte b : in) {
builder.append(String.format("%02x", b));
}
return builder.toString();
}
// consider using this
I am attempting to scoop some utf-8 encoded (Spanish text) data from a sqlite database and then display it in a webview. The essential parts of the code are as follows:
String web_data_string = cursor.getString(0);
webview.loadData(web_data_string, "text/html", "utf-8");
The string is a word containing all normal characters except one which should be a lower-case e+acute. In the webview all the normal characters appear correctly, but the e+acute appears as two characters, an A+tilde followed by a copyright symbol.
Where did I go wrong?
EDIT: +1 to dd619 for a solution that can be made to work, but I am hoping for a more general solution where there may be many more special characters, in other languages too.
This does the trick...
String web_data_string = cursor.getString(0);
webview.loadData(utf_eight_to_web(web_data_string), "text/html", "utf-8");
String utf_eight_to_web(String str)
{
String ans = "";
Character c;
for(int i = 0;i<str.length();i++)
{
c = str.charAt(i);
if (c <= 127)
{
ans += str.charAt(i);
}
else
{
ans += String.format("&#%d;",(int)c);
}
}
return ans;
}
If you have any special character/letter then you need to replace it with respective escape character sequence.
Have a look at this useful link.
I had the same problem with some Spanish characters e.g.Ă¡ and i solved it by replacing Ă¡ with \u00e1
e.g. if you want to print "ParĂ¡metros" then simply do.
String str="ParĂ¡metros";
str=str.replace("Ă¡","\u00e1");
Log.i("MyClass",str);
Now you can str in database or java or in C++ or any web platform!
The Mick's answer could be improved using StringBuilder:
private String utfEightToWeb(String str)
{
StringBuilder stringBuilder = new StringBuilder();
Character c;
for (int i = 0; i<str.length(); i++) {
c = str.charAt(i);
if (c <= 127) {
stringBuilder.append(str.charAt(i));
} else {
stringBuilder.append(String.format("&#%d;",(int)c));
}
}
return stringBuilder.toString();
}