Java读取文件中多个JSON对象
File file = new File("/home/renjx/testcases.json");
ObjectMapper objectMapper = new ObjectMapper();
List<Map<String, String>> maps = objectMapper.readValue(file, new TypeReference<List<Map<String, String>>>() {
});
for (Map<String, String> map : maps) {
byte[] privateKey = DatatypeConverter.parseHexBinary(map.get("private_key"));
byte[] publicKey = DatatypeConverter.parseHexBinary(map.get("public_key"));
byte[] signature = DatatypeConverter.parseHexBinary(map.get("signature"));
byte[] encrypted_message = DatatypeConverter.parseHexBinary(map.get("encrypted_message"));
String message = map.get("message");
boolean isValid = Secp256k1Crypto.verifySignature(message.getBytes(), signature, publicKey);
if (!isValid) {
logger.warn("sign and verify failed!");
break;
}
byte[] plainText = Secp256k1Crypto.decryptMessage(encrypted_message, privateKey, (byte) 0x02);
if (!Arrays.equals(plainText, message.getBytes())){
logger.warn("sign and verify failed!");
break;
}
}
将byte写入到json文件中
private static void testCVerifySignatureAndDecryptMessage() throws Exception {
byte[] privateKey = Secp256k1Crypto.generatePrivateKey();
byte[] publicKey = Secp256k1Crypto.generatePublicKeyFromPrivateKey(privateKey);
int randomInt = new Random().nextInt(512);
String hexString = CommonUtil.generateRandomHexString(randomInt * 2);
byte[] signature = Secp256k1Crypto.signMessage(hexString.getBytes(), privateKey);
byte[] cipher = Secp256k1Crypto.encryptMessage(hexString.getBytes(), publicKey, (byte) 0x02);
String private_key = bytesToHexFun(privateKey);
String public_key = bytesToHexFun(publicKey);
String signatures = bytesToHexFun(signature);
String encrypted_message = bytesToHexFun(cipher);
Map<String, Object> map = new HashMap<>();
map.put("private_key", private_key);
map.put("public_key", public_key);
map.put("signature", signatures);
map.put("encrypted_message", encrypted_message);
map.put("message", hexString);
String filePath = "/home/renjx/testcasesJava.json";
String isWrite = writeJson(filePath, map, true);
System.out.println(isWrite);
}
public static String writeJson(String jsonPath, Map<String, Object> inMap, boolean flag) {
String data = new JSONObject(inMap).toString();
File jsonFile = new File(jsonPath);
try {
if (!jsonFile.exists()) {
jsonFile.createNewFile();
}
FileWriter fileWriter = new FileWriter(jsonFile.getAbsoluteFile(), flag);
BufferedWriter bw = new BufferedWriter(fileWriter);
bw.write(data);
bw.close();
return "success";
} catch (IOException e) {
return "error";
}
}
public static String bytesToHexFun(byte[] bytes) {
char[] buf = new char[bytes.length * 2];
int index = 0;
for(byte b : bytes) {
buf[index++] = HEX_CHAR[b >>> 4 & 0xf];
buf[index++] = HEX_CHAR[b & 0xf];
}
return new String(buf);
}
private static final char[] HEX_CHAR = {'0', '1', '2', '3', '4', '5',
'6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};