Error 0x6f00 in Sign Method in javacard 2.2.1 - javacard

I wrote this code and I debug it with jcIDE. I have a error 0x6f00 in line signature.sign('''). I sent apdu "00 80 00 00 04 01 02 03 04" for signing operation
.
My key is RSA -1024
RSAPrivateKey thePrivateKey = (RSAPrivateKey) KeyBuilder.buildKey(KeyBuilder.TYPE_RSA_PRIVATE, KeyBuilder.LENGTH_RSA_1024, NO_EXTERNAL_ACCESS);
RSAPublicKey thePublickKey = (RSAPublicKey) KeyBuilder.buildKey(KeyBuilder.TYPE_RSA_PUBLIC, KeyBuilder.LENGTH_RSA_1024, NO_EXTERNAL_ACCESS);
public void generatesignature(APDU apdu)
{
if(!Pin.isValidated())
ISOException.throwIt (ISO7816.SW_SECURITY_STATUS_NOT_SATISFIED);
byte[] buffer=apdu.getBuffer();
// data field of the command APDU
short numdata=(short) buffer[ISO7816.OFFSET_LC];
byte p1=(byte)buffer[ISO7816.OFFSET_P1];
thePrivateKey=(RSAPrivateKey)PrivateKeyArray[p1];
thePublickKey=(RSAPublicKey)PublicKeyArray[p1];
// receive data starting from the offset
// ISO.OFFSET_CDATA
short inputlength= (short) apdu.setIncomingAndReceive();
// it is an error if the number of data bytes
// read does not match the number in Lc byte
if (inputlength == 0)
ISOException.throwIt(ISO7816.SW_WRONG_LENGTH);
try
{
//convert input to hash
MessageDigest digest=MessageDigest.getInstance(MessageDigest.ALG_SHA,false );
short hashlength=digest.doFinal(buffer,ISO7816.OFFSET_CDATA,numdata,Input_Hash,(short)0);
Signature signature=Signature.getInstance(Signature.ALG_RSA_SHA_PKCS1,false);
signature.init(thePrivateKey,Signature.MODE_SIGN);
short hashlength=signature.sign(Input_Hash,(short)0,hashlength,Input_Sign, (short)0);
Util.arrayCopy(Input_Sign,(short)0, buffer, (short)0, signLength);
apdu.setOutgoingAndSend((short)0, ((short)signLength));
}
catch (CryptoException c) {
short reason = c.getReason();
ISOException.throwIt(reason); // for check
}
}
Can everybody help me?exactly in line short hashlength=signature.sign(Input_Hash,(short)0,hashlength,Input_Sign, (short)0);
I have problem. I use catch but code never go in catch.
my result in apdutool on real gemalto 2.2.1 card

byte[] buffer=apdu.getBuffer();
short numdata=(short) buffer[ISO7816.OFFSET_LC];
short inputlength= (short) apdu.setIncomingAndReceive();
if (inputlength == 0)
ISOException.throwIt(ISO7816.SW_WRONG_LENGTH);
//sign
Signature signature=Signature.getInstance(Signature.ALG_RSA_SHA_PKCS1,false);
signature.init(thePrivateKey,Signature.MODE_SIGN);
signLength=signature.sign(buffer,(short)(ISO7816.OFFSET_CDATA & 0xFF), inputlength, buffer, (short)(0));
apdu.setOutgoingAndSend((short)0,signLength);

Related

Properly parse MAC Address

When I use tools such as snmp-walk or snmp-get to query an OID with a return type of MacAddress, It'll always parse the data as a HexString and display it properly. Even when they don't have the MIBs loaded it'll still works.
bash#snmpwalk -v 2c -c public 10.1.2.3 1.3.6.1.4.1.14179.2.2.1.1
SNMPv2-SMI::enterprises.14179.2.2.1.1.1.16.189.24.206.212.64 = Hex-STRING: 10 BD 18 CE D4 40
SNMPv2-SMI::enterprises.14179.2.2.1.1.1.100.233.80.151.114.192 = Hex-STRING: 64 E9 50 97 72 C0
However, I can't seem to get the same result from Lextm.SharpSnmpLib (11.2.0). Data types of MacAddress don't get decoded correctly and it's a manual process to convert it to a proper MAC.
public void WalkTable()
{
const string baseOid = "1.3.6.1.4.1.14179.2.2.1.1"; //The entire table
const string community = "public";
var ep = new IPEndPoint(IPAddress.Parse("10.1.2.3"), 161);
var results = new List<Variable>();
Messenger.Walk(VersionCode.V2, ep, new OctetString(community), new ObjectIdentifier(baseOid), results, 60000, WalkMode.WithinSubtree);
foreach(var v in results)
Console.WriteLine(v.Data.ToString());
}
Am I doing something wrong or is this just how the library works?
You are outputting the MAC Address as ASCII instead of Hex. Here's a quick method I put together that will detect non-ascii characters and output as hex if any are found.
public void WalkTable()
{
const string baseOid = "1.3.6.1.4.1.14179.2.2.1.1"; //The entire table
const string community = "public";
var ep = new IPEndPoint(IPAddress.Parse("10.1.2.3"), 161);
var results = new List<Variable>();
Messenger.Walk(VersionCode.V2, ep, new OctetString(community), new ObjectIdentifier(baseOid), results, 60000, WalkMode.WithinSubtree);
foreach(var v in results)
//If the result is an OctetString, check for ascii, otherwise use ToString()
Console.WriteLine(v.Data.TypeCode.ToString()=="OctetString" ? DecodeOctetString(v.Data.ToBytes()) : v.Data.ToString())
}
}
public string DecodeOctetString(byte[] raw)
{
//First 2 bytes are the Type, so remove them
byte[] bytes = new byte[raw.Length - 2];
Array.Copy(raw, 2, bytes, 0, bytes.Length);
//Check if there are any non-ascii characters
bool ascii = true;
foreach (char c in Encoding.UTF8.GetString(bytes))
{
if (c >= 128)
{
ascii = false;
}
}
//If it's all ascii, return as ascii, else convert to hex
return ascii ? Encoding.ASCII.GetString(bytes) : BitConverter.ToString(bytes);
}

How to manage several Serial messages in processing

I am reading the UID of my RFID card and storing it in a variable called myUID.
After that I am authorizing to the card with the factory key and read block number 4 (which has been written to earlier) and store it in a string readBlock.
On the Arduino, I print out the variables onto the serial interface like so.
Serial.println(myUID);
Serial.println(readBlock);
On the client side, I use a Java program that reads in serial data. My program uses the Processing Library.
Serial mySerial;
PrintWriter output;
void setup() {
output = createWriter( "data.txt" );
mySerial = new Serial( this, Serial.list()[0], 9600 );
mySerial.bufferUntil('\n');
}
void draw(){
while (mySerial.available() > 0) {
String inBuffer = mySerial.readString();
if (inBuffer != null)
output.println(inBuffer);
}
}
void keyPressed() { // Press a key to save the data
output.flush(); // Write the remaining data
output.close(); // Finish the file
exit(); // Stop the program
}
Now my data.txt is expected to look like
xxx xxx xxx xxx (uid of card)
00 00 00 00 00 00 00 00 ... (read block from card)
but looks like
237 63 58 1
07
37 37 95
37
97 98 50 54 37 5
4 55 102 55 52
45 98
I have tried several things like readStringUntil('\n'); in the Processing Library but without success.
For everyone interested, I have fixed the problem myself with many hours of searching Google, so maybe this will help someone in the future:
I could fix it with this code:
import processing.serial.*;
int count = 0;
String input = "";
String fileName = dataPath("SET FILEPATH HERE");
Serial mySerial;
import java.io.*;
void setup() {
mySerial = new Serial(this, Serial.list()[0], 9600);
mySerial.bufferUntil('\n');
File f = new File(fileName);
if (f.exists()) {
f.delete();
}
}
void draw(){}
// listen to serial events happening
void serialEvent(Serial mySerial){
input = mySerial.readStringUntil('\n');
write(input, count);
count++;
}
// function for writing the data to the file
void write(String inputString, int counter) {
// should new data be appended or replace any old text in the file?
boolean append = false;
// just for my purpose, because I have got two lines of serial which need to get written to the file
//(Line 1: UID of card, Line 2: Read block of card)
if(counter < 2){
append = true;
}
else{
count = 0;
}
try {
File file = new File("D:/xampp/htdocs/pizza/src/rfid/data.txt");
if (!file.exists()) {
file.createNewFile();
}
FileWriter fw = new FileWriter(file, append);
BufferedWriter bw = new BufferedWriter(fw);
PrintWriter pw = new PrintWriter(bw);
pw.write(inputString + '\n');
pw.close();
}
catch(IOException ioe) {
System.out.println("Exception ");
ioe.printStackTrace();
}
}

How to convert incoming buffer data from serial port to nodejs

hello I'am using Arduino and node js
I sent and recive data but the data incoming from arduino like this :
<Buffer 00 00 00 e0 e0 e0 00 e0 e0 e0>
<Buffer e0 e0 e0 e0 00 e0 e0 00 e0 00 e0 e0 e0>
How can i decode this to UTF8
arduino
int incomingByte = 0;
void setup() {
Serial.begin(9600); // opens serial port, sets data rate to 9600 bps
}
void loop() {
if (Serial.available() > 0) {
incomingByte = Serial.read(); // read the incoming byte:
Serial.print(incomingByte);
}
}
You can use readable.setEncoding method from Node SerialPort class:
const SerialPort = require('serialport');
var port = new SerialPort("COM3").setEncoding('utf8');
In node.js you can use toString:
console.log(incomeBuffer.toString('utf8'))
incomingByte.toString()
encoding The character encoding to decode to. Default: 'utf8'
look at here
I used the Buffer class to do various conversions to get printable hex data.
const { SerialPort } = require('serialport')
const { Buffer } = require('buffer')
let buffer = []
port.on('data', function (data) {
buffer.push(Buffer.from(data, 'ascii'))
}})
// Button handler or something else
let buffer_ascii = ''
buffer.forEach(chunk => {
buffer_ascii += chunk.toString('hex')
})
console.log(buffer_ascii)

Cannot Append to Received String in UDP Listener C#

I have a Form that create a UDP object, in the UDP class a UDPClient is created and the received data is done in the BeginReceive Method using EndReceive.
When I print the string of the reveived data, after converting the byte[], to the console from within the beginreceive method, with text appended, only the received data prints not the appended text.
So it looks like the received data is incomplete.
When the string prints, the NewLine and appended "done" is not shown.
Any help would be great!!
Thanks
class Udp
{
public EventHandler _dataReceived;
public Udp()
{
int receiverPort = 1248;
UdpClient receiver = new UdpClient(receiverPort);
string discovery = "<?xml version=\"1.0\"?><ServiceQuery></ServiceQuery>";
receiver.BeginReceive(new AsyncCallback( DataReceived), receiver);
IPEndPoint end = new IPEndPoint(IPAddress.Broadcast, 1248);
receiver.Send(Encoding.ASCII.GetBytes(discovery + "\0"), discovery.Length + 1, end);
}
private void DataReceived(IAsyncResult ar)
{
UdpClient c = (UdpClient)ar.AsyncState;
IPEndPoint receivedIpEndPoint = new IPEndPoint(IPAddress.Any, 1248);
Byte[] receivedBytes = c.EndReceive(ar, ref receivedIpEndPoint);
string receivedText = ASCIIEncoding.ASCII.GetString(receivedBytes);
Console.WriteLine("\n");
if(_dataReceived != null)
{
Console.Write(receivedIpEndPoint + ": " + receivedText + Environment.NewLine + "done");
_dataReceived(receivedText, new EventArgs());
}
c.BeginReceive(new AsyncCallback(DataReceived), c);
}
}
The simplest repro I can think of for this problem is this code:
private void button1_Click(object sender, EventArgs e) {
Byte[] receivedBytes = new byte[] { 0x48, 0x65, 0x6c, 0x00, 0x6c, 0x6f };
string receivedText = Encoding.ASCII.GetString(receivedBytes);
Console.Write(receivedText + ", you won't see this");
}
Output after clicking the button several times:
HelHelHelHel
Surely you now recognize the poison-pill in the receivedBytes array, it is the presence of the 0x00 byte that causes the output string to get cut short. Nothing beyond that byte makes it into the Visual Studio Output window.
Explaining this behavior requires a pretty deep dive in how Console.Write() in a Winforms app works and how it is capable of generating output, even though your program has no console. It is a long-winded story that isn't that likely to entertain anybody so I'll punt for the short version. With the Visual Studio Hosting Process debugger option enabled, Console.Write() is equivalent to Debug.Write(). Debug output is intercepted by the DefaultTraceListener class, it pinvokes OutputDebugString() to get the text to appear in the debugger trace window. These winapi functions takes C strings, a C string is zero-terminated to indicate the end of the string.
There are several ways to fix this, the programmer's way is to convert the byte[] array content to hex:
Byte[] receivedBytes = new byte[] { 0x48, 0x65, 0x6c, 0x00, 0x6c, 0x6f };
string receivedText = BitConverter.ToString(receivedBytes);
Console.WriteLine(receivedText + ", you see this");
Output:
48-65-6C-00-6C-6F, you see this
48-65-6C-00-6C-6F, you see this
48-65-6C-00-6C-6F, you see this
Or you might want to take a better look at the data you transmit, ensuring it is actually printable text that can be properly converted with Encoding.ASCII

encrypt PBEWithMD5AndDES in j2me

i'm triing to get this code to work on j2me
(it is working a java program)
but not yet in j2me
public static String generate(String plaintext, String passphase) throws Exception {
try {
PBEKeySpec pbeKeySpec = new PBEKeySpec(passphase.toCharArray());
PBEParameterSpec pbeParamSpec;
SecretKeyFactory keyFac;
// Salt
byte[] salt = {(byte) 0xc8, (byte) 0x73, (byte) 0x61, (byte) 0x1d, (byte) 0x1a, (byte) 0xf2, (byte) 0xa8, (byte) 0x99};
// Iteration count
int count = 20;
// Create PBE parameter set
pbeParamSpec = new PBEParameterSpec(salt, count);
keyFac = SecretKeyFactory.getInstance("PBEWithMD5AndDES");
SecretKey pbeKey = keyFac.generateSecret(pbeKeySpec);
// Create PBE Cipher
Cipher pbeCipher = Cipher.getInstance("PBEWithMD5AndDES");
// Initialize PBE Cipher with key and parameters
pbeCipher.init(Cipher.ENCRYPT_MODE, pbeKey, pbeParamSpec);
// Our cleartext
byte[] cleartext = plaintext.getBytes();
// Encrypt the cleartext
byte[] ciphertext = pbeCipher.doFinal(cleartext);
return ciphertext;
} catch (Exception ex) {
throw new Exception(ex.getMessage());
}
}
i found this lib
http://www.bouncycastle.org/java.html
the important thing is that i find a method for j2me that can encrypt using PBEWithMD5AndDES
anyone know the solution?
edit adding extra info
when i try to add the above code to a mobile project
following classes are not recognized (not included in j2me)
PBEKeySpec
PBEParameterSpec
SecretKeyFactory
so i need a package that allows me to encode plain text using PBEWithMD5AndDES
anyone know such a package compatible with j2me?
thx for the replies so far
A lot can go wrong when applying a primitive, you should use Jasypt.

Resources