Javscript store data from json file into map? - javascript

I´m quite new to Javascript, but know a lot about Java. Im trying to learn the basics by doing little projects, for understanding the language and code. In Java, i worked a lot with storing data from maps in json-files and, when you start the programm, the json file loads the data into the map.
An example for Java:
public Map<Integer, Client> example = new HashMap<>();
Herefor the Client class :
public class Client {
private String username;
private String password;
private String host;
public Client(String username, String password, String host) {
this.username = username;
this.password = password;
this.host = host;
}
public String getPassword() {
return password;
}
public String getHost() {
return host;
}
public String getUsername() {
return username;
}
}
I want to do the same thing, but now in Javascript. My map looks like that:
var price= new Map();
Like the Java example above, I want to load such a Map into a json file and want to load the data from the json file into my map.
Could somebody proivde me with a good example of code, how to store data from json in my map ? Even a link for a tutorial would be great!

In JS it's more common to use plain objects instead of Map().
For example, let's say you have the same Client class:
class Client {
constructor(username, password, host) {
this.username = username;
this.password = password;
this.host = host;
}
}
const client1 = new Client('username1', 'password1', 'localhost');
const client2 = new Client('username2', 'password2', 'localhost');
Your price map (int to Client) would look like this:
const price = {
1: client1,
2: client2
};
Now, you can use serialize it to json:
const json = JSON.stringify(price);
Or parse it from json:
const price = JSON.parse(json);
However, if you really want to use Map, here's a tutorial for it.

Related

How do i get RSACryptoServiceProvider to verify a message using public key and signature

I generated a private and public key in javascript like this.
import crypto from "crypto";
/*export const { publicKey, privateKey } = crypto.generateKeyPairSync("rsa", {
modulusLength: 2048,
});*/
const pair = crypto.generateKeyPairSync("rsa", { modulusLength: 2048 });
export const privateKey = pair.privateKey.export({
type: "pkcs1",
format: "pem",
});
export const publicKey = pair.publicKey.export({
type: "pkcs1",
format: "pem",
});
Then i use the private key to create a signature for a jsonfile like this, and the public key to verify it before i return the signature.
//Lav signatur
const signate = crypto.createSign("SHA384");
signate.update(Buffer.from(licenseRelationship, "utf-8"));
const signature = signate.sign(privateKey, "hex");
const verifier = crypto.createVerify("SHA384");
// verificer signature, besked
verifier.update(Buffer.from(licenseRelationship, "utf-8"));
const verificationResult = verifier.verify(publicKey, signature, "hex");
This works perfectly, and then i return the json and the signature as a http response.
I recieve it in c# code and store the two components so im can use them later on request.
Upon request i fetch the two components and want to use the signature to check if the json has been tampered with.
I also has the public key in this code.
I do it like this.
string licenseRelationshipJson = licenseRelationshipDAO.getLicenseRelationshipWithoutSignatureAsJson(licenseRelationship);
byte[] signature = Encoding.UTF8.GetBytes(licenseRelationship.signature);
byte[] licenseRelationshipJsonAsArray = Encoding.UTF8.GetBytes(licenseRelationshipJson);
RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(2048);
result = rsa.VerifyData(licenseRelationshipJsonAsArray, signature,
HashAlgorithmName.SHA384, RSASignaturePadding.Pkcs1);
if (result)
{
log.write("Message verified ", null);
} else
{
log.write("Message not Verified ", null);
}
All debug code and exception handling removed.
I'm a crypto virgin, and am trying to understand this. But i must have misunderstood something serious.
I have the public key as a string (not base64 encoded)
Ive checked the json, and it is the exact same bytes when signed in Javascript as when being verified in c#
The public key is not used in this process. That has to be wrong i think ?
How do i get the public key into the RWACryptoServiceProvider ?
Im sure im using RWACryptoServiceProvider wrong.
EDIT....:
Ive tried this instead, but still to no avail.
string licenseRelationshipJson = licenseRelationshipDAO.getLicenseRelationshipWithoutSignatureAsJson(licenseRelationship);
byte[] signature = Encoding.UTF8.GetBytes(licenseRelationship.signature);
byte[] licenseRelationshipJsonAsArray = Encoding.UTF8.GetBytes(licenseRelationshipJson);
byte[] asBytes = Encoding.ASCII.GetBytes(DataStorage.Instance.PUBLIC_KEY);
char[] publicKeyAsArray = Encoding.ASCII.GetChars(asBytes);
ReadOnlySpan<char> publicKeyChars = publicKeyAsArray;
RSA rsa = RSA.Create();
try
{
rsa.ImportFromPem(publicKeyChars);
result = rsa.VerifyData(licenseRelationshipJsonAsArray, signature, HashAlgorithmName.SHA384, RSASignaturePadding.Pkcs1);
} catch (CryptographicException cex)
{
log.write("Something went wrong with the crypto verification process", cex);
}
.
.
.
Thankyou for your time.

