Diffie-Hellman crack with partial info known - java

This is school work.
I'm given the problem of finding the private keys of both parties in a DH exchange. The numbers involved in the tests aren't big enough and the task is basically brute-force.
In the task, I can get the prime p, generator g and Alice's public key A.
I'm also given the methods to encrypt a message and decrypt a message with a custom key.
Right now I've only gotten a by simply looping through integers i=1...p and checking if g^i mod p == g^A mod p and promptly returning the first value that meets the requirement.
However, my solution isn't always true according to automated tests.
Anyone know how or even if it's possible to fins a and b with the given info?

Thanks to a third party, I managed to crack the DH code:
public Integer crackAlice() {
// TODO
Integer alicePrivate = 0;
int p = session.getP();
int g = session.getG();
int A = session.getAlicesPublicKey();
// A = g^a mod p
System.out.println("Alice public A: "+A);
String message = String.valueOf(156215);
for (int i = 1; i < p; i++) {
if (BigInteger.valueOf(g).pow(i).mod(BigInteger.valueOf(p)).equals(BigInteger.valueOf(A))) {
//System.out.println("\t\t\t\t"+BigInteger.valueOf(g).pow(i));
alicePrivate = i;
System.out.println("Potential Alice private a: "+i);
//break;
}
}
return alicePrivate;
}
and
public Integer crackBob() {
// TODO
Integer bobPrivate = 0;
Integer a = crackAlice();
int p = session.getP();
int g = session.getG();
int A = session.getAlicesPublicKey();
String mainMessage = "teade";
String msg = null;
try {
msg = session.getEncrypted(mainMessage);
} catch (Exception e) {
e.printStackTrace();
}
for (int i = 1; i < p; i++) {
int ai = a*i;
int Ai = A*i;
//System.out.println("a*b = "+ai);
BigInteger bigintP = BigInteger.valueOf(p);
if (((BigInteger.valueOf(g).pow(a).mod(bigintP)).pow(i)).mod(bigintP)
.equals(((BigInteger.valueOf(g).pow(i).mod(bigintP)).pow(a)).mod(bigintP))) {
String decrypt = null;
try {
decrypt = session.getDecryptedWithCustomKey(msg, BigInteger.valueOf(g).pow(a*i).mod(bigintP).intValue());
} catch (Exception e) {
e.printStackTrace();
}
if (decrypt != null && decrypt.trim().equals(mainMessage)) {
bobPrivate = i;
break;
}
}
}
return bobPrivate;
}
I hope this will help out other with a similar problem.

Related

Saving serial data in Processing

