To get a Java SHA256 hash I use the following method:
public String getSha256(String text, String encoding){
String sha = "";
try {
MessageDigest md = MessageDigest.getInstance("SHA-256");
md.update(text.getBytes(encoding));
byte[] digest = md.digest();
sha = new String(digest);
sha = sha.replace("\n", "");
} catch (NoSuchAlgorithmException | UnsupportedEncodingException ex) {
Logger.getLogger(Utils.class.getName()).log(Level.SEVERE, null, ex);
}
return sha;
}
Like so:
String testValue = getSha256("test", "UTF-8");
Then to get the HEX value out of it I do the following:
public String getHexFromString(String text){
String hex = "";
try {
byte[] myBytes = text.getBytes("UTF-8");
hex = DatatypeConverter.printHexBinary(myBytes);
} catch (UnsupportedEncodingException ex) {
Logger.getLogger(Utils.class.getName()).log(Level.SEVERE, null, ex);
}
return hex;
}
System.out.print(getHexFromString(testValue));
The result of this is:
C5B8E280A0C390EFBFBDCB864C7D65C5A12FC3AAC2A0C3855AC39015C2A3C2BF4F1B2B0BE2809A2CC3915D6C15C2B0C3B008
In javascript I do the following (using this library):
var hash = sjcl.hash.sha256.hash("test");
console.log(sjcl.codec.hex.fromBits(hash));
And the result is:
9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08
How can I get same hex in Java and Javascript?
What am I doing wrong, is it the Java or Javascript code?
#JonSkeet was right, changed the method, it now looks like this:
public String getSha256Hex(String text, String encoding){
String shaHex = "";
try {
MessageDigest md = MessageDigest.getInstance("SHA-256");
md.update(text.getBytes(encoding));
byte[] digest = md.digest();
shaHex = DatatypeConverter.printHexBinary(digest);
} catch (NoSuchAlgorithmException | UnsupportedEncodingException ex) {
Logger.getLogger(Utils.class.getName()).log(Level.SEVERE, null, ex);
}
return shaHex;
}
And the result is:
9F86D081884C7D659A2FEAA0C55AD015A3BF4F1B2B0B822CD15D6C15B0F00A08
The only difference is that the Java hex is upper case, but thats a minor thing to solve.
Related
I am trying to decrypt the string in JavaScript which is encrypted by using AES 256 algorithm in a C# application. The code of encryption and decryption is as below
I am able to decrypt the string in a C# application. I used the below code to decrypt the string JavaScript but I am not able to decrypt
public string Encrypt(string content)
{
if (string.IsNullOrEmpty(content))
{
throw new ArgumentNullException("content");
}
byte[] encryptedData = null;
try
{
using (AesCryptoServiceProvider aesMod = new AesCryptoServiceProvider())
{
//Set the key manullay to predefined values
aesMod.Key = m_Key;
aesMod.IV = m_IV;
ICryptoTransform encryptor = aesMod.CreateEncryptor(aesMod.Key, aesMod.IV);
// Create the streams used for encryption.
using (MemoryStream memstreamEncrypt = new MemoryStream())
{
using (CryptoStream csEncrypt = new CryptoStream(memstreamEncrypt, encryptor, CryptoStreamMode.Write))
{
using (StreamWriter swEncrypt = new StreamWriter(csEncrypt))
{
//Writing data to the stream.
swEncrypt.Write(content);
}
encryptedData = memstreamEncrypt.ToArray();
}
}
}
return Convert.ToBase64String(encryptedData);
}
catch (Exception ex)
{
throw new Exception("Exception in Encrypting .", ex);
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/crypto-js/3.1.2/rollups/aes.js"></script>
<script>
function decryptMessage(encryptedMessage = '', secretkey = ''){
var cipherParams = CryptoJS.lib.CipherParams.create({
ciphertext: CryptoJS.enc.Base64.parse(encryptedMessage)
});
var decrypted = CryptoJS.AES.decrypt(cipherParams, secretkey);
var decryptedMessage = decrypted.toString(CryptoJS.enc.Utf8);
return decryptedMessage;
}
</script>
The problem could be that the strings in C# are encoded in UTF-16
Try to change the encoding in the JavaScript code, if possible.
I am currently working on a project in which I want to send an image as ByteArray to a mosquitto broker with java to the topic images.
The subscriber of these Topic is a JavaScript application, which should convert the ByteArray,made in Java, back to an Image.
The reception of the image is working well, but the image cannot be shown correctly.
What I got so far:
Java Code to Publish an Image
public void doDemo(){
try {
client = new MqttClient("tcp://192.168.56.1", "Camera1", new MemoryPersistence());
MqttConnectOptions connOpts = new MqttConnectOptions();
connOpts.setCleanSession(true);
client.connect(connOpts);
MqttMessage message = new MqttMessage();
File imgPath = new File(Reciver.class.getResource("Card_1007330_bg_low_quality_000.png").getPath());
BufferedImage bufferedImage = ImageIO.read(imgPath);
// get DataBufferBytes from Raster
WritableRaster raster = bufferedImage .getRaster();
DataBufferByte data = (DataBufferByte) raster.getDataBuffer();
message.setPayload(data.getData());
client.publish("spengergasse/building-b/2.14/images", message);
} catch (MqttPersistenceException e) {
e.printStackTrace();
} catch (MqttSecurityException e) {
e.printStackTrace();
} catch (MqttException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally {
try {
client.disconnect();
} catch (MqttException e) {
e.printStackTrace();
}
}
}
JavaScript to show the image
function onMessageArrived(r_message){
console.log(r_message);
document.getElementById("ItemPreview").src = "data:image/png;base64," + convert(r_message.payloadBytes);
}
function convert(buffer) {
var binary = '';
var bytes = new Uint8Array(buffer);
var len = bytes.byteLength;
for (var i = 0; i < len; i++) {
binary += String.fromCharCode(bytes[i]);
}
return window.btoa(binary);
}
After Reciving the Image I am gettin this:
Maybe someone could help me out.
Thanks a lot :D
Give this a try:
function convert(buffer) {
var decoder = new TextDecoder('utf8');
return btoa(decoder.decode(buffer));
}
I think the best approach here is to use blobs. Instead of converting the array to base64 which is terribly slow an error prone if not done correctly, you create a blob from the input array and assign it to the .src property like this:
var blob = new Blob([r_message.payloadBytes], {type: 'image/png'});
document.getElementById("ItemPreview").src = URL.createObjectURL(blob);
I am passing JSON string to JavaScript code which contains {"imagePath":"a.svg"} Now instead of passing the path I want to send the image as string(some byte code maybe). I will be parsing this string in JavaScript and writing this as image to document.
Convert svg string to base64 and add base64 string to json as property.
Look at example: https://jsfiddle.net/wLftvees/1/
var decodedJson = {
img:
"PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0idXRmLTgiPz4NCjwhLS0gR2VuZXJhdG9yOiBB"+
"ZG9iZSBJbGx1c3RyYXRvciAxNS4xLjAsIFNWRyBFeHBvcnQgUGx1Zy1JbiAuIFNWRyBWZXJzaW9u"+
...
"NSw4LjU5NS0wLjA5NSwxMC42ODIsMS45MDMiLz4NCjwvc3ZnPg0K"
};
document.getElementById('image').src = 'data:image/svg+xml;base64,' + decodedJson.img;
First: Convert your image to String
public static String encodeToString(BufferedImage image, String type) {
String imageString = null;
ByteArrayOutputStream bos = new ByteArrayOutputStream();
try {
ImageIO.write(image, type, bos);
byte[] imageBytes = bos.toByteArray();
BASE64Encoder encoder = new BASE64Encoder();
imageString = encoder.encode(imageBytes);
bos.close();
} catch (IOException e) {
e.printStackTrace();
}
return imageString;
}
Second: Convert String to image
public static BufferedImage decodeToImage(String imageString) {
BufferedImage image = null;
byte[] imageByte;
try {
BASE64Decoder decoder = new BASE64Decoder();
imageByte = decoder.decodeBuffer(imageString);
ByteArrayInputStream bis = new ByteArrayInputStream(imageByte);
image = ImageIO.read(bis);
bis.close();
} catch (Exception e) {
e.printStackTrace();
}
return image;
}
Now you can use 2 function and switch to Javascript to get Image. ^^
I want to send image from one device to another so i have created that thing through node.js. i have converted the image into base64 and then into string and then send it to node.js server and decoded that string into another device and everythig works perfect. I have used socket.io. Now the problem arises as i have received the string as json response from node.js the full response is not getting half of response is being trimmed somewhere. So basically i am not getting full JSONRESPONSE. Here is my node.js code.
onLine[data.to].emit('newPrivateMessage1',{from:name, img:data.img.toString('base64'), type:'Private Msg1'})
And here is my first device from where i am sending image.
JSONObject json1 = new JSONObject();
String filepath = Environment.getExternalStorageDirectory().toString()+"/1.png";
File file = new File(filepath);
String itemname = getIntent().getStringExtra("itemname");
try {
#SuppressWarnings("resource")
FileInputStream imageInFile = new FileInputStream(file);
byte imageData[] = new byte[(int) file.length()];
Log.e("TAG", "IMAGEFATABYTE:::" + imageData);
imageInFile.read(imageData);
String imageDataString = android.util.Base64.encodeToString(imageData, 0);
json1.put("img", imageDataString);
json1.put("to", itemname);
Log.e("TAG", "MESSAGE:::" + json1);
socket.emit("privateMessage1", json1);
} catch (FileNotFoundException e1) {
e1.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Here is my second device to get response from json
String josn = getIntent().getStringExtra("pvtjson");
Log.e("TAG5", "IMAGEJSON" + josn);
try {
JSONObject jobj = new JSONObject(josn);
jobj.get("img");
byte[] decodedString = Base64.decode(jobj.get("img").toString(), Base64.DEFAULT);
Bitmap decodedByte = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length);
iv.setImageBitmap(decodedByte);
} catch (JSONException e) {
e.printStackTrace();
}
In my JSP, I have a button named "Download Zip file". When I click the button, I want to fetch data from the database and write it into a JS file and keep it inside a folder and download folder in ZIP format. I am using struts2.
How can I do this?
One way is to serve binary data from a servlet. Something like this:
byte[] zipFileBytes = ...;// generate the zip file and get the bytes
response.setContentType("application/octet-stream");
response.getOutputStream().write(zipFileBytes );
Then use a standard anchor element to download the file:
<a src="url to your servlet">download the file</a>
You might need to play with this a little bit to match your exact use case.
Try this : code to download file as a Zip
ServletOutputStream servletOS = null;
String zipFileName = null;
try {
servletOS = response.getOutputStream();
final ResourceResolver resolver = request.getResourceResolver();
zipFileName = FileDownloadHelper.getDownloadZipFileName();
response.setContentType("application/zip");
response.addHeader("Content-Disposition", "attachment; filename=" + zipFileName);
servletOS.write(FileDownloadHelper.prepareZipDownloadOutputStream(servletOS, documentUrls));
} finally {
if (servletOS != null) {
servletOS.flush();
servletOS.close();
}
}
public static byte[] prepareZipDownloadOutputStream(final ServletOutputStream outputStream,
final List<String> docUrls) throws IOException {
final byte[] buf = new byte[2048];
String fileName;
ZipOutputStream zipOutputStream = null;
InputStream isInputStream = null;
try {
zipOutputStream = new ZipOutputStream(outputStream);
for (final String docUrl : docUrls) {
LOGGER.info("Reading file from DAM : " + docUrl);
// read this file as input stream
isInputStream = new FileInputStream(docUrl);
if (isInputStream != null) {
fileName = getFileNameFromDocumentUrl(docUrl);
// Add ZIP entry to output stream.
zipOutputStream.putNextEntry(new ZipEntry(fileName));
int bytesRead;
while ((bytesRead = isInputStream.read(buf)) != -1) {
zipOutputStream.write(buf, 0, bytesRead);
}
zipOutputStream.closeEntry();
} e
}
} finally {
if (zipOutputStream != null) {
zipOutputStream.flush();
zipOutputStream.close();
}
if (isInputStream != null) {
isInputStream.close();
}
}
LOGGER.info("Returning buffer to be written to response output stream");
return buf;
}
public static String getFileNameFromDocumentUrl(final String docUrl) {
return docUrl
.substring(docUrl.lastIndexOf("/") + 1, docUrl.length());
}