AES encryption (in Java) of different JSON strings always produce same encrypted string as result. Why?

I have a program written in Java which takes JSON string as argument, encrypts it using AES then encodes it using Base64.
JSON string is like:

{"a": "b"} or {"a": "n"} or {"a": "k"} 

I.e related object would have one property a. Value part is randomly generated.

Program outputs for above JSON inputs looks like

UBNvKoRoGqk0PTQQL5K4Sw==
bKwlToSND3HkceDExEDXSw==
u/yKJq1FdoifBM+AnadC3A==

i.e. they are unique.

Same goes for {"a":"gn"} — random string with length 2. Same for 3 and so on.

But starting from 7 program produces the same encoded string for different inputs. I mean following JSON strings taken as input:

{"a": "pzfovvs"}
{"a": "bqwuvck"}

produces same string as output:

Dwg0Xjkot8UBfn+vbcCfOS4KluXB6RCFQ932Y9ABtIg=

Same goes for length 8 and 9. Starting from 10 results became unique again.

What is the explanation of this strange phenomenon?

(I can post code if needed.)

Ok, here is the code:

import java.security.Key;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;

public class JWTEncryptor {

private static String algorithm = "AES";
private static Key key;
private static KeyGenerator keyGenerator;
private static Cipher cipher;

public static String encrypt(String jwt) throws Exception {
    if (key == null || cipher == null) {
        setUp();
    }
    cipher.init(Cipher.ENCRYPT_MODE, key);
    return Base64.getEncoder().encodeToString(cipher.doFinal(jwt.getBytes("UTF-8")));
}

private static void setUp() {
    try {
        cipher = Cipher.getInstance(algorithm);
    } catch (Exception e1) {
        e1.printStackTrace();
    }
    if (keyGenerator != null) {
        key = keyGenerator.generateKey();
        return;
    }
    try {
        keyGenerator = KeyGenerator.getInstance(algorithm);
        key = keyGenerator.generateKey();
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    }
}

public static String decrypt(String encryptedJWT) throws Exception {
    cipher.init(Cipher.DECRYPT_MODE, key);
    return new 
   String(cipher.doFinal(Base64.getDecoder().decode(encryptedJWT)));
} 

}

appsec – What are the types of vulnerabilities that could result in exploits that do not require user interaction?

What are the existing types of vulnerabilities that could result in exploits that do not require user interaction (e.g. zero-click)? I’m trying to understand the type of zero-click attack type for us to plan proper mitigation in code.

wpdb – Check if Value Exists in Database, adding row details to variables and echoing result

I am trying to create a UK Postcode checker for a clients Woocommerce shop. I have created a table in WordPress with the cells, Postcode, Town and County.

When a user enters their postcode into a form and clicks submit, I want to check if the postcode exists in our database, and let the user know.

My code is not recognising whether the postcode exists in the database or outputting the town later.

Any help would be most gratefully appreciated.

<?php
global $wpdb;
$table_name = $wpdb->prefix.'vw_postcode_checker';

if (!empty($_POST(postcode)))
{
    $postcode = $_POST(postcode);
    $entry = $wpdb->get_results("SELECT * FROM ".$tablename."WHERE postcode =" . $postcode);
    if(count($entry) == 1){
         $id = $entry->id;   //We need this for the delete to work.
         $postcode = $entry->postcode;
         $town = $entry->town;
         $county = $entry->county;
         $confirmed = "Contratulations, we are delivering to" . $town;
         echo $confirmed;
       }
    else {
    $notconfirmed = "Sorry, we are not delivering to your area at this time.";
    echo $notconfirmed;
    }
}
?>

export – Notebook WindowSize is limiting ImageResize and affects result of CreateDocument

In the following example CreateDocument or Export seem to be overriding the size of the graphic being written to a PDF file.

First use a screen grab to create an image and paste into a notebook:

image =<your image>;

then get the dimensions:

{pageX, pageY} = ImageDimensions(image)

Create a symbol to play with the effect of increasing the size:

sizeIncrease = 1200;
imageLarger = ImageResize( image, pageX + sizeIncrease)

If you increase the value of sizeIncrease there comes a point where MMA ignores the over-sizing in order to ensure the resulting graphic fits within the WindowSize (a bigger window size allows a larger graphic.) Now try this with a few values of sizeIncrease:

nb = CreateDocument(imageLarger);
Export("test.pdf", nb);

Again it seems the width of the image in nb is constrained by the window size, however, the size of the image in the Exported file is also being constrained. In my actual case, this means the image in the PDF is too small. At first I thought it was the exported PDF file PrintingMarginsso I tried this:

nb = CreateDocument(res, PageBreakBelow -> True, Visible -> True, 
   WindowSize -> {1200, 900});
Export("test.pdf", nb,
  PrintingOptions -> {"PrintingMargins" -> {{50, 50}, {50, 50}}, 
    "PaperOrientation" -> "Portrait"});

This, however, does not help – something else is constraining the size of the image. Any ideas on how I can get the image sized to fill the printable page?

The overall goal here is to create a function that allows me (now us) to import a PDF file created by a scanner, then binarize, crop, and resize it, before exporting it back to a now much smaller cleaned up PDF. MMA does a fantastic job of reducing dirty looking 200MB PDFs down to a few megabytes. The only problem is the size of the image in the PDF. Here is my first stab at the function. The Do Loop is to avoid reading in the whole PDF file (if I do that with a 200MB PDF the Graphics ByteCount is around 7Gb!)