Hello all for the second time,
Initially I was looking for a broad answer, but this thread got blocked for being "too broad"... so I've got no choice, but to go into detail. My apologies if asking the question again is against the forum guidelines, I'm new to stackoverflow so please be kind.
I’ve got data coming into a serial port at 250Hz and I’d like to save it all to a .csv file. Of course draw() is not going to be able to keep up with that rate of data...
At the moment I am using the serialEvent(port) to collect and parse the data. Once parsed out, I'm calling a function in draw to add the data to a new line in a table and then saving that table every 5 seconds...
Yes, I see the obvious flaw that if I'm saving the current data in draw then of course it's not going to be able to save all the data coming in, but rather just the data that happens to be present when the data saving function is called... but I'm not sure of the best way to solve that. A buffer scheme? Or can I have a separate thread that just adds ALL data coming in to a table?
which lead to my initial (broad) question...
Is there a way to save all incoming data to a file without polling?
Thanks to all in advance.. code below:
Twain
import processing.serial.*;
import static javax.swing.JOptionPane.*;
Table table;
String Path = "PathProvidedHere.csv";
String message;
//Some time keeping variables
int hours, minutes, seconds, milliseconds;
float SaveTime;
//Serial port selection
Serial myPort;
String COMx, COMlist = "";
final boolean debug = true;
String portName;
// Data variables
float yaw = 0.0; float pitch = 0.0; float roll = 0.0;
float A1, A2, A3, A4;
float E1, E2, E3, E4;
void setup()
{
//Set up GIU box
size(1024, 768, P3D);
frameRate(250);
smooth();
//Some other setups like fonts, graphs, etc.
//Set up the logging table
table = new Table();
table.addColumn("A1"); table.addColumn("A2"); table.addColumn("A3"); table.addColumn("A4");
table.addColumn(""); table.addColumn("E1"); table.addColumn("E3"); table.addColumn("E4");
table.addColumn(" "); table.addColumn("min"); table.addColumn("sec"); table.addColumn("milli");
portName = chooseCOM();
delay(1000);
}
void draw()
{
SavetoCSV();
//serialEvent(myPort); // read and parse incoming serial message
ACouple();
Unrelated();
FunctionsHere();
if(millis() - SaveTime > 5000)
{
saveTable(table, Path);
SaveTime=millis();
}
}
String chooseCOM()
{
setupP2 = true;
try
{
if (debug) printArray(Serial.list());
int i = Serial.list().length;
if (i != 0)
{
if (i >= 2)
{
// need to check which port the inst uses -
// for now we'll just let the user decide
for (int j = 0; j < i; )
{
COMlist += char(j+'a') + " = " + Serial.list()[j];
if (++j < i) COMlist += ", ";
}
COMx = showInputDialog("Which COM port is correct? (a,b,..):\n"+COMlist);
if (COMx == null) exit();
if (COMx.isEmpty()) exit();
i = int(COMx.toLowerCase().charAt(0) - 'a') + 1;
}
String portName = Serial.list()[i-1];
if (debug) //println(portName + " Selected");
myPort = new Serial(this, portName, 115200); // change baud rate to your liking
myPort.bufferUntil(13); // buffer until CR/LF appears, but not required..
return portName;
}
else
{
showMessageDialog(frame, "Device is not connected to the PC");
exit();
}
}
catch (Exception e)
{ //Print the type of error
showMessageDialog(frame, "COM port is not available (may\nbe in use by another program)");
//println("Error:", e);
exit();
}
return "noPort";
}
void serialEvent(Serial myPort)
{
int newLine = 13; // new line character in ASCII
do
{
message = myPort.readStringUntil(newLine); // read from port until new line
if (message != null)
{
String[] list = split(trim(message), " ");
if (list.length == 4 && list[0].equals("i"))
{
yaw = float(list[1]); // convert to float yaw
pitch = float(list[2]); // convert to float pitch
roll = float(list[3]); // convert to float roll
}
else if (list.length == 5 && list[0].equals("s"))
{
A1 = float(list[1]);
A2 = float(list[2]);
A3 = float(list[3]);
A4 = float(list[4]);
}
else if (list.length >=2 && list[0].equals("b"))
{
Battery = int(list[1]);
}
else if (list.length >= 2 && list[0].equals("m"))
{
MACid = int(list[1]);
}
else
{
//print anything extra to console
//println(message);
}
}
} while (message != null);
}
void SavetoCSV()
{
if (A1 != 0)
{
TableRow newRow = table.addRow();
newRow.setFloat("A1", (A1));
newRow.setFloat("A2", (A2));
newRow.setFloat("A3", (A3));
newRow.setFloat("A4", (A4));
//saveTable(table, Path);
}
}
Additional info:
- Processing P3
- For the record, with the rest of my script I can get draw up to 80hz or so
- I'd be okay with saving all the data and parsing it later
Went the buffer route.... I think I'm getting close now. Unsure if I'm saving the data in the right order or if the saving process will halt the rest of the processes...
Code:
import processing.serial.*;
import static javax.swing.JOptionPane.*;
//Arrays to save the data
LinkedList<Integer> A1c = new LinkedList<Integer>();
LinkedList<Integer> A2c = new LinkedList<Integer>();
LinkedList<Integer> A3c = new LinkedList<Integer>();
LinkedList<Integer> A4c = new LinkedList<Integer>();
int bufferLength = 500;
int bufflen = 0;
//Serial port selection
Serial myPort;
String COMx, COMlist = "";
final boolean debug = true;
String portName;
// Data variables
float yaw = 0.0; float pitch = 0.0; float roll = 0.0;
float A1, A2, A3, A4;
//Data log variables
Table table;
String Path = "PathtoFile.csv";
void setup() {
//Set up GIU box
size(1024, 768, P3D);
frameRate(250);
strokeWeight(50);
smooth();
//Set up the logging table
table = new Table();
table.addColumn("A1"); table.addColumn("A2"); table.addColumn("A3"); table.addColumn("A4");
portName = chooseCOM();
}
void draw() {
//SavetoCSV now called within SerialEvent()
//SavetoCSV();
//serialEvent(myPort); // read and parse incoming serial message
Some();
Unrelated();
FunctionsHere();
}
void serialEvent(Serial myPort) {
int newLine = 13; // new line character in ASCII
do {
message = myPort.readStringUntil(newLine); // read from port until new line
if (message != null) {
String[] list = split(trim(message), " ");
if (list.length == 4 && list[0].equals("i")) {
yaw = float(list[1]); // convert to float yaw
pitch = float(list[2]); // convert to float pitch
roll = float(list[3]); // convert to float roll
} else if (list.length == 5 && list[0].equals("s")) {
A1 = float(list[1]);
A2 = float(list[2]);
A3 = float(list[3]);
A4 = float(list[4]);
if (bufflen < bufferLength) {
A1c.push(int(A1));
A2c.push(int(A2));
A3c.push(int(A3));
A4c.push(int(A4));
bufflen++;
}
else{
bufflen = 0;
SavetoCSV();
}
} else if (list.length >=2 && list[0].equals("b")) {
Battery = int(list[1]);
} else if (list.length >= 2 && list[0].equals("m")) {
MACid = int(list[1]);
} else {
//print anything extra to console
//println(message);
}
}
} while (message != null);
}
void SavetoCSV() {
if (A1 != 0) {
for (int i = bufferLength - 1; i >= 0; i--){
if (i < bufferLength){
TableRow newRow = table.addRow();
newRow.setFloat("A1", (A1c.get(i)));
newRow.setFloat("A2", (A2c.get(i)));
newRow.setFloat("A3", (A3c.get(i)));
newRow.setFloat("A4", (A4c.get(i)));
} else saveTable(table, Path);
}
}
}
String chooseCOM() {
setupP2 = true;
try {
if (debug) printArray(Serial.list());
int i = Serial.list().length;
if (i != 0) {
if (i >= 2) {
// need to check which port the inst uses -
// for now we'll just let the user decide
for (int j = 0; j < i; ) {
COMlist += char(j+'a') + " = " + Serial.list()[j];
if (++j < i) COMlist += ", ";
}
COMx = showInputDialog("Which COM port is correct? (a,b,..):\n"+COMlist);
if (COMx == null) exit();
if (COMx.isEmpty()) exit();
i = int(COMx.toLowerCase().charAt(0) - 'a') + 1;
}
String portName = Serial.list()[i-1];
if (debug) //println(portName + " Selected");
myPort = new Serial(this, portName, 115200); // change baud rate to your liking
myPort.bufferUntil(13); // buffer until CR/LF appears, but not required..
return portName;
} else {
showMessageDialog(frame, "Device is not connected to the PC");
exit();
}
}
catch (Exception e)
{ //Print the type of error
showMessageDialog(frame, "COM port is not available (may\nbe in use by another program)");
//println("Error:", e);
exit();
}
return "noPort";
}

