Decrypt by Public key in angularjs And decrypt by Java using private key - RSA Asymmetric - angularjs

I am generating a asymmetric key pair (public and private) in java using RSA algorithm and trying to use the public key in java-script to decrypt some text and after modification of data again encrypt the data using same public key sent to spring-boot server , so that spring boot can decrypt using by private key
source link : https://github.com/jeebendu/RSA_Asymetric_Encryption/blob/main/AsymmetricMain.java
Can anyone help how to achieve in angularjs or any javascript framework CryptoJS
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.SecureRandom;
import java.security.spec.EncodedKeySpec;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.Base64;
import javax.crypto.Cipher;
public class AsymmetricMain {
private static final String ALGORITHM = "RSA";
private static final String PVTKEY = "MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQCa1OwhIXq10pykhtCap/stVCL0 X/1VyyeAl82HXEHotvw8F6TR8y9AsARdgSpHn6ozPaHSvo39QqTPvni065iaYidXFt4rR6dLrQ8S Ar1edbVQ/L//DCSQPQezmr0fL88R2oMO/MdPVPLlnwTJMXhMCQTnKydD/otShjSfpd9FVqII9BGh MR68pUBCtLgNcmn1YgBqXUyUGWahFbPsOAn0yRD+/28Y3xDYu3y3rNINITNf2bS2GKbmhKV1QLjp 0v7N5VppWBrrYlRSmlMyf2/1ChZPWEPUjdC117aR+PDY6t6dPtcap/pCxU4vQo1oIZBre1AEfoCe mt5bNj4yB30rAgMBAAECggEAeXfn1EomsfSMTYsyptJ4fORQE/YmkqMx13HAnZwkXQUJt7844Dlv 7cjpc838tHovlcmZZfN3A6TAFfcxTYazjxLIGEvpenzZY8ZeV1vs4ulnmSThH5+QI9StcRtJmejx A+mw/hYT60oS0VBC+fCklspQnWc+g9pzxQdiy4jfM8534yjv8FnFQqRxuqAZfbJraSx5E+nT3XSt IrLriMoKsNaLSzXn+RulGJndxRmcZ63j+rmoiEPxl9nrU0S/ZwLfvuaCv1wy7kuJB80Gfc8W3N7m 8sq5o8pAqxRe6nz1WnI5EabArSyysOOeZdXC9lt3liLUMy2EO3QYX7chiewdWQKBgQDzLB90HI5H o1pNzPA/SNVD1pZIENtgCI+ssrJymjwZNAZBP8OKYCbygmXsO3cwTvxJ7F3d0kif+aa6ndjgU+9B 71z/QZD81pKmbTHqvOU/ceEEP02DufIANaUPzR/ZRAtzgRmW3o1O2qQu7uZyFQAbgqh9sci3NqTb f2FfvMfLvQKBgQCi/9HJZHZwSdhpRVEYfQPVCa4Wmhd/PNc7nWCrex0RpTxCx7ov67O4kDnwRKVa 6en2D2GDgB0nZRq54tURrAe+J63gEqghlEI8kgC3jZazZyTtyVm4vL+Sb0ssadc+47LnGtoR6ibE +LId5RPKmmTwR0UUgVDZOtQwZf+xYIXHBwKBgQCvFtH+9KCtjDz1T96ccoC8O8IxWZHbb86jdndu dQdYzlDConrVI65nZuSkV5zWN8kIIRzlHwgTx9n4/Lavrz/Spdq8ICWZJ5aoJm+OqTwXlpOCT2Is urI43GdhHT0VXx0vqYEXVF9Cq8MT2AgtlFljdYyEFIKFCN9i/DDMkkz5sQKBgHm1OMj+2az4hr38 AxSc7EqbYsD/qAHaxP9/gJoqYEc3sOpQRgbYISbzkj+Ekk9zD74qN+6/r4Ul6jHYXK5IXLOw3xTL +XyxPlAJ2L013MvyfVGMIhFd5lGKBoCQOyd7T69ejmwIAZDb/etyjDeg1zPOk5c/A8ZgNeY5kxW3 88vrAoGBAIfCKxtchHtCDj0mp+mBmXUCxzywMJgHfdnBXd1McUdeJS0ExTNKifY3YESCQdwfVgFX 681wzsNdENQpGrN1VF47zZvra33/2cwy2eGB1wOb9wDuJiYwZWV5uTkvaf3q9+N8m03V9gJrR4tj wXnJZOeA1/4gjkmWdzoTCg0zO1LT";
private static final String PUBKEY = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAmtTsISF6tdKcpIbQmqf7LVQi9F/9VcsngJfNh1xB6Lb8PBek0fMvQLAEXYEqR5+qMz2h0r6N/UKkz754tOuYmmInVxbeK0enS60PEgK9XnW1UPy//wwkkD0Hs5q9Hy/PEdqDDvzHT1Ty5Z8EyTF4TAkE5ysnQ/6LUoY0n6XfRVaiCPQRoTEevKVAQrS4DXJp9WIAal1MlBlmoRWz7DgJ9MkQ/v9vGN8Q2Lt8t6zSDSEzX9m0thim5oSldUC46dL+zeVaaVga62JUUppTMn9v9QoWT1hD1I3Qtde2kfjw2OrenT7XGqf6QsVOL0KNaCGQa3tQBH6AnpreWzY+Mgd9KwIDAQAB";
// Generating public & private keys
// using RSA algorithm.
public static KeyPair generateRSAKkeyPair() throws Exception {
SecureRandom secureRandom = new SecureRandom();
KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(ALGORITHM);
keyPairGenerator.initialize(2048, secureRandom);
return keyPairGenerator.generateKeyPair();
}
// Encryption function which converts
// the plainText into a cipherText
// using private Key.
public static byte[] encrypt(String plainText, PrivateKey privateKey) throws Exception {
Cipher cipher = Cipher.getInstance(ALGORITHM);
cipher.init(Cipher.ENCRYPT_MODE, privateKey);
return cipher.doFinal(plainText.getBytes());
}
// Decryption function which converts
// the ciphertext back to the
// original plaintext.
public static String decrypt(byte[] cipherText, PublicKey publicKey) throws Exception {
Cipher cipher = Cipher.getInstance(ALGORITHM);
cipher.init(Cipher.DECRYPT_MODE, publicKey);
byte[] result = cipher.doFinal(cipherText);
return new String(result);
}
public static byte[] encrypt(String plainText, PublicKey publicKey) throws Exception {
Cipher cipher = Cipher.getInstance(ALGORITHM);
cipher.init(Cipher.ENCRYPT_MODE, publicKey);
return cipher.doFinal(plainText.getBytes());
}
public static String decrypt(byte[] cipherText, PrivateKey privateKey) throws Exception {
Cipher cipher = Cipher.getInstance(ALGORITHM);
cipher.init(Cipher.DECRYPT_MODE, privateKey);
byte[] decryptedBytes = cipher.doFinal(cipherText);
return new String(decryptedBytes);
}
public static PublicKey getPublicKey(byte[] pk) throws NoSuchAlgorithmException, InvalidKeySpecException {
EncodedKeySpec publicKeySpec = new X509EncodedKeySpec(pk);
KeyFactory kf = KeyFactory.getInstance(ALGORITHM);
PublicKey pub = kf.generatePublic(publicKeySpec);
return pub;
}
public static PrivateKey getPrivateKey(byte[] privk) throws NoSuchAlgorithmException, InvalidKeySpecException {
PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(privk);
KeyFactory kf = KeyFactory.getInstance("RSA");
PrivateKey privKey = kf.generatePrivate(keySpec);
return privKey;
}
// Driver code
public static void main(String args[]) throws Exception {
springToAngularJS();
}
// Encrypt the data by private key and send to angularjs
private static void springToAngularJS() {
try {
/*
KeyPair keypair = generateRSAKkeyPair();
System.out.println ("-----BEGIN PRIVATE KEY-----");
System.out.println (Base64.getMimeEncoder().encodeToString( keypair.getPrivate().getEncoded()));
System.out.println ("-----END PRIVATE KEY-----");
System.out.println ("-----BEGIN PUBLIC KEY-----");
System.out.println (Base64.getMimeEncoder().encodeToString( keypair.getPublic().getEncoded()));
System.out.println ("-----END PUBLIC KEY-----");
*/
String plainText = "This is the PlainText " + "I want to Encrypt using RSA.";
byte[] encodedPublicKey = Base64.getDecoder().decode((PUBKEY.replace(" ", "").getBytes()));
byte[] encodedPrivateKey = Base64.getDecoder().decode((PVTKEY.replace(" ", "").getBytes()));
PublicKey publicKey = getPublicKey(encodedPublicKey);
PrivateKey privateKey = getPrivateKey(encodedPrivateKey);
byte[] cipherText = encrypt(plainText, privateKey);
//System.out.println( "The Public Key is: " + DatatypeConverter.printHexBinary(keypair.getPublic().getEncoded()));
//System.out.println( "The Private Key is: " + DatatypeConverter.printHexBinary(keypair.getPrivate().getEncoded()));
System.out.print("Backend :The Encrypted Text is: ");
System.out.println(Base64.getEncoder().encodeToString(cipherText));
String decryptedText = decrypt(cipherText, publicKey);
System.out.println("Backend : The decrypted text is: " + decryptedText);
angularjsToSpringboot(Base64.getEncoder().encodeToString(cipherText));
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
//Receive encrypted data from springboot and decrypt by public key
//After any modification encrypt by public key and sent to springboot
private static void angularjsToSpringboot(String cipherText) {
try {
byte[] encodedPublicKey = Base64.getDecoder().decode((PUBKEY.replace(" ", "").getBytes()));
PublicKey publicKey = getPublicKey(encodedPublicKey);
String decryptedText = decrypt(Base64.getDecoder().decode(cipherText), publicKey);
System.out.println("Public : The decrypted text is: " + decryptedText);
byte[] dataEncByPublicKey = encrypt(decryptedText, publicKey);
System.out.print("Public : The Encrypted Text is: ");
System.out.println(Base64.getEncoder().encodeToString(dataEncByPublicKey));
decryptBySpringboot(Base64.getEncoder().encodeToString(dataEncByPublicKey));
//decryptBySpringboot(DatatypeConverter.printHexBinary(dataEncByPublicKey));
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
//receive encrypted data and decrypt by private key and save to db
private static void decryptBySpringboot(String cipherText) {
try {
byte[] encodedPrivateKey = Base64.getDecoder().decode((PVTKEY.replace(" ", "").getBytes()));
PrivateKey privateKey = getPrivateKey(encodedPrivateKey);
String decryptedText = decrypt(Base64.getDecoder().decode(cipherText), privateKey);
System.out.println("Backend : The decrypted text is: " + decryptedText);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}

I am generating a asymmetric key pair (public and private) in java
using RSA algorithm and trying to use the public key in java-script to
decrypt some text
You can not use the public key to decrypt. In Asymmetric encryption only private key can decrypt.
and after modification of data again encrypt the
data using same public key sent to spring-boot server , so that spring
boot can decrypt using by private key
Why don't you just use HTTPS/SSL protocol instead of doing your own encryption/decryption. Asymmetric encryption is not good for large content anyway.

Related

Accept Multipart file upload as camel restlet or cxfrs endpoint

I am looking to implement a route where reslet/cxfrs end point will accept file as multipart request and process. (Request may have some JSON data as well.
Thanks in advance.
Regards.
[EDIT]
Have tried following code. Also tried sending file using curl. I can see file related info in headers and debug output, but not able to retrieve attachment.
from("servlet:///hello").process(new Processor() {
#Override
public void process(Exchange exchange) throws Exception {
Message in = exchange.getIn();
StringBuffer v = new StringBuffer();
HttpServletRequest request = (HttpServletRequest) in
.getHeaders().get(Exchange.HTTP_SERVLET_REQUEST);
DiskFileItemFactory diskFile = new DiskFileItemFactory();
FileItemFactory factory = diskFile;
ServletFileUpload upload = new ServletFileUpload(factory);
List items = upload.parseRequest(request);
.....
curl :
curl -vvv -i -X POST -H "Content-Type: multipart/form-data" -F "image=#/Users/navaltiger/1.jpg; type=image/jpg" http://:8080/JettySample/camel/hello
following code works (but can't use as it embeds jetty, and we would like to deploy it on tomcat/weblogic)
public void configure() throws Exception {
// getContext().getProperties().put("CamelJettyTempDir", "target");
getContext().setStreamCaching(true);
getContext().setTracing(true);
from("jetty:///test").process(new Processor() {
// from("servlet:///hello").process(new Processor() {
public void process(Exchange exchange) throws Exception {
String body = exchange.getIn().getBody(String.class);
HttpServletRequest request = exchange.getIn().getBody(
HttpServletRequest.class);
StringBuffer v = new StringBuffer();
// byte[] picture = (request.getParameter("image")).getBytes();
v.append("\n Printing All Request Parameters From HttpSerlvetRequest: \n+"+body +" \n\n");
Enumeration<String> requestParameters = request
.getParameterNames();
while (requestParameters.hasMoreElements()) {
String paramName = (String) requestParameters.nextElement();
v.append("\n Request Paramter Name: " + paramName
+ ", Value - " + request.getParameter(paramName));
}
I had a similar problem and managed to resolve inspired by the answer of brentos. The rest endpoint in my case is defined via xml:
<restContext id="UploaderServices" xmlns="http://camel.apache.org/schema/spring">
<rest path="/uploader">
<post bindingMode="off" uri="/upload" produces="application/json">
<to uri="bean:UploaderService?method=uploadData"/>
</post>
</rest>
</restContext>
I had to use "bindingMode=off" to disable xml/json unmarshalling because the HttpRequest body contains multipart data (json/text+file) and obviously the standard unmarshaling process was unable to process the request because it's expecting a string in the body and not a multipart payload.
The file and other parameters are sent from a front end that uses the file upload angular module: https://github.com/danialfarid/ng-file-upload
To solve CORS problems I had to add a CORSFilter filter in the web.xml like the one here:
public class CORSFilter implements Filter {
#Override
public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws IOException,
ServletException {
HttpServletResponse httpResp = (HttpServletResponse) resp;
HttpServletRequest httpReq = (HttpServletRequest) req;
httpResp.setHeader("Access-Control-Allow-Methods", "GET, HEAD, POST, PUT, DELETE, TRACE, OPTIONS, CONNECT, PATCH");
httpResp.setHeader("Access-Control-Allow-Origin", "*");
if (httpReq.getMethod().equalsIgnoreCase("OPTIONS")) {
httpResp.setHeader("Access-Control-Allow-Headers",
httpReq.getHeader("Access-Control-Request-Headers"));
}
chain.doFilter(req, resp);
}
#Override
public void init(FilterConfig arg0) throws ServletException {
}
#Override
public void destroy() {
}
}
Also, I had to modify a little bit the unmarshaling part:
public String uploadData(Message exchange) {
String contentType=(String) exchange.getIn().getHeader(Exchange.CONTENT_TYPE);
MediaType mediaType = MediaType.valueOf(contentType); //otherwise the boundary parameter is lost
InputRepresentation representation = new InputRepresentation(exchange
.getBody(InputStream.class), mediaType);
try {
List<FileItem> items = new RestletFileUpload(
new DiskFileItemFactory())
.parseRepresentation(representation);
for (FileItem item : items) {
if (!item.isFormField()) {
InputStream inputStream = item.getInputStream();
// Path destination = Paths.get("MyFile.jpg");
// Files.copy(inputStream, destination,
// StandardCopyOption.REPLACE_EXISTING);
System.out.println("found file in request:" + item);
}else{
System.out.println("found string in request:" + new String(item.get(), "UTF-8"));
}
}
} catch (Exception e) {
e.printStackTrace();
}
return "200";
}
I'm using the Camel REST DSL with Restlet and was able to get file uploads working with the following code.
rest("/images").description("Image Upload Service")
.consumes("multipart/form-data").produces("application/json")
.post().description("Uploads image")
.to("direct:uploadImage");
from("direct:uploadImage")
.process(new Processor() {
#Override
public void process(Exchange exchange) throws Exception {
MediaType mediaType =
exchange.getIn().getHeader(Exchange.CONTENT_TYPE, MediaType.class);
InputRepresentation representation =
new InputRepresentation(
exchange.getIn().getBody(InputStream.class), mediaType);
try {
List<FileItem> items =
new RestletFileUpload(
new DiskFileItemFactory()).parseRepresentation(representation);
for (FileItem item : items) {
if (!item.isFormField()) {
InputStream inputStream = item.getInputStream();
Path destination = Paths.get("MyFile.jpg");
Files.copy(inputStream, destination,
StandardCopyOption.REPLACE_EXISTING);
}
}
} catch (FileUploadException | IOException e) {
e.printStackTrace();
}
}
});
you can do this with restdsl even if you are not using restlet (exemple jetty) for your restdsl component.
you need to turn restdinding of first for that route and reate two classes to handle the multipart that is in your body.
you need two classes :
DWRequestContext
DWFileUpload
and then you use them in your custom processor
here is the code :
DWRequestContext.java
import org.apache.camel.Exchange;
import org.apache.commons.fileupload.RequestContext;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
public class DWRequestContext implements RequestContext {
private Exchange exchange;
public DWRequestContext(Exchange exchange) {
this.exchange = exchange;
}
public String getCharacterEncoding() {
return StandardCharsets.UTF_8.toString();
}
//could compute here (we have stream cache enabled)
public int getContentLength() {
return (int) -1;
}
public String getContentType() {
return exchange.getIn().getHeader("Content-Type").toString();
}
public InputStream getInputStream() throws IOException {
return this.exchange.getIn().getBody(InputStream.class);
}
}
DWFileUpload.java
import org.apache.camel.Exchange;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUpload;
import org.apache.commons.fileupload.FileUploadException;
import java.util.List;
public class DWFileUpload extends
FileUpload {
public DWFileUpload() {
super();
}
public DWFileUpload(FileItemFactory fileItemFactory) {
super(fileItemFactory);
}
public List<FileItem> parseInputStream(Exchange exchange)
throws FileUploadException {
return parseRequest(new DWRequestContext(exchange));
}
}
you can define your processor like this:
routeDefinition.process(new Processor() {
#Override
public void process(Exchange exchange) throws Exception {
// Create a factory for disk-based file items
DiskFileItemFactory factory = new DiskFileItemFactory();
factory.setRepository(new File(System.getProperty("java.io.tmpdir")));
DWFileUpload upload = new DWFileUpload(factory);
java.util.List<FileItem> items = upload.parseInputStream(exchange);
//here I assume I have only one, but I could split it here somehow and link them to camel properties...
//with this, the first file sended with your multipart replaces the body
// of the exchange for the next processor to handle it
exchange.getIn().setBody(items.get(0).getInputStream());
}
});
I stumbled into the same requirement of having to consume a multipart request (containing file data including binary) through Apache Camel Restlet component.
Even though 2.17.x is out, since my project was part of a wider framework / application, I had to be using version 2.12.4.
Initially, my solution drew a lot from restlet-jdbc example yielded data in exchange that although was successfully retrieving text files but I was unable to retrieve correct binary content.
I attempted to dump the data directly into a file to inspect the content using following code (abridged).
from("restlet:/upload?restletMethod=POST")
.to("direct:save-files");
from("direct:save-files")
.process(new org.apache.camel.Processor(){
public void process(org.apache.camel.Exchange exchange){
/*
* Code to sniff exchange content
*/
}
})
.to("file:///C:/<path to a folder>");
;
I used org.apache.commons.fileupload.MultipartStream from apache fileuplaod library to write following utility class to parse Multipart request from a file. It worked successfully when the output of a mulitpart request from Postman was fed to it. However, failed to parse content of the file created by Camel (even through to eyes content of both files looked similar).
public class MultipartParserFileCreator{
public static final String DELIMITER = "\\r?\\n";
public static void main(String[] args) throws Exception {
// taking it from the content-type in exchange
byte[] boundary = "------5lXVNrZvONBWFXxd".getBytes();
FileInputStream fis = new FileInputStream(new File("<path-to-file>"));
extractFile(fis, boundary);
}
public static void extractFile(InputStream is, byte[] boundary) throws Exception {
MultipartStream multipartStream = new MultipartStream(is, boundary, 1024*4, null);
boolean nextPart = multipartStream.skipPreamble();
while (nextPart) {
String headers = multipartStream.readHeaders();
if(isFileContent(headers)) {
String filename = getFileName(headers);
File file = new File("<dir-where-file-created>"+filename);
if(!file.exists()) {
file.createNewFile();
}
FileOutputStream fos = new FileOutputStream(file);
multipartStream.readBodyData(fos);
fos.flush();
fos.close();
}else {
multipartStream.readBodyData(System.out);
}
nextPart = multipartStream.readBoundary();
}
}
public static String[] getContentDispositionTokens(String headersJoined) {
String[] headers = headersJoined.split(DELIMITER, -1);
for(String header: headers) {
System.out.println("Processing header: "+header);
if(header != null && header.startsWith("Content-Disposition:")) {
return header.split(";");
}
}
throw new RuntimeException(
String.format("[%s] header not found in supplied headers [%s]", "Content-Disposition:", headersJoined));
}
public static boolean isFileContent(String header) {
String[] tokens = getContentDispositionTokens(header);
for (String token : tokens) {
if (token.trim().startsWith("filename")) {
return true;
}
}
return false;
}
public static String getFileName(String header) {
String[] tokens = getContentDispositionTokens(header);
for (String token : tokens) {
if (token.trim().startsWith("filename")) {
String filename = token.substring(token.indexOf("=") + 2, token.length()-1);
System.out.println("fileName is " + filename);
return filename;
}
}
return null;
}
}
On debugging through the Camel code, I noticed that at one stage Camel is converting the entire content into String. After a point I had to stop pursuing this approach as there was very little on net applicable for version 2.12.4 and my work was not going anywhere.
Finally, I resorted to following solution
Write an implementation of HttpServletRequestWrapper to allow
multiple read of input stream. One can get an idea from
How to read request.getInputStream() multiple times
Create a filter that uses the above to wrap HttpServletRequest object, reads and extract the file to a directory Convenient way to parse incoming multipart/form-data parameters in a Servlet and attach the path to the request using request.setAttribute() method. With web.xml, configure this filter on restlet servlet
In the process method of camel route, type cast the
exchange.getIn().getBody() in HttpServletRequest object, extract the
attribute (path) use it to read the file as ByteStreamArray for
further processing
Not the cleanest, but I could achieve the objective.

Send JSon from Server to Client in GCM

I am Using GCM (Google Cloud Messaging).In that what i want i want to send J Son from the server side .On Client side I want to receive that for simple message i have done but i am stucked how could i pass J Son from the server side to the client side.
Please help me to resolve this.
This is my Server side code
public class GCMBroadcast extends HttpServlet {
private static final long serialVersionUID = 1L;
private static final String SENDER_ID = "";
private static final String ANDROID_DEVICE = "";
private List<String> androidTargets = new ArrayList<String>();
public GCMBroadcast() {
super();
androidTargets.add(ANDROID_DEVICE);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String collapseKey = "";
String userMessage = "";
try {
userMessage = request.getParameter("Message");
collapseKey = request.getParameter("CollapseKey");
} catch (Exception e) {
e.printStackTrace();
return;
}
Sender sender = new Sender(SENDER_ID);
Message message = new Message.Builder()
.collapseKey(collapseKey)
.addData("message", userMessage)
.build();
try {
MulticastResult result = sender.send(message, androidTargets, 1);
System.out.println("Response: " + result.getResults().toString());
if (result.getResults() != null) {
int canonicalRegId = result.getCanonicalIds();
if (canonicalRegId != 0) {
System.out.println("response " +canonicalRegId );
}
} else {
int error = result.getFailure();
System.out.println("Broadcast failure: " + error);
}
} catch (Exception e) {
e.printStackTrace();
}
request.setAttribute("CollapseKey", collapseKey);
request.setAttribute("Message", userMessage);
request.getRequestDispatcher("XX.jsp").forward(request, response);
}
}
Your payload (added to the Message by calls to addData) can only be name/value pairs. If you want to send a JSON, you can put a JSON string in the value of such name/value pair. Then you'll have to parse that JSON yourself in the client side.
For example :
.addData("message","{\"some_json_key\":\"some_json_value\"}")

Signing base_string in OAuth

Hi i am trying to implement OAuth1.0 following this tutorial in this tutorial there is a heading OAuthGetRequestToken
in which for getting request token we have to send a post request to URL
www.google.com/accounts/OAuthGetRequestToken
i am sending a post request in my code in google app engine my code is:
public class HelloWorldServlet extends HttpServlet {
#SuppressWarnings({ "unchecked", "unchecked" })
public void doGet(HttpServletRequest req, HttpServletResponse resp)
throws IOException {
resp.setContentType("text/html");
resp.getWriter().println("<html><head> <meta name=\"google-site-verification\" content=\"OBFeK6hFEbTkNdcYc-SQNH9tCTpcht-HkUdj6IgCaLg\" </head>");
resp.getWriter().println("<body>Hello, world");
//String post="key=AIzaSyBgmwbZaW3-1uaVOQ9UqlyHAUxvQtHe7X0&oauth_consumer_key=iriteshmehandiratta.appspot.com";
//String param= "&oauth_callback=\"https://www.iriteshmehandiratta.appspot.com\"&scope=\"http://www.google.com/calendar/feeds\"";
//URL url=new URL("https://www.googleapis.com/prediction/v1.5/trainedmodels/10/predict?");
TreeMap<String,String> tree=new TreeMap<String,String>();
tree.put("oauth_version","1.0");
tree.put("oauth_nonce", System.currentTimeMillis()+"");
tree.put("oauth_timestamp",System.currentTimeMillis()/1000+"");
tree.put("oauth_consumer_key", "imehandirattaritesh.appspot.com");
tree.put("oauth_signature_method", "RSA-SHA1");
ServletContext context = getServletContext();
PrivateKey privKey = getPrivateKey(context,"/myrsakey11.pk8");
tree.put("oauth_callback", "https://imehandirattaritesh.appspot.com/authsub");
tree.put("scope", "https://www.google.com/calendar/feeds");
Set set = tree.entrySet();
Iterator<Map.Entry<String, String>> i = set.iterator();
String datastring="";
Map.Entry me=(Map.Entry)i.next();
datastring=me.getKey()+"=";
datastring+=me.getValue();
while(i.hasNext()) {
me = (Map.Entry)i.next();
datastring+="&"+me.getKey()+"=";
datastring+=(me.getValue());
}
String data_string="GET&https://www.google.com/accounts/OAuthGetRequestToken&"+datastring;
byte[] xx11;
String str = null;
try {
xx11 = sign(privKey,data_string);
str=new String(xx11);
resp.getWriter().println(str);
} catch (GeneralSecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
URL url=new URL("https://www.google.com/accounts/OAuthGetRequestToken?"+str);
// resp.getWriter().println(""+datastring);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
urlConnection.setRequestProperty("Authorization", " OAuth");
urlConnection.setRequestMethod("GET");
urlConnection.setDoOutput(true);
BufferedReader in = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
resp.getWriter().println( urlConnection.getResponseCode());
String xx="";
String xx1="";
while((xx1=in.readLine()) != null)
{
xx+=xx1;
}
resp.getWriter().println("response");
resp.getWriter().println(xx);
resp.getWriter().println("</body></html>");
}
public static PrivateKey getPrivateKey(ServletContext context,String privKeyFileName) throws IOException {
InputStream resourceContent = context.getResourceAsStream("/WEB-INF/myrsakey11.pk8");
// FileInputStream fis = new FileInputStream(privKeyFile);
DataInputStream dis = new DataInputStream(resourceContent);
#SuppressWarnings("deprecation")
String str="";
String str1="";
while((str=dis.readLine())!=null)
{
str1+=str;
}
String BEGIN = "-----BEGIN PRIVATE KEY-----";
String END = "-----END PRIVATE KEY-----";
// String str = new String(privKeyBytes);
if (str1.contains(BEGIN) && str1.contains(END)) {
str1 = str1.substring(BEGIN.length(), str1.lastIndexOf(END));
}
KeyFactory fac;
try {
fac = KeyFactory.getInstance("RSA");
EncodedKeySpec privKeySpec= new PKCS8EncodedKeySpec(Base64.decode(str1));
return fac.generatePrivate(privKeySpec);
} catch (NoSuchAlgorithmException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (Base64DecoderException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvalidKeySpecException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
byte[] sign(PrivateKey key, String data) throws GeneralSecurityException {
Signature signature = Signature.getInstance("SHA1withRSA");
signature.initSign(key);
signature.update(data.getBytes());
return signature.sign();
}
}
first i generate data_string then sign it using my private key i get an encrypted string like this
F????T???&??$????????l:v????x???}??U-'?"?????U?[?kr^?G?(? ???qT0??]??j???5??`??$??AD??T??#<t?,#:`V????????????
then i concatenate it with
url : https://www.google.com/accounts/OAuthGetRequestToken?
and i get 400 error obviously it is not a valid uri format so i get this error.i post a query on stackoverflow a person suggest me to use sign method and after signing data_string i will get oauth_signature embedded in the return string which is variable str but in place of oauth_signature included i am getting an encrypted string can any one please tell me how to sign this data_string and what mistake i am doing ??
I would suggest you use an existing Java library for doing the OAuth. It will be much easier in the long term and you won't have to worry about debugging the protocol.

FileInputFormat where filename is KEY and text contents are VALUE

I'd like to use an entire file as a single record for MAP processing, with the filename as the key.
I've read the following post: How to get Filename/File Contents as key/value input for MAP when running a Hadoop MapReduce Job?
and while the theory of the top answer is solid, no code or "how-to" is actually provided.
Here is my custom FileInputFormat and the corresponding RecordReader, which compile, yet do not produce ANY record data.
Thanks for any help.
public class CommentsInput
extends FileInputFormat<Text,Text> {
protected boolean isSplitable(FileSystem fs, Path filename)
{
return false;
}
#Override
public RecordReader<Text, Text> createRecordReader(InputSplit split, TaskAttemptContext ctx)
throws IOException, InterruptedException {
return new CommentFileRecordReader((FileSplit) split, ctx.getConfiguration());
}
/////////////////////////
public class CommentFileRecordReader
extends RecordReader<Text,Text> {
private InputStream in;
private long start;
private long length;
private long position;
private Text key;
private Text value;
private boolean processed;
private FileSplit fileSplit;
private Configuration conf;
public CommentFileRecordReader(FileSplit fileSplit, Configuration conf) throws IOException
{
this.fileSplit = fileSplit;
this.conf=conf;
}
/** Boilerplate initialization code for file input streams. */
#Override
public void initialize(InputSplit split,
TaskAttemptContext context)
throws IOException, InterruptedException {
Configuration conf = context.getConfiguration();
fileSplit = (FileSplit) split;
this.start = fileSplit.getStart();
this.length = fileSplit.getLength();
this.position = 0;
this.processed = false;
Path path = fileSplit.getPath();
FileSystem fs = path.getFileSystem(conf);
FSDataInputStream in = fs.open(path);
CompressionCodecFactory codecs = new CompressionCodecFactory(conf);
CompressionCodec codec = codecs.getCodec(path);
if (codec != null)
this.in = codec.createInputStream(in);
else
this.in = in;
// If using Writables:
// key = new Text();
// value = new Text();
}
public boolean next(Text key, Text value) throws IOException
{
if(!processed)
{
key = new Text(fileSplit.getPath().toString());
Path file = fileSplit.getPath();
FileSystem fs = file.getFileSystem(conf);
FSDataInputStream in = null;
byte[] contents = new byte[(int) fileSplit.getLength()];
try
{
in = fs.open(file);
IOUtils.readFully(in, contents, 0, contents.length);
value.set(contents.toString());
}
finally
{
IOUtils.closeStream(in);
}
processed = true;
return true;
}
return false;
}
#Override
public boolean nextKeyValue() throws IOException {
// TODO parse the next key value, update position and return true.
return false;
}
#Override
public Text getCurrentKey() {
return key;
}
#Override
public Text getCurrentValue() {
return value;
}
/** Returns our progress within the split, as a float between 0 and 1. */
#Override
public float getProgress() {
if (length == 0)
return 0.0f;
return Math.min(1.0f, position / (float)length);
}
#Override
public void close() throws IOException {
if (in != null)
in.close();
}
}
You need to find a way to define your own key class and make sure your classes use it. You can look up how to define your own key class and you can get a file name by calling hte getName() method on its path then use it to make your key.

Android: database reading problem throws exception

i am having this problem with the android database. I adopted the DBAdapter file the NotepadAdv3 example from the google android page.
DBAdapter.java
public class DBAdapter {
private static final String TAG = "DBAdapter";
private static final String DATABASE_NAME = "PasswordDb";
private static final String DATABASE_TABLE = "myuserdata";
private static final String DATABASE_USERKEY = "myuserkey";
private static final int DATABASE_VERSION = 2;
public static final String KEY_USERKEY = "userkey";
public static final String KEY_TITLE = "title";
public static final String KEY_DATA = "data";
public static final String KEY_ROWID = "_id";
private final Context mContext;
private DatabaseHelper mDbHelper;
private SQLiteDatabase mDb;
private static final String DB_CREATE_KEY =
"create table " + DATABASE_USERKEY
+ " ("
+ "userkey text not null"
+");";
private static final String DB_CREATE_DATA =
"create table " + DATABASE_TABLE
+ " ("
+ "_id integer primary key autoincrement, "
+ "title text not null"
+ "data text"
+");";
private static class DatabaseHelper extends SQLiteOpenHelper {
DatabaseHelper(Context context)
{
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db)
{
db.execSQL(DB_CREATE_KEY);
db.execSQL(DB_CREATE_DATA);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion,
int newVersion)
{
Log.w(TAG, "Upgrading database from version " + oldVersion
+ " to "
+ newVersion + ", which will destroy all old data");
db.execSQL("DROP TABLE IF EXISTS myuserkey");
db.execSQL("DROP TABLE IF EXISTS myuserdata");
onCreate(db);
}
}
public DBAdapter(Context ctx)
{
this.mContext = ctx;
}
public DBAdapter Open() throws SQLException{
try {
mDbHelper = new DatabaseHelper(mContext);
}
catch(Exception e){
Log.e(TAG, e.toString());
}
mDb = mDbHelper.getWritableDatabase();
return this;
}
public void close(){
mDbHelper.close();
}
public Long storeKey(String userKey){
ContentValues initialValues = new ContentValues();
initialValues.put(KEY_USERKEY, userKey);
try {
mDb.delete(DATABASE_USERKEY, "1=1", null);
}
catch(Exception e)
{
Log.e(TAG, e.toString());
}
return mDb.insert(DATABASE_USERKEY, null, initialValues);
}
public String retrieveKey() {
final Cursor c;
try {
c = mDb.query(DATABASE_USERKEY, new String[] {
KEY_USERKEY},
null,
null,
null,
null,
null);
}catch(Exception e){
Log.e(TAG, e.toString());
return "";
}
if(c.moveToFirst()){
return c.getString(0);
}
else{
Log.d(TAG, "UserKey Empty");
}
return "";
}
//not including any function related to "myuserdata" table
}
Class1.java
{
mUserKey = mDbHelper.retrieveKey();
mDbHelper.storeKey(Key);
}
the error that i am receiving is from Log.e(TAG, e.toString()) in the methods retrieveKey() and storeKey()
"no such table: myuserkey: , while compiling: SELECT userkey FROM myuserkey"
Did you pop the DB version so onUpgrade fires? You're at version 2 in the example above but if you changed the schema since version 2 then you need to pop the version again.
i think you are not mention your provider tag in AndroidManifest.xml .Check it.
u have to mention the tag like
<provider android:name=".name of providerclass"
android:authorities="authority path" />

Resources