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.)

postgresql – How to aggregate json fields when using GROUP BY clause in postgres?

I have the following table structure in my Postgres DB (v12.0)

id | pieces | item_id | material_detail
---|--------|---------|-----------------
1  | 10     | 2       | ({"material_id":1,"pieces":10},{"material_id":2,"pieces":20},{"material_id":3,"pieces":30})

2  | 20     | 2       | ({"material_id":1,"pieces":40}
3  | 30     | 3       | ({"material_id":1,"pieces":20},{"material_id":3,"pieces":30}

I am using GROUP BY query for this records, like below

SELECT SUM(PIECES) FROM detail_table GROUP BY item_id HAVING item_id =2 

Using which I will get the total pieces as 30. But how could I get the count of total pieces from material_detail group by material_id.

I want result something like this

 pieces |  material_detail
 -------| ------------------
  30    |  ({"material_id":1,"pieces":50},{"material_id":2,"pieces":20},{"material_id":3,"pieces":30})

As I am from MySQL background, I don’t know how to achieve this with JSON fields in Postgres.

Note: material_detail column is of JSONB type.

c# – How to properly format classes for JSON deserialization with JSON.net for Unity?

I am creating an inventory system and decided to keep a master list of all the items. The goal is to use JSON.net to parse the item list and populate the database of items. The JSON item list looks like:

{
    "Items":{
        "Ingredients":{

        },
        "Consumables": {
            "0" : {
                "ID" : "TP_Small",
                "Icon" : "Sprites/porridge.png",
                "Name" : "Small Tan Pill's Porridge",
                "Consumable" : true,
                "Cooldown": 0,
                "Duration": 3,
                "Effect Description" : "Restores 100 health.",
                "Description" : "A hearty drinkable meal from everyone's favorite hypercellulose gelatin timelord!!!",
                "SFX": "{eb4e9ad8-c6ac-414f-8d5e-c3d012ca6ae6}",
                "Bonuses" : {
                    "HP": 100,
                    "Stamina": 100,
                    "Tolerance": 20,
                    "Attack": 4
                    }

                }
        },
        "Concoctions":{

        },
        "Equipment": {

        },
        "Abilities" : {

        }   
    }
}

And this is the structure of the classes we are using to match the JSON:

(System.Serializable)
    public class Items
    {
        public List<ItemCategory> type { get; set; }
    }

    (System.Serializable)
    public class ItemCategory
    {
        public List<ItemBase> id { get; set; }
    }

    (System.Serializable)
    public class ItemBase
    {
        string ID { get; set; }
        string Icon { get; set; }
        string Name { get; set; }
        bool Consumable { get; set; }
        int Cooldown { get; set; }
        int Duration { get; set; }
        string EffectDescription { get; set; }
        string Description { get; set; }
        string SFX { get; set; }
        StatBonus Bonuses { get; set; }
    }

    (System.Serializable)
    public class StatBonus
    {
        int HP { get; set; }
        int Stamina { get; set; }
        int Tolerance { get; set; }
        int Attack { get; set; }
    }

However, when I use the debugger, it seems everything but the root class is null and the root class’s value is the “InventoryItems+items”, with InventoryItems being the name of the file.

How can I access an item by it’s number in the list? So items -> Consumables -> 0 and that element’s fields

The deserialization code:

TextAsset json = Resources.Load<TextAsset>("itemList");

        itemList = new Items();

        itemList = JsonConvert.DeserializeObject<Items>(json.text);

        Debug.Log(itemList);
        foreach(ItemCategory cat in itemList.type)
        {
            foreach(ItemBase b in cat.id)
            {
                Debug.Log(b.ToString());
            }
        }

Java: Error deserialising an aggregate object from JSON (HAS-A relationship)

I am getting a Can not set com.google.api.services.androidmanagement.v1.model.HardwareInfo field com.google.api.services.androidmanagement.v1.model.Device.hardwareInfo to java.util.LinkedHashMap error when I am converting a Google API Services Device object to JSON (using Jackson 2.10.0) and reading back from it in a test. The Device object consists of objects of HardwareInfo, MemoryInfo objects that seems to be failing since the ObjectMapper is reading them as LinkedHashMap instead of the actual types. I tried searching on StackOverflow and went through a load of articles but none of them seem to be addressing this JsonMappingException.

What am I doing wrong and how do I fix this? I tried using Mixin since this is a Google POJO and I cannot modify properties directly, but wasn’t able to resolve the problem. Any help regarding this would be greatly appreciated! Thanks.

The complete test code is:

import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.testng.annotations.Test;

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.api.services.androidmanagement.v1.model.Device;
import com.google.api.services.androidmanagement.v1.model.HardwareInfo;
import com.google.api.services.androidmanagement.v1.model.MemoryInfo;
import com.google.api.services.androidmanagement.v1.model.SoftwareInfo;
import com.google.common.collect.ImmutableMap;

/**
 * TODO: Document this class.
 */
public class DeviceTest {


    @Test
    public void myTest() {

        // code to build the test Device object 
        Device device = new Device();
        final List<String> prevNameList = Arrays.asList("prev-1", "prev-2", "prev-3");

        final HardwareInfo hwInfo = new HardwareInfo();
        hwInfo.setBrand("hwinfo-brand");
        hwInfo.setDeviceBasebandVersion("hwinfo-baseband-version");
        hwInfo.setManufacturer("test-manufacturer");
        hwInfo.setModel("hwinfo-model");
        hwInfo.setSerialNumber("hwinfo-serial-no");
        hwInfo.setHardware("hwinfo-hardware");

        final MemoryInfo memoryInfo = new MemoryInfo();
        memoryInfo.setTotalInternalStorage(123456789L);
        memoryInfo.setTotalRam(123456789L);

        final Map<String, String> propsMap = ImmutableMap.of(
                "prop1", "x86",
                "prop2", "ARM",
                "prop3", "Intel Itanium-based");

        device.setPolicyName("test-policy-name");
        device.setAppliedPolicyName("test-applied-policy-name");
        device.setEnrollmentTokenName("test-enrollment-token-name");
        device.setEnrollmentTokenData("test-enrollment-token-data");
        device.setEnrollmentTime("2020-01-01T00:00:00.000Z");
        device.setLastPolicySyncTime("2020-01-01T00:00:00.000Z");
        device.setLastStatusReportTime("2020-01-01T00:00:00.000Z");
        device.setLastPolicyComplianceReportTime("2020-01-01T00:00:00.000Z");
        device.setUserName("test-user-name");
        device.setName("test-name");

        device.setPreviousDeviceNames(prevNameList);
        device.setSystemProperties(propsMap);
        device.setHardwareInfo(hwInfo);
        device.setMemoryInfo(memoryInfo);

        ObjectMapper mapper = buildMapper();
        try {
            // code to convert object to JSON
            final String json = mapper.writeValueAsString(device);
            final String jsonHwInfo = mapper.writeValueAsString(device);
            System.out.println(json);

            // code to read JSON to object
            final Device deserializedDevice = mapper.readValue(json, Device.class);
            System.out.println(deserializedDevice);
        } catch (IOException | JsonProcessingException e) {
            e.print
        }
    }

    private static ObjectMapper buildMapper() {
        ObjectMapper mapper = new ObjectMapper();
        mapper.setVisibility(PropertyAccessor.FIELD, JsonAutoDetect.Visibility.ANY);
        mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
        mapper.setVisibility(PropertyAccessor.FIELD, JsonAutoDetect.Visibility.ANY);

        return mapper;
    }

}

The output for this test is:

{"appliedPolicyName":"test-applied-policy-name","enrollmentTime":"2020-01-01T00:00:00.000Z","enrollmentTokenData":"test-enrollment-token-data","enrollmentTokenName":"test-enrollment-token-name","hardwareInfo":{"brand":"hwinfo-brand","deviceBasebandVersion":"hwinfo-baseband-version","hardware":"hwinfo-hardware","manufacturer":"test-manufacturer","model":"hwinfo-model","serialNumber":"hwinfo-serial-no"},"lastPolicyComplianceReportTime":"2020-01-01T00:00:00.000Z","lastPolicySyncTime":"2020-01-01T00:00:00.000Z","lastStatusReportTime":"2020-01-01T00:00:00.000Z","memoryInfo":{"totalInternalStorage":123456789,"totalRam":123456789},"name":"test-name","policyName":"test-policy-name","previousDeviceNames":("prev-1","prev-2","prev-3"),"systemProperties":{"prop1":"x86","prop2":"ARM","prop3":"Intel Itanium-based"},"userName":"test-user-name"}
com.fasterxml.jackson.databind.JsonMappingException: Can not set com.google.api.services.androidmanagement.v1.model.HardwareInfo field com.google.api.services.androidmanagement.v1.model.Device.hardwareInfo to java.util.LinkedHashMap (through reference chain: com.google.api.services.androidmanagement.v1.model.Device("hardwareInfo"))
    at com.fasterxml.jackson.databind.JsonMappingException.wrapWithPath(JsonMappingException.java:394)
    at com.fasterxml.jackson.databind.JsonMappingException.wrapWithPath(JsonMappingException.java:353)
    at com.fasterxml.jackson.databind.deser.std.ContainerDeserializerBase.wrapAndThrow(ContainerDeserializerBase.java:181)
    at com.fasterxml.jackson.databind.deser.std.MapDeserializer._readAndBindStringKeyMap(MapDeserializer.java:539)
    at com.fasterxml.jackson.databind.deser.std.MapDeserializer.deserialize(MapDeserializer.java:364)
    at com.fasterxml.jackson.databind.deser.std.MapDeserializer.deserialize(MapDeserializer.java:29)
    at com.fasterxml.jackson.databind.ObjectMapper._readMapAndClose(ObjectMapper.java:4202)
    at com.fasterxml.jackson.databind.ObjectMapper.readValue(ObjectMapper.java:3205)
    at com.fasterxml.jackson.databind.ObjectMapper.readValue(ObjectMapper.java:3188)
    at com.mobileiron.polaris.service.androidwork.androidmanagementapi.DeviceTest.myTest(DeviceTest.java:89)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.testng.internal.MethodInvocationHelper.invokeMethod(MethodInvocationHelper.java:104)
    at org.testng.internal.Invoker.invokeMethod(Invoker.java:645)
    at org.testng.internal.Invoker.invokeTestMethod(Invoker.java:851)
    at org.testng.internal.Invoker.invokeTestMethods(Invoker.java:1177)
    at org.testng.internal.TestMethodWorker.invokeTestMethods(TestMethodWorker.java:129)
    at org.testng.internal.TestMethodWorker.run(TestMethodWorker.java:112)
    at org.testng.TestRunner.privateRun(TestRunner.java:756)
    at org.testng.TestRunner.run(TestRunner.java:610)
    at org.testng.SuiteRunner.runTest(SuiteRunner.java:387)
    at org.testng.SuiteRunner.runSequentially(SuiteRunner.java:382)
    at org.testng.SuiteRunner.privateRun(SuiteRunner.java:340)
    at org.testng.SuiteRunner.run(SuiteRunner.java:289)
    at org.testng.SuiteRunnerWorker.runSuite(SuiteRunnerWorker.java:52)
    at org.testng.SuiteRunnerWorker.run(SuiteRunnerWorker.java:86)
    at org.testng.TestNG.runSuitesSequentially(TestNG.java:1293)
    at org.testng.TestNG.runSuitesLocally(TestNG.java:1218)
    at org.testng.TestNG.runSuites(TestNG.java:1133)
    at org.testng.TestNG.run(TestNG.java:1104)
    at com.intellij.rt.testng.IDEARemoteTestNG.run(IDEARemoteTestNG.java:66)
    at com.intellij.rt.testng.RemoteTestNGStarter.main(RemoteTestNGStarter.java:110)
Caused by: java.lang.IllegalArgumentException: Can not set com.google.api.services.androidmanagement.v1.model.HardwareInfo field com.google.api.services.androidmanagement.v1.model.Device.hardwareInfo to java.util.LinkedHashMap
    at sun.reflect.UnsafeFieldAccessorImpl.throwSetIllegalArgumentException(UnsafeFieldAccessorImpl.java:167)
    at sun.reflect.UnsafeFieldAccessorImpl.throwSetIllegalArgumentException(UnsafeFieldAccessorImpl.java:171)
    at sun.reflect.UnsafeObjectFieldAccessorImpl.set(UnsafeObjectFieldAccessorImpl.java:81)
    at java.lang.reflect.Field.set(Field.java:764)
    at com.google.api.client.util.FieldInfo.setFieldValue(FieldInfo.java:245)
    at com.google.api.client.util.FieldInfo.setValue(FieldInfo.java:206)
    at com.google.api.client.util.GenericData.put(GenericData.java:103)
    at com.google.api.client.util.GenericData.put(GenericData.java:47)
    at com.fasterxml.jackson.databind.deser.std.MapDeserializer._readAndBindStringKeyMap(MapDeserializer.java:534)
    ... 30 more

json – Dividir en consulta Nosql

Quiero hacer una consulta que me proporcione para cada libro, cual es su proporción entre número de páginas y precio. Mi consulta está a medias y seria así:

introducir la descripción de la imagen aquí

La estructura de un documento libro es así:

{
  _id:valor,
  tema:"Libros",
  nombre:valor,
  precio:valor,
  paginas:valor
}

El problema es que no se como dividir el número de páginas entre su precio en Nosql ¿Que tendría que ir en Proporcion: ?

php – How to store and retrieve custom metabox data as json in wordpress api

I am trying to store metabox data as json in wordpress and then get it using wp-json api.

What i tried

$current = array(
  'id' => "in json object",
  'name' => 'name in json object'
);
$serializedArray = unserialize($current);
update_post_meta($post_id, 'ha_basic_information', serialize($current));

What i am trying to achieve
{"id": "in json object", "name": "name in json object"}

What i am getting
"s:75:"a:2:{s:2:"id";s:14:"in json object";s:4:"name";s:19:"name in json object";}";"

I want to get data as object in wp-json api. I’ve tried serialize/unserialize, json_encode/json_decode but nothing seems to work. I am new in php and can’t figure it out. there are many questions related to this but nothing seems to work.

json – JsonNode inválido cuando contiene un objeto

estoy intentando analizar un archivo JSON con referencias (JSON Pointers) usando la biblioteca json-glib en C. Al intentar analizar un nodo que contiene un objeto, obtengo el error crítico json_node_get_node_type: assertion 'JSON_NODE_IS_VALID (node)' failed.

El siguiente es mi código relevante:

GError* err;
JsonReader* reader = json_reader_new(json_parser_get_root(parser));
JsonParser* parser = json_parser_new();
json_parser_load_from_data(parser, data, -1, &err);
JsonNode* value_node = json_reader_get_value(reader);
if (JSON_NODE_HOLDS_VALUE(value_node))
{
    /* ... */
} else if (JSON_NODE_HOLDS_NULL(value_node))
{
    /* ... */
} else if (JSON_NODE_HOLDS_OBJECT(value_node))
{
    /* ... */
}
json_reader_end_member(reader);

Ya identifiqué que el error ocurre en el momento de obtener el tipo de nodo (al usar la macro JSON_NODE_HOLDS_VALUE), pero no entiendo por qué.

json rpc – windows rpc connect failure

Good afternoon! I am trying to remotely connect via rpc to the windows server where bitcoin core is running

my config

listen=1
maxconnections=15
server=1
daemon=1
rpcuser=rootrr
rpcpassword=1213
rpcallowip=(ip_remote, not local)
rpcport=8332

through the browser of the local server with bitcoin core installed, everything starts, and on the remote connection error with the host, the firewall is disabled

help me, plz =(

JSON API response reported as XSS by the vulnerability scanner. Is this a false positive?

When a user tries to access a URL (including a non-existent URL), my web service returns an HTTP 401 response. This response is JSON encoded and the body of this response contains the path requested by the 39; user, presumably for diagnostic purposes.
The answer also includes www-authenticate on your mind. If a user visits this URL in the browser, this triggers their browser to request credentials.

However, the automated scanning tools report that this is an XSS vulnerability. This seems to be due to the fact that the requested path is included, and if the requested path is also valid JavaScript code, that path is returned with the response. See the cURL output below:

curl -i & # 39; https: //myservice.example.com/"
HTTP / 2 401
server: nginx
date: tue 19 may 2020 15:02:20 GMT
content type: application / json; charset = UTF-8
content length: 167
strict-transport-security: max-age = 31536000; includeSubDomains
www-authenticate: Basic realm = "Spring"

{"timestamp": 1589900540080, "status": 401, "error": "Unauthorized", "message": "Full authentication is required to access this resource", "path": "/"}%

I think this is a false positive, because the API response is JSON coded, according to this question: XSS reflected via JSON executed with Burp, but how to do it under realistic conditions?

Am I right?

javascript – Preencher 2 ou mais campos de input (autocomplete) com o resultado de um JSON

Boa Noite pessoal

O caso é o seguinte

eu tenho um script PHP que me cria um Json com nome da pessoa e sua id

Json criado

(
  {
    "Nome_Pessoa": "Vinicius Domaia",
    "ID_Pessoa": "5"
  }
)

Arquivo BuscaPessoa.php

$PalavraPraBusca = $_REQUEST('query');

$SQL_Busca = "
SELECT SQL_CACHE Nome_Pessoa, ID_Pessoa
FROM pessoas 
WHERE Nome_Pessoa
LIKE '%$PalavraPraBusca%' 
";


$Busca = $ConnectionSystem->query($SQL_Busca) or die($ConnectionSystem->error);
$DadosAutoComplete = array();

if ($Busca->num_rows > 0) {
    while($Dados = $Busca->fetch_assoc()) {
        $DadosAutoComplete()= $Dados;

    }
    echo json_encode($DadosAutoComplete,JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
}

$ConnectionSystem->close();

O problema é aqui

<!DOCTYPE html>
<html>
<head>
    <title>Autocomplete</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-3-typeahead/4.0.2/bootstrap3-typeahead.min.js"></script>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
</head>
<body>
<br /><br />
<div class="container" style="width:600px;">
    <label>Pessoa</label>
    <input type="text" name="Pessoa" id="Campo_Pesquisa" class="form-control input-lg" autocomplete="off" placeholder="Digite o nome da pessoa" />
    <label>Id</label>
    <input type="text" name="Id" id="Id_Pessoa" class="form-control input-lg" autocomplete="off" placeholder="Id da pessoa" />

</div>

<script>
    $(document).ready(function(){
        $('#Campo_Pesquisa').typeahead({
            source: function(query, result){
                $.ajax({
                    url:"BuscaPessoa.php",
                    method:"POST",
                    data:{query:query},
                    dataType:"json",
                    success:function(data){
                        result($.map(data, function(item){
                            return item;
                        }));
                    }
                })


            }
        });

    });


</script>
</body>
</html>

Pois eu desejo que ao selecionar o nome da pessoa ele preencha o campo pessoa e o de id.

No momento só estou conseguindo colocar o nome mas a id não.

Alguém ai pode ajudar por favor?