I have written a code and I can't explain why is it not behaving the way it should. I know this sounds silly but it is not.
boolean verify = EDV.verifySignature(signature, cipherText,
SERVER_PUBLIC_KEY);
out.println("Validity " + verify);
if (verify) {
// //message is authentic
String decryptedMessage = EDV.decrypt(cipherText,
SERVER_PRIVATE_KEY);
out.println("Message : " + decryptedMessage);
}else
{
out.println("Signature did not match");
}
This is a simple code that verifies signature and then decrypts the message if the signature is valid(verify is true)
The output of this code is this :
Validity false
Signature did not match
The message decrypts just fine.
The problem is that the signature should verify (I have checked the signature, cipherText, and key over n times). Here's the kick.
The almost same code
boolean verify = EDV.verifySignature(signature, cipherText,
SERVER_PUBLIC_KEY);
out.println("Validity " + verify);
// if (verify) {
// //message is authentic
String decryptedMessage = EDV.decrypt(cipherText,
SERVER_PRIVATE_KEY);
out.println("Message : " + decryptedMessage);
// }else
// {
// out.println("Signature did not match");
// }
and Voila!, output is as I wanted it to be and as it should be.
Validity true
Message : This is a sample Text
And, the first code works just fine on Eclipse, but running it on JAVA servlet is the only time I get this.
Also, the first time I run the code#2 it gives false but after that it gives true.
I can't seem to explain the reason.
LINKS
Code#1
Code#2(Run this code, it gives false validity refresh it and it turns true)
Something's not initialising properly in the code just before the sample you gave. Try adding some test println statements for the signature, cipherText and SERVER_PUBLIC_KEY parameters.
Also, check the initialisation of EDV.verifySignature.
Related
I am having a problem when trying to use the Z3Str3 from z3-4.8.9-x64-ubuntu-16.04 notably if I substitute the com.microsoft.z3.jar to the one in z3-4.8.8-x64-ubuntu-16.04 I no longer have that issue. The problem is that the Z3 process never comes back with a result, despite the simplicity of the query. I noticed though that it returns the valid answer when I kill my program. I am not noticing that behavior when I am trying to run the same query on the executable, so I am guessing there is something about using the jar file that I might need to tweak one way or the other.
Here is my code. I am using Ubuntu 16.04 LTS, and IntelliJ version ultimate 2020.3.
Many thanks!
import com.microsoft.z3.*;
public class Z3String3Processor_reduced {
public static void main(String[] args) {
StringBuilder currentQuery = new StringBuilder("\n" +
"(declare-const string0 String)\n" +
"(assert (= (str.indexof string0 \"a\" 1) 6))\n" +
"(check-sat)\n" +
"(get-model)\n" +
"\n");
Context context1 = new Context();
Solver solver1 = context1.mkSolver();
Params params = context1.mkParams();
params.add("smt.string_solver", "z3str3");
solver1.setParameters(params);
StringBuilder finalQuery = new StringBuilder(currentQuery.toString());
// attempt to parse the query, if successful continue with checking satisfiability
try {
// throws z3 exception if malformed or unknown constant/operation
BoolExpr[] assertions = context1.parseSMTLIB2String(finalQuery.toString(), null, null, null, null);
solver1.add(assertions);
// check sat, if so we can go ahead and get the model....
if (solver1.check() == Status.SATISFIABLE) {
System.out.println("sat");
} else
System.out.println("not sat");
context1.close();
} catch (Z3Exception e) {
System.out.println("Z3 exception: " + e.getMessage());
}
}
}
I don't think this has anything to do with Java. Let's extract your query and put it in a file named a.smt2:
$ cat a.smt2
(declare-const string0 String)
(assert (= (str.indexof string0 "a" 1) 6))
(check-sat)
(get-model)
Now, if I run:
$ z3 a.smt2
sat
(
(define-fun string0 () String
"FBCADEaGaa")
)
That's good. But if I run:
$ z3 smt.string_solver=z3str3 a.smt2
... does not terminate ..
So, bottom line, your query (as simple as it looks), gives hard time to the z3str3 solver.
I see that you already reported this as a bug at https://github.com/Z3Prover/z3/issues/5673
Given that the default string-solver can handle the query just fine, why not just use that one? If you have to use z3str3 for some other reason, then you've found a case where it doesn't handle this query well; I'm not sure how inclined the z3 folks will be to fix this given the query is handled by the default solver rather quickly. Please report what you find out!
I have an unexpected issue with the sendKeys() method:
A long time before it all worked fine, but unexpectedly the (certain(!)) values are replaced when the code tries to set data into the input field:
For example, if I set value USER_NAME into the field, value replaced with /tmp/7d7b7...../upload123...file/USER_NAME. As we can see - some path was added into the USER_NAME value.
I added logs to the method and we can see a moment when the value was replaced:
clearInputFld(inputFld);
Log.info("INSIDE clearAndTypeIntoInputField() ---------> value after clearing: " + inputElement.getAttribute("value"));
Log.info("INSIDE clearAndTypeIntoInputField() ---------> value to set: " + value);
inputElement.sendKeys(value);
Log.info("INSIDE clearAndTypeIntoInputField() ---------> value after set: " + inputElement.getAttribute("value"));
Output:
INSIDE clearAndTypeIntoInputField() ---------> value after clearing:
INSIDE clearAndTypeIntoInputField() ---------> value to set: USER_NAME
INSIDE clearAndTypeIntoInputField() ---------> value after set: /tmp/7d7b7...../upload123...file/USER_NAME
So we can be sure - value sets exactly at the moment when value sets into the field.
Important to know, and conclusions:
Not all users replaced - Only several certain users! So I suppose a part of users is cached. But I do not understand the process with which this happens, why this happens, and where these users might be cached.
I also restarted the docker, so it seems the problem is not in the automatic side.
Is it possible that this issue occurs via the backend or UI part?
It looks like there is a script running on the page that changes the input you type, as this is a password field.
What I suggest is that you use the Robot object to mimic keyboard strokes.
First click on the text field using Selenium, then launch the Robot code (use package Java.awt):
Robot robot = null;
try {
robot = new Robot();
for (char c : textToType.toCharArray()) {
int keyCode = KeyEvent.getExtendedKeyCodeForChar(c);
if (KeyEvent.CHAR_UNDEFINED == keyCode) {
logger.error("Key code not found for character '" + c + "'");
} else {
try {
robot.keyPress(keyCode);
robot.delay(10);
robot.keyRelease(keyCode);
robot.delay(10);
} catch (Exception e) {
if (c == '_') {
robot.keyPress(KeyEvent.VK_SHIFT);
robot.keyPress(KeyEvent.VK_MINUS);
robot.keyRelease(KeyEvent.VK_MINUS);
robot.keyRelease(KeyEvent.VK_SHIFT);
}
if (c == ':') {
robot.keyPress(KeyEvent.VK_SHIFT);
robot.keyPress(KeyEvent.VK_SEMICOLON);
robot.keyRelease(KeyEvent.VK_SEMICOLON);
robot.keyRelease(KeyEvent.VK_SHIFT);
}
}
}
}
robot.keyPress(KeyEvent.VK_ENTER);
} catch (Exception ex) {
logger.error(ex.getMessage());
}
According to Logs, I think there is something come with the value.
Suggest trying :
Get the changed text, do some operation, fill it back
string[] temp;
temp = (inputElement.Text).Split('/');
inputElement.Sendkeys(temp(temp.Length - 1));
I am a beginner in Selenium. I wanted to know how I can verify the URL against the keyword I entered in the search bar.
The search page url is https://catalog-mytest.com/search?
When I entered redcar in the search bar and hit enter, the url becomes https://catalog-mytest.com/search?keywords=redcar
Could you guide me on how to write a piece of code that would verify the URL with the keywords? thank you.
There can be two approaches-
Approach-1:
String url = Driver.getCurrentUrl();
boolean passed = url.contains("your keyword here");
if (passed) {
System.out.println("Test Passed");
} else {
System.out.println("Test Failed");
Assert.fail("This message will be printed in stacktrace if the assertion fails.");
}
This is the simplest way of doing this.
Approach-2:
String keyword = Driver.getCurrentUrl().split("?")[1].split("=")[1];
boolean passed = keyword.equals("your keyword here");
if (passed) {
System.out.println("Test Passed");
} else {
System.out.println("Test Failed");
Assert.fail("This message will be printed in stacktrace if the assertion fails.");
}
This approach can be error prone, if the URL does not always contain
?, = in it then the test can fail with
ArrayIndexOutOfBoundsException
I have written a code to connect to this webpage: compilerjava.net
1) I found the text-area field within that page which accepts the code to compile.
2) I have found the button that compiles the code.
3) I have found the text-area which returns the result of the code.
The issue is, when I call textarea.setText( "something"), it (I think) doesn't actually change the code in the webpage. So when I click on the compile button, it compiles the default code within that page and returns the output of that default code.
I have tried to set focus to textarea, you can see all of those down below.
I called;
1) textArea.focus();
2) textArea.click();
3) I tried using textArea.setAttribute( "name", "code");
I have searched the internet and found various stackoverflow questions close to this problem, neither of them solved my issue and it just seems to work for everyone when they say textArea.setText().
Another interesting fact I should share with you is,
If I call textArea.setText( "...") and then I say;
HtmlTextArea textArea1 = form.getTextAreaByName( "code");
If I call textArea1.getText(), the value of this text will be "...". This should imply that I have actually managed to change the value of the text-area, but when I compile, it compiles the default text in the text-area and not the text that I have set it to.
Any help with this?
P.S: The reason why I put the result of the compilation on a while loop is related to network connection issues. If you try to run this code it might not work on your first try. Also note that the run-time is around 15 seconds, because it gives thousands of warnings which I blocked to print to console.
P.S2: I also looked at this page and none of these worked;
http://www.programcreek.com/java-api-examples/index.php?api=com.gargoylesoftware.htmlunit.html.HtmlTextArea
public class Test {
public static void main(String[] args) {
try {
// Prevents the program to print thousands of warning codes.
java.util.logging.Logger.getLogger("com.gargoylesoftware").setLevel(java.util.logging.Level.OFF);
java.util.logging.Logger.getLogger("org.apache.http").setLevel(java.util.logging.Level.OFF);
// Initializes the web client and yet again stops some warning codes.
WebClient webClient = new WebClient( BrowserVersion.CHROME);
webClient.getOptions().setThrowExceptionOnFailingStatusCode( false);
webClient.getOptions().setThrowExceptionOnScriptError( false);
webClient.getOptions().setJavaScriptEnabled( true);
webClient.getOptions().setCssEnabled( true);
// Gets the html page, which is the online compiler I'm using.
HtmlPage page = webClient.getPage("https://www.compilejava.net/");
// Succesfully finds the form which has the required buttons etc.
List<HtmlForm> forms = page.getForms();
HtmlForm form = forms.get( 0);
// Finds the textarea which will hold the code.
HtmlTextArea textArea = form.getTextAreaByName( "code");
// Finds the textarea which will hold the result of the compilation.
HtmlTextArea resultArea = page.getHtmlElementById( "execsout");
// Finds the compile button.
HtmlButtonInput button = form.getInputByName( "compile");
textArea.click();
textArea.focus();
// Simple code to run.
textArea.setDefaultValue( "public class HelloWorld\n" +
"{\n" +
" // arguments are passed using the text field below this editor\n" +
" public static void main(String[] args)\n" +
" {\n" +
" System.out.print( \"Hello\");\n" +
" }\n" +
"}");
System.out.println( textArea.getText());
// Compiles.
button.click();
// Result of the compilation.
String str = resultArea.getText();
while ( resultArea.getText() == null || resultArea.getText().substring(0, 3).equals( "exe")) {
System.out.print( resultArea.getText());
}
System.out.println();
System.out.println( resultArea.getText());
} catch ( Exception e) {
e.printStackTrace();
}
}
}
a little patience helps here
// Result of the compilation.
while (resultArea.getText() == null || resultArea.getText().startsWith("exe")) {
System.out.println(resultArea.getText());
Thread.sleep(500);
}
System.out.println();
System.out.println(resultArea.getText());
So I'm making a simple code redemption plugin for a Minecraft server. What's weird is when I type /redeem (the valid code), nothing happens, although it's supposed to... The valid code is the a code entered into the plugins configuration by the user.
Here's my code...
public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args)
{
//Assigns the commands chosen in config to strings
String commandChosen1 = this.getConfig().getString("Command for code 1");
String commandChosen2 = this.getConfig().getString("Command for code 2");
String commandChosen3 = this.getConfig().getString("Command for code 3");
//Assigns the codes to strings
String validCode1 = this.getConfig().getString("Valid Code 1");
String validCode2 = this.getConfig().getString("Valid Code 2");
String validCode3 = this.getConfig().getString("Valid Code 3");
//If the redeem command is sent from a player
if(cmd.getName().equalsIgnoreCase("redeem") && sender instanceof Player)
{
//Casts the sender to a new player.
Player player = (Player) sender;
//Creates object hasUSed to store whether or not the player has already redeemed a code
Object hasUsed = this.getConfig().get(player.getName());
//Gives an error message of the arguments don't equal 1.
if(args.length != 1)
{
player.sendMessage(ChatColor.DARK_RED + "Please enter a valid promo code. Find them on our twitter!");
}
if(args.length == 1)
{
//If the player hasn't used the code yet and the arguments given are equal to a code then give them the reward...
if(args[0] == validCode1 && hasUsed == null)
{
this.getConfig().set(player.getName(), 1);
player.sendMessage(ChatColor.GREEN + "Promo code successfully entered!");
if(commandChosen1 == "xp")
{
Bukkit.dispatchCommand(player, commandChosen1 + getConfig().getString("XP Given") + "L" + " " + player.getName());
}
}
}
return true;
}
return false;
}
The problem occurs on "if (args[0] == validCode1 && hasUsed == null)". The code that's supposed to happen if both those things check out, doesn't happen and I have no clue why.
Make sure to use equals() when comparing Strings. Using commandChosen1 == "xp" compares string references not values; use commandChosen1.equals("xp") or if you prefer "xp".equals(commandChosen1).
Also,
While it is possible to use a this.getConfig().getString()with a key value that contains spaces, it can make configuration files hard to read and cluttered. Whenever I design plugins I'll design my config.yml as such
VoteGUI:
message: 'hello'
and then run a this.getConfig().getString("VoteGUI.message");
For yours I'd suggest something like this
Promo-Codes:
validCode1: 'insert code here'
validCode2: 'insert code here'
validCode3: 'insert code here'
and then put this in your onCommand method:
String validCode1 = this.getConfig().getString("Promo-Codes.validCode1");
String validCode2 = this.getConfig().getString("Promo-Codes.validCode2");
String validCode3 = this.getConfig().getString("Promo-Codes.validCode3");
If this does not resolve the issue, copy and paste the exception being thrown from the console and I may be of further assistance