JPA/Hibernate/Spring - Primary key exception

Eclipse throws me an exception - Duplicate entry '201805091-1' for key 'PRIMARY'. I understand that exception, but I do not understand why the code below makes a new record in my database. I thought this should work like: If the combination of date and doctors id does not exist - then make it otherwise use the combination that is currently in database. But there must be obviously something wrong...
Thank you very much :)
OperationsDate od = null; // these 6 lines of the code may be problematic
if(em.find(OperationsDate.class, id) != null) {
od = em.find(OperationsDate.class, id);
} else {
od = new OperationsDate(id);
}
public void process(List<Integer> list, int doctorId, String pin, boolean inf) {
Patient p = em.find(Patient.class, pin);
Doctor d = em.find(Doctor.class, doctorId);
p.addDoctor(d);
d.addPatient(p);
int id = countId(doctorId);
OperationsDate od = null;
if(em.find(OperationsDate.class, id) != null) {
od = em.find(OperationsDate.class, id);
} else {
od = new OperationsDate(id);
}
if(inf) {
for(int number : list) {
Medicine m = em.find(Medicine.class, number);
od.setDoctor(d);
d.addOperationsDate(od);
od.addMedicine(m);
m.addOperationsDate(od);
}
} else {
Operation o = em.find(Operation.class, list.get(0));
od.setDoctor(d);
d.addOperationsDate(od);
od.addOperation(o);
o.addOperationsDate(od);
}
}
public int countId(int doctorId) {
long millis=System.currentTimeMillis();
java.sql.Date date=new java.sql.Date(millis);
String id = "";
String date2 = date.toString();
for(int i=0; i < date2.length();i++) {
if(i == 4 || i == 7) {
continue;
}
id += date2.charAt(i);
}
id += doctorId;
int id2 = Integer.parseInt(id);
return id2;
}
Just try it this way then, as I told you in my comment:
OperationsDate od = em.find(OperationsDate.class, id);
if( od == null) {
od = new OperationsDate(id);
}
...
// potential persist or merge, depending on your frameworks configuration regarding autocommit and such
em.persist(od);
If it still doesn't work, add the code for your entities, to make sure nothing's wrong about it.