compressPDF(file_String, folder_String, width_, crop_List) := Module(
  {pageCount, compressedPages, pagei, binarizedImage, pageX, pageY, 
   cropX, cropY, pageCropped, pageLarger},
  pageCount = Import(folder <> fileName, { "PageCount"});
  Print(pageCount);
  compressedPages = {};
  Do(
   pagei = Import(folder <> fileName, { "Pages", i})((1));
   binarizedImage = Binarize(pagei);
   {pageX, pageY} = ImageDimensions(binarizedImage);
   {cropX, cropY} = crop;
   pageCropped = 
    ImageCrop(
     binarizedImage, {{cropX, pageX - cropX}, {cropY, pageY - cropY}});
   pageLarger = ImageResize( pageCropped, {pageX + width});
   AppendTo(compressedPages, pageLarger);
   , {i, 1, pageCount}
   );
  Return(compressedPages)
  )

numerics – Numerical evaluation expression not returning result in requested precision

I have a long list of descriptive statistical quantities for a univariate list of data. The problem is that the set number of significant figures is ignored by the N(...,sigs) for most expressions. In the code they are easily identified with a comment (* sigs not working *).

Why are they not returned in requested precision of 3 significant figures? How can I fix this?

sigs = 3;
{"n", n = Length(raw)}
{"range", range = N(Max(raw) - Min(raw), sigs)}
{"midrange", 
 midrange = N(Min(raw) + range/2, sigs)}(* sigs not working *)
{"(Mu) ", (Mu) = N(Mean(raw), sigs)}(* sigs not working *)
{"median", median = N(Median(raw), sigs)}
{"mode", mode = N(Commonest(raw)((1)), sigs)}
{"rms", rms = N(RootMeanSquare(raw), sigs)}(* sigs not working *)
{"(Sigma)2", (Sigma)2 = 
  N(Variance(raw), sigs)}(* sigs not working *)
{"(Sigma)", (Sigma) = 
  N(Sqrt((Sigma)2), sigs)}(* sigs not working *)
{"(Sigma)mean", (Sigma)mean = 
  N(MeanDeviation(raw), sigs)}(* sigs not working *)
{"Cvar", Cvar = N((Sigma)/(Mu), sigs)}(* sigs not working *)
{"Es", Es = 
  N((6745/10000) StandardDeviation(raw), 
   sigsup)}(* sigs not working *)
{"Em", Em = N(Es/Sqrt(n), sigsup)}(* sigs not working *)
{"skew", skew = N(Skewness(raw), sigsdn)}(* sigs not working *)
{"kurt", kurt = N(Kurtosis(raw), sigsdn)}(* sigs not working *)

front end – Frontend/Backend Integration: Wait for a Google Cloud function to run and then return result

I am trying to create a tool that receives a user input on the front end, uses that input to run a Google Cloud function and then returns a link to the output, hosted on Google cloud as well.

How can you give updates that a process is being performed, and update the page when it is finished?

php – Thickbox to display the result of a custom db query in admin

Is it possible to add php generated output in a WordPress thickbox?

I have the thickbox working fine from a button in a custom meta box, it displays html without issue. However, what I actually want to display is the output from a query on a custom table. The db query works fine, the html works fine, but the echoed php output is not displayed.

dataset – In Wolfram Mathematica, who do I query the result of a Counts operation efficiently and conveniently?

Setup

Say, I’m given a dataset, like the one below:

titanic = ExampleData({"Dataset", "Titanic"}); titanic

Answering with:

Sample of the Titanic example data

And I want to count the occurrences of any combination between { "1st", "2nd"} and {"female", "male"}, using the Counts operator on the dataset, like:

genderclasscounts = titanic(All, {"class", "sex"})(Counts)

Gender Class combination counts

Problem statement

This is not a “flat” dataset and I don’t have a clue how to query in the usual way, like:

genderclasscount(Select( ... ), ...)

The resulting dataset doesn’t provide “column” names to be used as parameters in the Select nor can I refer to the number representing the count by a name.

And I’ve no clue how to express an Association as a value in a Select!?

Furthermore, try genderclasscount(Print), this demonstrates the values presented to the operation over this dataset are just numbers!

An unsatisfactory attempt

Of course, I can “flatten” the Counts result, by doing something horrific and inefficient like:

temp = Dataset((row (Function) 
     AssociationThread({"class", "sex", "count"} -> row)) /@ (Nest(
      Normal, genderclasscounts, 3) /. 
     Rule({Rule("class", class_), Rule("sex", sex_)}, 
       count_) -> {class, sex, count}))

Flattened Counts over a dataset result

In this form it is easy to query a count result:

First@temp(Select(#class == "1st" (And) #sex == "female" &), "count")

Question

So, my questions are

  1. How can I query the (immediate) result of the Count operation in a convenient and efficient fashion, like using a Select operation on the resulting dataset? Or, if that is not possible;

  2. Is there an efficient and convenient transformation of the Counts result dataset possible facilitating such a query? With “convenient” I mean, for example, that you just provide the dataset and the transformation handles the rest. So, not something like I’ve shown above in my unsatisfactory “solution” 😉

Thanks for reading this far and I’m looking forward to anwsers and inspiration.

/@nanitous

Is there a search engine with reverse search mechanism: processing multiple queries and retrieving a single result for each of them?

A regular search engine retrieves a number of results matching a single query. I need one that does the opposite: enables to input a number of queries and displays a single match to each of them. If there is no match, I need to know it too. An implementation of this approach exists, but its application is limited to the database embedding it (PubMed). Batch Citation Matcher enables a user to identify unique content in databases covering material also present in PubMed. A user can submit a text file and the engine transforms the content of the file separated in a required way into a number of queries, then displays a table with queries in one column and the information on whether the text of the queries was found in a database being compared to PubMed in another column. Is there an analogues application which can be applied to any website?