Html to pdf conversion and download

I have an Angular web app for simple quizzes, at the end of the last quiz I bind the result into an HTML template.
Previously I could generate a pdf file using PHP mpdf library from this HTML template, now as I am building the business logic and the security in spring boot I want to do that as well in spring boot.
I used Flying saucer and i could generate a pdf file from an HTML-template in the resources folder.
The question is how can I get this HTML file from the front end and generate a pdf file out of it and download the last to my pc?
#Service
public class PdfService {
private static final String OUTPUT_FILE = "test.pdf";
private static final String UTF_8 = "UTF-8";
#Test
public void generatePdf() throws Exception {
// We set-up a Thymeleaf rendering engine. All Thymeleaf templates
// are HTML-based files located under "src/test/resources". Beside
// of the main HTML file, we also have partials like a footer.html or
// a header. We can re-use those partials in different documents.
ClassLoaderTemplateResolver templateResolver = new ClassLoaderTemplateResolver();
templateResolver.setPrefix("/");
templateResolver.setSuffix(".html");
templateResolver.setTemplateMode(HTML);
templateResolver.setCharacterEncoding(UTF_8);
TemplateEngine templateEngine = new TemplateEngine();
templateEngine.setTemplateResolver(templateResolver);
// The data in our Thymeleaf templates is not hard-coded. Instead,
// we use placeholders in our templates. We fill these placeholders
// with actual data by passing in an object. In this example, we will
// write a letter to "John Doe".
//
// Note that we could also read this data from a JSON file, a database
// a web service or whatever.
Data data = exampleDataForJohnDoe();
Context context = new Context();
context.setVariable("data", data);
// Flying Saucer needs XHTML - not just normal HTML. To make our life
// easy, we use JTidy to convert the rendered Thymeleaf template to
// XHTML. Note that this might not work for very complicated HTML. But
// it's good enough for a simple letter.
String renderedHtmlContent = templateEngine.process("template", context);
String xHtml = convertToXhtml(renderedHtmlContent);
ITextRenderer renderer = new ITextRenderer();
renderer.getFontResolver().addFont("Code39.ttf", IDENTITY_H, EMBEDDED);
// FlyingSaucer has a working directory. If you run this test, the working directory
// will be the root folder of your project. However, all files (HTML, CSS, etc.) are
// located under "/src/test/resources". So we want to use this folder as the working
// directory.
String baseUrl = FileSystems
.getDefault()
.getPath("src", "test", "resources")
.toUri()
.toURL()
.toString();
renderer.setDocumentFromString(xHtml, baseUrl);
renderer.layout();
// And finally, we create the PDF:
OutputStream outputStream = new FileOutputStream(OUTPUT_FILE);
renderer.createPDF(outputStream);
outputStream.close();
}
private Data exampleDataForJohnDoe() {
Data data = new Data();
data.setFirstname("John");
data.setLastname("Doe");
data.setStreet("Example Street 1");
data.setZipCode("12345");
data.setCity("Example City");
return data;
}
static class Data {
private String firstname;
private String lastname;
private String street;
private String zipCode;
private String city;
public String getFirstname() {
return firstname;
}
public void setFirstname(String firstname) {
this.firstname = firstname;
}
public String getLastname() {
return lastname;
}
public void setLastname(String lastname) {
this.lastname = lastname;
}
public String getStreet() {
return street;
}
public void setStreet(String street) {
this.street = street;
}
public String getZipCode() {
return zipCode;
}
public void setZipCode(String zipCode) {
this.zipCode = zipCode;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
}
private String convertToXhtml(String html) throws UnsupportedEncodingException {
Tidy tidy = new Tidy();
tidy.setInputEncoding(UTF_8);
tidy.setOutputEncoding(UTF_8);
tidy.setXHTML(true);
ByteArrayInputStream inputStream = new ByteArrayInputStream(html.getBytes(UTF_8));
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
tidy.parseDOM(inputStream, outputStream);
return outputStream.toString(UTF_8);
}

create C# 256 bit AES encryption like cryptoJS

im trying to encrpyt a payload in c#.
i have the code in Javascript and im trying to create same encryption in C#, having hard time to recreate the same encryption.
given javascript code (cannot be changed):
var data =
{
'username':username,
'password':password,
'isPersistent':'false'
};
var encrypted = CryptoJS.AES.encrypt(JSON.stringify(data),token, { format: JsonFormatter });
var body = {
payload: JSON.parse(encrypted.toString()),
token: token
}
debugger
$.post(url, body).success(resultFunction)
i want to create the same encryption in c#
Dictionary<string, string> data = new Dictionary<string, string>();
data.Add("username", username);
data.Add("password", password);
data.Add("isPersistent", "false");
string token = "7e4bac048ef766e83f0ec8c079e1f90c2eb690a9";
string serializedData = json_serialize(data);
string encrypted = EncryptText(serializedData, token);
Dictionary<string, string> body = new Dictionary<string, string>();
body.Add("payload", json_deserialize(encrypted));
body.Add("token", token);
var loginWebRequest = createWebRequest(address, "POST", json_serialize(body));
i have several issue here, in js you can specify the format of encryption and then use JSON.parse.
it seems it cannot be done in c#.
i used the methods from http://www.codeproject.com/Articles/769741/Csharp-AES-bits-Encryption-Library-with-Salt.
is there anyway i can create the same code snippet in c#?
Thanks!
The code from this post: openssl using only .NET classes is compatible with CryptoJS AES.
Test:
JS:
var encrypted = CryptoJS.AES.encrypt("abc12345","7e4bac048ef766e83f0ec8c079e1f90c2eb690a9");
encrypted.toString(); //output: "U2FsdGVkX18eGD2hSe9UyGgTk5NGKFmvWq/3c5IYHoQ="
C#:
var p = new Protection();
var s = p.OpenSSLDecrypt("U2FsdGVkX18eGD2hSe9UyGgTk5NGKFmvWq/3c5IYHoQ=", "7e4bac048ef766e83f0ec8c079e1f90c2eb690a9");
Console.WriteLine(s);//output: "abc12345"

Parse.com Cloud Code RSA Verification - Android In App Purchase Verification

I'm trying to verify an RSA signature on Parse.com Cloud Code. Basically I am trying to do the receipt verification for an Android In App Purchase on the server.
Parse.com crypto module does not suppor the verify method. So I found a library online that I imported.
var KJUR = require("cloud/jsrsasign-4.7.0/npm/lib/jsrsasign.js");
var verifier = new KJUR.crypto.Signature({alg: "SHA1withRSA", prov: "cryptojs/jsrsa"});
verifier.initVerifyByCertificatePEM(publicKey);
verifier.updateString(purchaseData);
//verifier.updateHex(hexValue);
var result = verifier.verify(signature);
I am doing something wrong, but can't really tell what. I might be putting the signature, publicKey and purchaseData in the wrong places.
The purchaseData looks like this: (per Android specs, I altered the data)
var purchaseData = {
orderID: "12999763169854705758.1300523466622834",
packageName: "com.blabla.bla",
productID: e.purchase.SKU,
purchaseTime: new moment(time).valueOf(),
purchaseState: 0,
developerPayload: "74571d75-98b8-4327-942d-5379309c9033",
purchaseToken: "klsDmifojfknmbojimkkkdkm.AO-J1OyXvZ3RH1aPiPD2MIdOUu00FrCnuTCjl1-K3ZD4Puu0zXDPTOAKH3Dc1hq1DZwiNI-AgXwW18gDV3eU9kXCR1IwhADLvVeOSkyu5kzdUBoVNdA42Zc"
};
I get the following error:
Result: TypeError: Cannot call method 'bitLength' of undefined
at RSAKey._rsasign_verifyWithMessageHash [as verifyWithMessageHash] (jsrsasign-4.7.0/npm/lib/jsrsasign.js:251:3675)
at verify (jsrsasign-4.7.0/npm/lib/jsrsasign.js:230:10483)
at main.js:43:24
If you have any prior experience doing this, I would appreciate your help. Thanks
Here's how to do it:
var KJUR = require("cloud/jsrsasign.js");
var publicKey =
"-----BEGIN PUBLIC KEY-----\n" +
// your public key from google play
"-----END PUBLIC KEY-----\n";
var verifier = new KJUR.crypto.Signature({alg: "SHA1withRSA"});
verifier.init(publicKey);
verifier.updateString(signedData); // signedData from IAB response
var result = verifier.verify(KJUR.b64utohex(signature));
Be sure to convert the signature from base64 to hex.
I'm guessing things have changed a little with updates to jsrasign - my solution looks like this:
cloud/lib/crypto.js:
// jsrasign expects to be running in a browser and expects these to be in the global namespace
var navigator = {},
window = {};
// Include contents of jsrsasign-latest-all-min.js from https://kjur.github.io/jsrsasign/
// ------------- Snip -------------
// Expose a Validate method
exports.Validate = function(sText, sPublicKey, sSignature) {
var cVerifier = new KJUR.crypto.Signature({ alg: 'SHA1withRSA' });
cVerifier.init("-----BEGIN PUBLIC KEY-----\n" + sPublicKey + "-----END PUBLIC KEY-----\n");
cVerifier.updateString(sText);
return cVerifier.verify(b64utohex(sSignature));
};
cloud/MakePurchase.js:
var Crypto = require('cloud/lib/crypto'),
// You should have got this from https://play.google.com/apps/publish
sPublicKey = 'SomethingSlightlySecretUsing64CharactersWithNoSpacesOrNewLines';
// Assume you have done something to get back a Google receipt object containing:
// json: A stringified JSON object with the purchase details
// signature: A base64 string
// payload: Data you might have set when you made the purchase
if (Crypto.Validate(cReceipt.json, sPublicKey, cReceipt.signature)) {
// Purchase confirmed
}

How to pass a camera image to mail as an attachment. (Android, iOS, Windows Phone, Phonegap)

I am developing an app for my work (social housing) and I want it to be able to allow the user to take a photo and attach it to an email so they can send it to us (pictures of repairs etc)
I'm using Phonegap and Eclipse as I want the app to be cross platform but am testing in Android primarily at the moment. Is there a way to do this? I am currently using the code below with no avail.
<script typr="text/javascript" charset="utf-8">
function camera()
{
navigator.camera.getPicture(onSuccess, onFail, { quality: 20,
destinationType: Camera.DestinationType.DATA_URL
});
function onSuccess(imageData) {
var image = document.getElementById('image');
var data = "data:image/jpeg;base64," + imageData;
var link = "mailto:johnsmith#gmail.com?body="+data+"&subject=john smith";
window.location.href = link;
}
function onFail(message) {
alert('Failed because: ' + message);
}
}
</script>
So far I've tried passing the data through to the mail app using the mailto: &attachment method but that never attaches an image (most mail apps treat this as a security hole). Then I tried to embed the base64 code of the image in the body of the email (as shown above). Unfortunately the base64 just displays as plain text and makes mail unresponsive. I've also tried using the image URI instead of the Base64 method in Phonegap but that throws an 'image.URI is not defined' error in my logcat.
Is this possible? I know I can use intents for just android as detailed in another question here but this won't work on iOS etc.
Any help would be greatly appreciated.
EDIT 02/12/2012
What I'm trying to achieve here is the same functionality you get in the native Android gallery/camera app. After you take a picture you have share options, one of which is mail. If you chose to share via mail the image is passed to the mail app as an attachment. Is there any way I can implement this same functionality in my app?
So it looks like there is no 'one size fits all' solution for this problem.
The mailto: method just doesn't pass attachments in most modern mail apps as it's seen as a security risk. So regardless of whether its an imageURI or a base64 encoded image, mailto: just won't work. The passing of 'subject' and 'body' works well though for anyone that wants to use the above code for pre-filling in an email with no attachments.
After posing this question elsewhere it looks like I'll need to use a phonegap plugin (emailComposer for iOS and WebIntent for Android) in order to pass an image sucessfully to a mail app from my phonegap app.
Thanks.
use this JAVA code to send Email with photo and text.
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.security.Security;
import java.util.Properties;
import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.Message;
import javax.mail.Multipart;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
public class GMailSender extends javax.mail.Authenticator {
private String mailhost = "smtp.gmail.com";
private String user;
private String password;
private Session session;
static {
Security.addProvider(new JSSEProvider());
}
public GMailSender(String user, String password) {
this.user = user;
this.password = password;
Properties props = new Properties();
props.setProperty("mail.transport.protocol", "smtp");
props.setProperty("mail.host", mailhost);
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.port", "465");
props.put("mail.smtp.socketFactory.port", "465");
props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
props.put("mail.smtp.socketFactory.fallback", "false");
props.setProperty("mail.smtp.quitwait", "false");
session = Session.getDefaultInstance(props, this);
}
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(user, password);
}
public synchronized void sendMail(String subject, String body, String sender, String recipients) throws Exception {
try {
MimeMessage message = new MimeMessage(session);
DataHandler handler = new DataHandler(new ByteArrayDataSource(body.getBytes(), "text/plain"));
message.setSender(new InternetAddress(sender));
message.setSubject(subject);
message.setDataHandler(handler);
if (recipients.indexOf(',') > 0)
message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(recipients));
else
message.setRecipient(Message.RecipientType.TO, new InternetAddress(recipients));
Transport.send(message);
} catch (Exception e) {
}
}
public synchronized void sendMail(String subject, String body, String senderEmail, String recipients, String filePath,String logFilePath) throws Exception {
boolean fileExists = new File(filePath).exists();
if (fileExists) {
String from = senderEmail;
String to = recipients;
String fileAttachment = filePath;
// Define message
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(from));
message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
message.setSubject(subject);
// create the message part
MimeBodyPart messageBodyPart = new MimeBodyPart();
// fill message
messageBodyPart.setText(body);
Multipart multipart = new MimeMultipart();
multipart.addBodyPart(messageBodyPart);
// Part two is attachment
messageBodyPart = new MimeBodyPart();
DataSource source = new FileDataSource(fileAttachment);
messageBodyPart.setDataHandler(new DataHandler(source));
messageBodyPart.setFileName("screenShoot.jpg");
multipart.addBodyPart(messageBodyPart);
//part three for logs
messageBodyPart = new MimeBodyPart();
DataSource sourceb = new FileDataSource(logFilePath);
messageBodyPart.setDataHandler(new DataHandler(sourceb));
messageBodyPart.setFileName("logs.txt");
multipart.addBodyPart(messageBodyPart);
// Put parts in message
message.setContent(multipart);
// Send the message
Transport.send(message);
}else{
sendMail( subject, body, senderEmail, recipients);
}
}
public class ByteArrayDataSource implements DataSource {
private byte[] data;
private String type;
public ByteArrayDataSource(byte[] data, String type) {
super();
this.data = data;
this.type = type;
}
public ByteArrayDataSource(byte[] data) {
super();
this.data = data;
}
public void setType(String type) {
this.type = type;
}
public String getContentType() {
if (type == null)
return "application/octet-stream";
else
return type;
}
public InputStream getInputStream() throws IOException {
return new ByteArrayInputStream(data);
}
public String getName() {
return "ByteArrayDataSource";
}
public OutputStream getOutputStream() throws IOException {
throw new IOException("Not Supported");
}
}
}

Categories

Resources