how to input new string if there have value except zero

i need help. can somebody tell me about concept and example code i need use? the case is, I want input game history using java into mysql (phpmyadmin).
I'm already create like this if S0: 1.0; and all value zero
try
{
connection = dbManager.getConnection();
String bs = "S0:"+s[0]+"; S1:"+s[1]+"; S2:"+s[2]+"; S3:"+s[3]+"; S4:"+s[4]+"; S5:"+s[5]+"; S6:"+s[6]+"; S7:"+s[7]+"; S8:"+s[8]+"; S9:"+s[9]+"; S10:"+s[10]+"; S11:"+s[11]+"; S12:"+s[12]+"; S13:"+s[13]+"; S14:"+s[14]+"; S15:"+s[15]+"; S16:"+s[16]+"; S17:"+s[17]+"; S18:"+s[18]+"; S19:"+s[19]+"; S20:"+s[20]+"; S21:"+s[21]+"; S22:"+s[22]+"; S23:"+s[23]+"; S24:"+s[24]+"; S25:"+s[25]+"; S26:"+s[26]+"; S27:"+s[27]+"; S28:"+s[28]+"; S29:"+s[29]+"; S30:"+s[30]+"; S31:"+s[31]+"; S32:"+s[32]+"; S33:"+s[33]+"; S34:"+s[34]+"; S35:"+s[35]+"; S36:"+s[36]+"";
}
catch (SQLException e)
{
trace("player 1 update error");
}
and it's working and result like this
S0:1.0; S1:0.0; S2:0.0; S3:0.0; S4:0.0; S5:0.0; S6:0.0; S7:0.0; S8:0.0; S9:0.0; S10:0.0; S11:0.0; S12:0.0; S13:0.0; S14:0.0; S15:0.0; S16:0.0; S17:0.0; S18:0.0; S19:0.0; S20:0.0; S21:0.0; S22:0.0; S23:0.0; S24:0.0; S25:0.0; S26:0.0; S27:0.0; S28:0.0; S29:0.0; S30:0.0; S31:0.0; S32:0.0; S33:0.0; S34:0.0; S35:0.0; S36:0.0
but it's not efficient, the question is how i can input if there have any value except zero, example like S0:1 ; S1:0 ; S2:1 and insert into mysql just like this S0:1 ; S2:1 so if there no have value / zero, not being inserted. Thanks
You could try this:
String bs = "";
int count = 0;
for (int i = 0; i < size; i++) {
if(!s[i].equals(0.0)) {
if(count > 0) {
bs += " ; " ;
}
bs += "S" + count + ":" + s[i].split(".")[0];
count++;
}
}
try this code
private static String format (int x) {
if (x == 0) {
return null;
}
return String.format ("S%d = %d; ", x ,x);
}
// testing from main
{
StringBuilder buf = new StringBuilder();
for (int x = 0; x < 4; x++) { // dummy input stream
String rv = format (x);
if (rv != null) {
buf.append(rv);
}
}
System.out.println(buf.toString());
}

XYPlot doesn't draw all points correctly

I'm trying to display 550 data points with periodic peaks (the flat line is 61). The problem is, that androidplot isn't drawing all the points correctly! From my log:
ECG I values 61,61,62,63,62,61,61,61,61,67,71,68,61,53,61,61,61,61,61,61,61,61,62,63,64,64,64,63,62,61,61,61
I've got the rangeboundaries set to plot.setRangeBoundaries(0,100, BoundaryMode.AUTO);, but as you can see, the peaks never drop to the 53 data point. I can see this lower point sometimes, but it gets smoothed out a fraction of a second later (as you can see in the screenshot).
My line and point formatter is:
LineAndPointFormatter lapf = new LineAndPointFormatter(p.color, null, null, null);
lapf.getLinePaint().setStrokeJoin(Paint.Join.MITER);
lapf.getLinePaint().setStrokeWidth(1);
I've tried with the both Paint.Join.ROUND and Paint.Join.BEVEL and got the same effect. I've also used the debugger to check that 53 is being inserted into the series.
EDIT
After some debugging, it looks like my pulse loop thread is wrong:
while (keepRunning) {
for (PulseXYSeries j : series) {
for (int k = 0; k < j.plotStep; k++) {
int at = (j.position + k) % j.getSize();
if (j.pulsing) {
if (j.pulsePosition == j.pulseValues.size() - 1) {
j.pulsing = false;
j.pulsePosition = 0;
} else {
try {
int pulseVal = j.pulseValues.get(j.pulsePosition);
j.setY(pulseVal,at);
j.pulsePosition += 1;
} catch(IndexOutOfBoundsException e) {
j.pulsePosition = 0;
}
}
} else {
j.setY(j.pulseValues.get(0), at);
long currTime = SystemClock.elapsedRealtime();
if (currTime - j.getLastPulse() >= j.getPulseDelay()) {
j.pulsing = true;
j.setLastPulse(currTime);
}
}
j.remove(((at + j.eraserSize) % j.getSize()));
}
j.position = (j.position + 1) % j.getSize(); // fixed it by changing +1 to + j.plotStep
}
Thread.sleep(delay);
}
My custom series looks like:
private class PulseXYSeries implements XYSeries {
private List<Integer> pulseValues = new ArrayList<Integer>();
private int pulsePerMinute;
public int pulsePosition;
public int position;
private ArrayList<Integer> values;
private String title;
private long lastPulse;
public boolean pulsing = false;
public int eraserSize = 20;
public int plotStep = 3;
}

counting unique combinations of object properties

I have a class TypesHolder that has four properties which are each int values. I want to identify how many unique combinations of values are in the four int variables, and then to give a count of how many instances of TypesHolder have each specific combination of the four integer variables. How can I accomplish this in code? My code attempt below is failing, with the failed results summarized at the end. There must be a simpler way to do this correctly.
Here is my TypesHolder class:
public class TypesHolder {
private int with;
private int type;
private int reason1;
private int reason2;
//getters and setters
}
To hold the unique combinations during analysis, I created the following TypesSummaryHolder class:
public class TypesSummaryHolder {
private int with;
private int type;
private int reason1;
private int reason2;
private int count;
//getters and setters
}
I then created an ArrayList to store the 15000+ instances of TypesHolder and another ArrayList to store the TypesSummaryHolder objects who represent each of the unique combinations of width, type, reason1, and reason2 from the TypesHolder objects, along with a count variable for each of the unique combinations. I wrote the following code to populate the ArrayList of TypesSummaryHolder objects along with their counts:
#SuppressWarnings("null")
static void countCommunicationTypes(){
int CommunicationWithNumber;int CommunicationTypeNumber;int CommunicationReasonNumber;
int SecondReasonNumber;int counter = 0;
ArrayList<EncounterTypesHolder> types = new ArrayList<EncounterTypesHolder>();
ArrayList<EncounterTypesSummaryHolder> summaries = new ArrayList<EncounterTypesSummaryHolder>();
////////
try {Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");}
catch (ClassNotFoundException e1) {e1.printStackTrace();}
Connection sourceConn = null;
try {sourceConn = DriverManager.getConnection("jdbc:odbc:PIC_NEW_32");}
catch (Exception e1) {e1.printStackTrace();}
Statement st = null;
try {st = sourceConn.createStatement();}
catch (Exception e1) { e1.printStackTrace();}
ResultSet rest = null;
try {
rest = st.executeQuery("SELECT * FROM someTable");
while (rest.next()) {
CommunicationWithNumber = rest.getInt(3);
CommunicationTypeNumber = rest.getInt(5);
CommunicationReasonNumber = rest.getInt(6);
SecondReasonNumber = rest.getInt(6);
EncounterTypesHolder etype = new EncounterTypesHolder();
etype.setWith(CommunicationWithNumber);
etype.setType(CommunicationTypeNumber);
etype.setReason1(CommunicationReasonNumber);
etype.setReason2(SecondReasonNumber);
if(!isDuplicateType(etype,types)){
EncounterTypesSummaryHolder summaryholder = new EncounterTypesSummaryHolder();
summaryholder.setWith(CommunicationWithNumber);
summaryholder.setType(CommunicationTypeNumber);
summaryholder.setReason1(CommunicationReasonNumber);
summaryholder.setReason2(SecondReasonNumber);
summaryholder.setCount(1);
summaries.add(summaryholder);
} else {
EncounterTypesSummaryHolder summaryholder = new EncounterTypesSummaryHolder();
summaryholder.setWith(etype.getWith());
summaryholder.setType(etype.getType());
summaryholder.setReason1(etype.getReason1());
summaryholder.setReason2(etype.getReason2());
if(isDuplicateSummaryType(summaryholder, summaries)){
for(int u = 0; u<summaries.size();u++){
if((CommunicationWithNumber==summaries.get(u).getWith()) && (CommunicationTypeNumber==summaries.get(u).getType()) && (CommunicationReasonNumber==summaries.get(u).getReason1()) && (SecondReasonNumber==summaries.get(u).getReason2()) ){
int oldcount = summaries.get(u).getCount();
int newcount = oldcount+1;
summaries.get(u).setCount(newcount);
}
}
}else {
summaryholder.setCount(1);
summaries.add(summaryholder);
}
}
types.add(etype);
counter += 1;
System.out.println("counter is: "+counter);
System.out.println("summaries.size() is: "+summaries.size());
}
} catch (Exception e) {e.printStackTrace();}
System.out.println("at end: counter is: "+counter);
System.out.println("at end: types.size() is: "+types.size());
System.out.println("at end: summaries.size() is: "+summaries.size());
int total = 0;
for(int r=0;r<summaries.size();r++){
total += summaries.get(r).getCount();
int with = summaries.get(r).getWith();int type = summaries.get(r).getType();int reason1 = summaries.get(r).getReason1();int reason2 = summaries.get(r).getReason2();int thiscount = summaries.get(r).getCount();
}
System.out.println("total is: "+total);
}
static boolean isDuplicateType(EncounterTypesHolder testType, ArrayList<EncounterTypesHolder> types){
for(int j = 0; j<types.size(); j++){
if( (testType.getWith() == types.get(j).getWith()) && (testType.getType() == types.get(j).getType()) && (testType.getReason1() == types.get(j).getReason1()) && (testType.getReason2() == types.get(j).getReason2())){
System.out.println("=====TRUE!!====");
return true;
}
}
return false;
}
static boolean isDuplicateSummaryType(EncounterTypesSummaryHolder testType, ArrayList<EncounterTypesSummaryHolder> types){
for(int j = 0; j<types.size(); j++){
if( (testType.getWith() == types.get(j).getWith()) && (testType.getType() == types.get(j).getType()) && (testType.getReason1() == types.get(j).getReason1()) && (testType.getReason2() == types.get(j).getReason2())){
System.out.println("=====TRUE!!====");
return true;
}
}
return false;
}
The code above is producing the following SYSO output at the end:
at end: counter is: 15415
at end: types.size() is: 15415
at end: summaries.size() is: 15084
total is: 2343089
The max possible value for summaries.size() should be around 600, but the 331 you get from types.size() minus summaries.size() above is within the range of believable values for summaries.size(). However, the value for total should be equal to the 15414 value of types.size(). What is wrong with my code above? How can I change my code above to get both a list of the unique combinations of with, type, reason1, and reason2, and also a count of the number of instances with each of those unique value combinations?
If I understand you right, you could add hashcode() and equals() methods to to TypesHolder, then add all your values to a Set<TypesHolder> of some sort. Then just count the total objects (call size()) in the set to get the number of unique combinations.
Here's a link to implementing hashcode() and equals() from SO, if you're not familiar with those methods. Google is your friend.

Categories

Resources