Kleopatra: Decryption failed: invalid data - javascript

For encrypting files I use PKCS # 7 and the Javascript bundle forge.pki.
var forge = require('node-forge');
var contentBuffer = forge.util.createBuffer( forge.util.decode64( "fasdasd asdasdasda" ));
var cert = forge.pki.certificateFromPem(certPem);
var p7 = forge.pkcs7.createEnvelopedData();
p7.addRecipient(cert);
p7.content = contentBuffer;
console.log("Encrypt...");
p7.encrypt();
var asn1Cert = p7.toAsn1();
var derBuffer = forge.asn1.toDer(asn1Cert);
var p7mContent = derBuffer.toHex();
console.log(p7mContent);
I copy the hex value into my Java class as a string constant. Java saves then converts this into a .p7m file and stores it locally for me.
public void writeDocumentContent(String filename) throws Exception {
byte[] encryptedMessage = getP7MBytes(hex);
InputStream inputStream = new ByteArrayInputStream(encryptedMessage);
handleTransfer(inputStream, TransferKanal.HTML5);
}
private static byte[] getP7MBytes(String p7m) {
int len = p7m.length();
byte[] data = new byte[len / 2];
for (int i = 0; i < len; i += 2) {
data[i / 2] = (byte) ((Character.digit(p7m.charAt(i), 16) << 4) + Character.digit(p7m.charAt(i + 1), 16));
}
return data;
}
private void handleTransfer(InputStream inputStream, TransferKanal kanal) throws Exception {
String path = "C:TEMP/padline";
createDirectory(path);
String filename = "example." + kanal.getFileExtension();
File targetFile = new File(path, filename);
provideTransferData(inputStream, targetFile);
}
private void provideTransferData(InputStream inputStream, File targetFile) throws Exception {
try (InputStream bInputStream = new BufferedInputStream(inputStream, 20 * 8192)) {
provide(bInputStream, targetFile);
} catch (IOException e) {
throw new Exception("error while reading/writing transfer data", e);
}
}
private boolean createDirectory(String directory) {
File file = new File(directory);
if (!file.exists()) {
file.mkdirs();
return true;
}
return false;
}
private void provide(InputStream is, File finalFile) throws Exception {
try {
File destFile = new File(finalFile.getAbsolutePath());
FileOutputStream buffer = null;
try {
buffer = new FileOutputStream(destFile);
int nRead;
byte[] buf = new byte[2 * 16384];
while ((nRead = is.read(buf, 0, buf.length)) != -1) {
buffer.write(buf, 0, nRead);
}
} catch (Exception e) {
throw new Exception("provision location corrupted", e);
} finally {
if (buffer != null) {
buffer.close();
}
}
} catch (IOException e) {
throw new Exception("error copying file", e);
}
}
Before, I create a bundle of the certificate and the private key via openSSL with following command:
openssl pkcs12 -export -inkey private.key -in public.cert -out certificate.pfx
and imported it into Kleopatra as a .pfx file. Then I have the generated (encrypted) p7m file to decrypt in Cleopatra and pushed the following error message:
Decryption failed: invalid data

Related

cant decode a message from a Websocket

I`m trying to connect my HTML/JS client to my C# server as a part of a university project in order to allow the user real-time notification. (I just need the server to be able to send a specific user a message at any given time)
My server Is just a mock in order to implement it in my project.
I Successfully passed the handshake stage and I am trying to send a plain string from the server to the client. I read something about Encoding the message is a way that the client will not give the "One or more reserved bits are on: reserved1 = 0, reserved2 = 1, reserved3 = 1" error but without success.
How can I send primitive data through the Sockets and decode them on the client?
My server code:
while (true)
{
TcpListener sck = new TcpListener(IPAddress.Any, 7878);
sck.Start(1000);
TcpClient client = sck.AcceptTcpClient();
NetworkStream _stream = client.GetStream();
StreamReader clientStreamReader = new StreamReader(_stream);
StreamWriter clientStreamWriter = new StreamWriter(_stream);
while (true)
{
while (!_stream.DataAvailable) ;
Byte[] bytes = new Byte[client.Available];
_stream.Read(bytes, 0, bytes.Count());
String data = Encoding.UTF8.GetString(bytes);
if (Regex.IsMatch(data, "^GET"))
{
const string eol = "\r\n"; // HTTP/1.1 defines the sequence CR LF as the end-of-line marker
Byte[] response = Encoding.UTF8.GetBytes("HTTP/1.1 101 Switching Protocols" + eol
+ "Connection: Upgrade" + eol
+ "Upgrade: websocket" + eol
+ "Sec-WebSocket-Accept: " + Convert.ToBase64String(
System.Security.Cryptography.SHA1.Create().ComputeHash(
Encoding.UTF8.GetBytes(
new System.Text.RegularExpressions.Regex("Sec-WebSocket-Key: (.*)").Match(data).Groups[1].Value.Trim() + "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"
)
)
) + eol
+ eol);
_stream.Write(response, 0, response.Length);
}
else
{
}
}
}
My Client Code:
<script type="text/javascript">
function WebSocketTest() {
if ("WebSocket" in window) {
alert("WebSocket is supported by your Browser!");
// Let us open a web socket
var ws = new WebSocket("ws://localhost:7878");
ws.onopen = function () {
// Web Socket is connected, send data using send()
ws.send("Message to send");
alert("Message is sent...");
};
ws.onmessage = function (evt) {
var received_msg = evt.data;
alert("Message is received...");
};
ws.onclose = function () {
// websocket is closed.
alert("Connection is closed...");
};
} else {
// The browser doesn't support WebSocket
alert("WebSocket NOT supported by your Browser!");
}
}
</script>
I kept my server as above but added a send string function, and a decode message function:
public static string DecodeMessage(Byte[] bytes)
{
string incomingData = string.Empty;
byte secondByte = bytes[1];
int dataLength = secondByte & 127;
int indexFirstMask = 2;
if (dataLength == 126)
indexFirstMask = 4;
else if (dataLength == 127)
indexFirstMask = 10;
IEnumerable<byte> keys = bytes.Skip(indexFirstMask).Take(4);
int indexFirstDataByte = indexFirstMask + 4;
byte[] decoded = new byte[bytes.Length - indexFirstDataByte];
for (int i = indexFirstDataByte, j = 0; i < bytes.Length; i++, j++)
{
decoded[j] = (byte)(bytes[i] ^ keys.ElementAt(j % 4));
}
return Encoding.UTF8.GetString(decoded, 0, decoded.Length);
}
public static void SendString(string userName ,string str)
{
if (!userConnections.ContainsKey(userName))
return;
TcpClient client = userConnections[userName];
NetworkStream _stream = client.GetStream();
try
{
var buf = Encoding.UTF8.GetBytes(str);
int frameSize = 64;
var parts = buf.Select((b, i) => new { b, i })
.GroupBy(x => x.i / (frameSize - 1))
.Select(x => x.Select(y => y.b).ToArray())
.ToList();
for (int i = 0; i < parts.Count; i++)
{
byte cmd = 0;
if (i == 0) cmd |= 1;
if (i == parts.Count - 1) cmd |= 0x80;
_stream.WriteByte(cmd);
_stream.WriteByte((byte)parts[i].Length);
_stream.Write(parts[i], 0, parts[i].Length);
}
_stream.Flush();
}
catch (Exception ex)
{
Console.WriteLine("Error");
}
}
Where userConnections is: public static Dictionary userConnections = new Dictionary();
in order to maintain user - connection relation
You can use SuperWebSocket, this library sends the handshake automatically.
Server:
using SuperSocket.SocketBase;
using SuperWebSocket;
using System;
using System.Net;
using System.Net.Sockets;
namespace Jees.Library.WebSocket
{
public class WebSocket
{
WebSocketServer appServer;
public event EventHandler ServerStarted;
public event EventHandler ServerStopped;
public event EventHandler MessageReceived;
public string IP { get; } = string.Empty;
public int Port { get; } = 1337; //change this to the port you want to use
public WebSocket() => this.IP = GetLocalIPAddress(); //or set it manually
public void Start()
{
appServer = new WebSocketServer();
if (!appServer.Setup(this.IP, this.Port))
{
this.OnServerStarted(new WebSocketServerEventArgs(false));
return;
}
/* start listening */
appServer.NewMessageReceived += new SessionHandler<WebSocketSession, string>(AppServer_NewMessageReceived);
if (appServer.Start())
this.OnServerStarted(new WebSocketServerEventArgs(true));
else
{
this.OnServerStarted(new WebSocketServerEventArgs(false));
appServer = null;
appServer.Dispose();
}
}
public void Stop()
{
if (appServer != null)
{
appServer.Stop();
this.OnServerStopped(new EventArgs());
appServer = null;
appServer.Dispose();
}
}
private void AppServer_NewMessageReceived(WebSocketSession session, string message)
{
this.OnMessageReceived(new MessageReceivedEventArgs(message, session));
}
protected virtual void OnMessageReceived(EventArgs e) => this.MessageReceived?.Invoke(this, e);
protected virtual void OnServerStarted(EventArgs e) => this.ServerStarted?.Invoke(this, e);
protected virtual void OnServerStopped(EventArgs e) => this.ServerStopped?.Invoke(this, e);
private string GetLocalIPAddress()
{
var host = Dns.GetHostEntry(Dns.GetHostName());
foreach (var ip in host.AddressList)
if (ip.AddressFamily == AddressFamily.InterNetwork)
return ip.ToString();
throw new Exception("No network adapters with an IPv4 address in the system!");
}
}
public class WebSocketServerEventArgs : EventArgs
{
public WebSocketServerEventArgs(bool success) => this.Success = success;
public bool Success { get; }
}
public class MessageReceivedEventArgs : EventArgs
{
public MessageReceivedEventArgs(string message, WebSocketSession session)
{
this.Message = message;
this.Session = session;
}
public string Message { get; }
public WebSocketSession Session { get; }
}
}
Server Setup (I use a UserControl):
using DevExpress.XtraEditors;
using SuperWebSocket;
using System;
using System.Linq;
using System.Windows.Forms;
namespace WebSocketServer
{
public partial class Server : UserControl
{
WebSocket server;
WebSocketSession session;
public Server()
{
InitializeComponent();
server = new WebSocket();
server.ServerStarted += Server_ServerStarted;
server.ServerStopped += Server_ServerStopped;
server.MessageReceived += Server_MessageReceived;
}
private void Server_MessageReceived(object sender, EventArgs e)
{
MessageReceivedEventArgs eventArgs = (MessageReceivedEventArgs)e;
/* save session */
this.session = eventArgs.Session;
this.Log("SessionID: " + session.RemoteEndPoint.ToString() + "; Message: " + eventArgs.Message);
/* send back the message to the client */
this.session.Send(eventArgs.Message); //comment out if needed
}
private void Server_ServerStopped(object sender, EventArgs e)
{
this.Log("Server stopped!");
}
private void Server_ServerStarted(object sender, EventArgs e)
{
if ((e as WebSocketServerEventArgs).Success)
{
this.Log("Server started on ws://" + server.IP + ":" + server.Port + "/");
}
else
this.Log("Can't start the server!");
}
private void Log(string message)
{
/* here, this.log is a TextBox */
if (this.log.InvokeRequired)
this.log.Invoke((MethodInvoker)delegate
{
this.log.Text += DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss") + " > " + message + Environment.NewLine;
});
else
{
this.log.Text += DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss") + " > " + message + Environment.NewLine;
}
}
/* a button to start the server */
private void BtnStart_Click(object sender, EventArgs e) => server.Start();
/* a button to stop the server */
private void BtnStop_Click(object sender, EventArgs e) => server.Stop();
/* a button to send a message from a TextBox to the client */
private void BtnSend_Click(object sender, EventArgs e)
{
if (this.txtMessage.Text != string.Empty)
this.SendMessage(this.txtMessage.Text);
}
private void SendMessage(string message)
{
try
{
/* use current session to send the message */
this.session.Send(message);
this.Log("Message: " + message + " sent to client!");
}
catch (Exception e)
{
this.Log(e.Message);
}
}
}
}
If you need more clarification, add a comment and I'll update my answer!

I want to print to pdf file in javascript, where outputstream and pdfwriter

I am trying to create a PDF from a server-side controller (report) (ireport) with ajax (and so on), and try to return the data to pdfwriter, servletoutputstream, and httpservletresponse. (I do not know exactly what I'm doing, but I'm doing it this way).
The original purpose was to send a server-side pdf file to the client, find the printer and print without a preview window.
Among them, I wrote 'application / pdf' on the server side and 'datetype: text' on the client side ajax (there is an error if I do not use ajax datatype: text)
If you print the results to the console, they will only be listed as unknown code.
Currently I am trying to put it into an iframe frame.
Question!
1. What should I do to use the text string sent to server -> client as pdf or script code?
(I have already asked you two weeks ago)
2. How do I send a pdf to server -> client? I would like to apply it to the screen by expressing it directly in code instead of downloading it. To print out.
ENG)>
// I used ajax only, because I dont know any other way
$.ajax({
url : "url",
data : JSON.stringify(data),
dataType : "text",
type: "POST",
contentType: 'application/json; charset=utf-8',
async : false,
success: function(result){
// I want to view PDF contents and directly print to PDF.
}
})
public Params createIbExItemLabelReport(HttpServletRequest resq, HttpSession session, Params inParams, HttpServletResponse resp) throws Exception{
Params outParams = ParamsFactory.createParams(inParams);
resp.setHeader("Cache-Control", "no-cache");
resp.setHeader("Pragma", "no-cache");
resp.setHeader("Expires", "0");
List<DataRow> list = new ArrayList<DataRow>();
String reportCd = "15";
String fileName = "ibExItemLabel"+reportCd+"Report";
String nullJpgFile = "";
int flag = 0;
int nullCheck = 0;
for(DataRow dr : inParams.getDataTable("dt_data")){
String imgName = "c:\\WMS\\LABEL\\FIAC021_" +reportCd + ".jpg";
File f = new File(imgName);
if (!f.isFile()) {
flag = 1;
if(nullCheck != 0){
nullJpgFile += ", ";
}
nullJpgFile += "FIAC021";
nullCheck++;
continue;
}
String bacodeCd = "FIAC02120180416001";
dr.setParam("imgName", imgName);
dr.setParam("bacodeCd", bacodeCd);
list.add(dr);
}
if(flag == 1){
outParams.setParam("ERROR_FILE", "제품코드 ["+nullJpgFile+"]의 라벨 사이즈" + reportCd + "인 파일이 존재하지않습니다.");
return outParams;
}
String appPath = session.getServletContext().getRealPath("/");
String pdfPath = null;
List<DataRow> list2 = new ArrayList<DataRow>();
for(int i = 0; i < list.size(); i++){
for(int j = 0; j < list.get(i).getInt("printQty"); j++){
list2.add(list.get(i));
}
}
Report report = new Report();
pdfPath = report.reportToPdf(session, list2, fileName);
outParams.setParam("fileName", pdfPath);
System.out.println("Found! FileName is ' : "+ pdfPath);
pdfPath = appPath + pdfPath;
pdfPath = pdfPath.replace("//", "/");
ServletOutputStream servletOutput = resp.getOutputStream();
PdfWriter pdfWriter = null;
StringBuffer pdfJs = null;
ByteArrayOutputStream pdfOutput = null;
InputStream pdfInput = null;
PdfReader pdfReader = null;
PdfStamper pdfStamper = null;
pdfOutput = convertPDFToByteArrayOutputStream(pdfPath);
int printCopy = 1;
if (printCopy == 0) {
printCopy = 1;
}
if (printCopy > 1) {
PdfCopyFields pdfPrintCopy = new PdfCopyFields(pdfOutput);
for (int i = 0; i < printCopy; i++) {
pdfPrintCopy.addDocument(new PdfReader(outputToInputStream(pdfOutput)));
}
pdfPrintCopy.close();
}
pdfInput = outputToInputStream(pdfOutput);
pdfReader = new PdfReader(pdfInput);
pdfStamper = new PdfStamper(pdfReader, servletOutput);
pdfWriter = pdfStamper.getWriter();
String printerNm = "SINDOH D410 Series PCL";
pdfWriter.setViewerPreferences(PdfWriter.HideMenubar | PdfWriter.HideToolbar | PdfWriter.HideWindowUI);
pdfJs = new StringBuffer();
pdfJs.append("var param=this.getPrintParams();\r");
pdfJs.append("param.printerName=\"").append(printerNm).append("\";\r");
pdfJs.append("param.interactive=param.constants.interactionLevel.silent;\r");
pdfJs.append("param.pageHandling=param.constants.handling.shrink;\r");
pdfJs.append("this.print(param);\r");
pdfJs.append("this.closeDoc();");
pdfWriter.addJavaScript(pdfJs.toString(), false);
servletOutput.flush();
Log.debug("servletOutput " );
if (pdfInput != null) {
try {
pdfInput.close();
} catch (Exception e) {
}
pdfInput = null;
}
if (pdfOutput != null) {
try {
pdfOutput.close();
} catch (Exception e) {
}
pdfOutput = null;
}
if (pdfReader != null) {
pdfReader.close();
pdfReader = null;
}
pdfWriter = null;
try {
if (pdfStamper != null) {
pdfStamper.close();
pdfStamper = null;
}
} catch (Exception e) {
}
resp.setHeader("Content-Disposition", "inline; filename="+pdfPath);
resp.setHeader("Content-Type", "application/pdf; charset=UTF-8");
resp.setCharacterEncoding("UTF-8");
Log.debug("before outParams " );
return outParams;
}
private InputStream outputToInputStream(ByteArrayOutputStream source) {
return new ByteArrayInputStream(source.toByteArray());
}
private static ByteArrayOutputStream convertPDFToByteArrayOutputStream(String FilePath) {
InputStream inputStream = null;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try {
inputStream = new FileInputStream(new File(FilePath));
byte[] buffer = new byte[1024];
baos = new ByteArrayOutputStream();
int bytesRead;
while ((bytesRead = inputStream.read(buffer)) != -1) {
baos.write(buffer, 0, bytesRead);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return baos;
}
please answer my question

Encoding in JavaScript

I'm very new in programming with Javascript and stuck in encoding my data.
I have done this as per need in my Android App, but could not able to do the same in JavaScript for my web portal.
The code which I'm using in Android App:
public void encryptdata(byte[] data) {
Encrypter encrypter = new Encrypter();
HashGenerator hashGenerator = new HashGenerator();
try {
byte[] e = encrypter.generateSessionKey();
byte[] encryptedData = encrypter.encryptUsingSessionKey(e, data);
byte[] hmac = hashGenerator.generateSha256Hash(data);
byte[] encryptedHmacBytes = encrypter.encryptUsingSessionKey(e, hmac);
this.encodedSessionKey = encodeBase64(e);
this.encodedHmac = encodeBase64(encryptedHmacBytes);
this.encodedData = encodeBase64(encryptedData);
} catch (Exception var6) {
var6.printStackTrace();
throw new RuntimeException(var6);
}
}
Encrypter.java
class Encrypter {
private static final String JCE_PROVIDER = "BC";
private static final int SYMMETRIC_KEY_SIZE = 256;
Encrypter() {
}
public byte[] generateSessionKey() throws NoSuchAlgorithmException, NoSuchProviderException {
KeyGenerator kgen = KeyGenerator.getInstance("AES", "BC");
kgen.init(256);
SecretKey key = kgen.generateKey();
byte[] symmKey = key.getEncoded();
return symmKey;
}
public byte[] encryptUsingSessionKey(byte[] skey, byte[] data) throws InvalidCipherTextException {
PaddedBufferedBlockCipher cipher = new PaddedBufferedBlockCipher(new AESEngine(), new PKCS7Padding());
cipher.init(true, new KeyParameter(skey));
int outputSize = cipher.getOutputSize(data.length);
byte[] tempOP = new byte[outputSize];
int processLen = cipher.processBytes(data, 0, data.length, tempOP, 0);
int outputLen = cipher.doFinal(tempOP, processLen);
byte[] result = new byte[processLen + outputLen];
System.arraycopy(tempOP, 0, result, 0, result.length);
return result;
}
static {
Security.addProvider(new BouncyCastleProvider());
}
}
HashGenerator.java
class HashGenerator {
public HashGenerator() {
}
public byte[] generateSha256Hash(byte[] message) {
String var2 = "SHA-256";
String var3 = "BC";
byte[] var4 = null;
try {
MessageDigest var7 = MessageDigest.getInstance(var2, var3);
var7.reset();
var4 = var7.digest(message);
} catch (Exception var6) {
var6.printStackTrace();
}
return var4;
}
}
These piece of code encoding the data and giving me HMAC as per my need, but I am not able to do same with JavaScript.
Can anyone give any reference or code on for JavaScript client.
Any help will be appreciated.
Thanks for down-voting the question, may be a not great question, but here I done it myself
this.doEncryption = function (data) {
var key = btoa(this.generateRandomString());
var Encryptionkey = CryptoJS.enc.Base64.parse(key);
var encryptedPid = CryptoJS.AES.encrypt(data,Encryptionkey,{ mode: CryptoJS.mode.ECB, padding: CryptoJS.pad.Pkcs7});
var sha256 = CryptoJS.SHA256(data);
var encryptedHmac = CryptoJS.AES.encrypt(sha256,Encryptionkey,{ mode: CryptoJS.mode.ECB, padding: CryptoJS.pad.Pkcs7});
return {
encryptionKey : key,
encryptedPid : encryptedPid.toString(),
encryptedHmac : encryptedHmac.toString()
};

react-native AES Encryption matching Java Decryption algorithm

The Full code of my Java Encryption/Decryption algorithm:
public class AESEncryptUtil {
private static AESEncryptUtil instance = new AESEncryptUtil();
private String password = "123456";
private Key key;
private Cipher cipher;
public AESEncryptUtil(){
try {
KeyGenerator kgen = KeyGenerator.getInstance("AES");
kgen.init(128, new SecureRandom(password.getBytes()));
SecretKey secretKey = kgen.generateKey();
byte[] enCodeFormat = secretKey.getEncoded();
key = new SecretKeySpec(enCodeFormat, "AES");
cipher = Cipher.getInstance("AES");
} catch (Exception e) {
e.printStackTrace();
}
}
public static byte[] encrypt(String content) throws Exception {
byte[] byteContent = content.getBytes("utf-8");
instance.cipher.init(Cipher.ENCRYPT_MODE, instance.key);
byte[] result = instance.cipher.doFinal(byteContent);
return result;
}
public static byte[] decrypt(byte[] content) throws Exception {
instance.cipher.init(Cipher.DECRYPT_MODE, instance.key);
byte[] result = instance.cipher.doFinal(content);
return result;
}
public static String parseByte2HexStr(byte buf[]) {
StringBuffer sb = new StringBuffer();
for (int i = 0; i < buf.length; i++) {
String hex = Integer.toHexString(buf[i] & 0xFF);
if (hex.length() == 1) {
hex = '0' + hex;
}
sb.append(hex.toUpperCase());
}
return sb.toString();
}
public static byte[] parseHexStr2Byte(String hexStr) {
if (hexStr.length() < 1)
return null;
byte[] result = new byte[hexStr.length() / 2];
for (int i = 0; i < hexStr.length() / 2; i++) {
int high = Integer.parseInt(hexStr.substring(i * 2, i * 2 + 1), 16);
int low = Integer.parseInt(hexStr.substring(i * 2 + 1, i * 2 + 2),
16);
result[i] = (byte) (high * 16 + low);
}
return result;
}
public static String getNonce() {
String base = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
Random random = new Random();
StringBuffer sb = new StringBuffer();
for (int i = 0; i < 16; i++) {
int number = random.nextInt(base.length());
sb.append(base.charAt(number));
}
return sb.toString();
}
public static void main(String[] args) throws Exception {
String content = "test";
System.out.println("content: " + content);
byte[] encryptResult = encrypt(content);
String encryptResultStr = parseByte2HexStr(encryptResult);
System.out.println("encryptResultStr: " + encryptResultStr);
byte[] decryptFrom = parseHexStr2Byte(encryptResultStr);
byte[] decryptResult = decrypt(decryptFrom);
System.out.println("decryptResult: " + new String(decryptResult));
}
}
I've tried many times and many ways to match the Java algorithm, but the result are always different. Which module should I use to do this ? Can anyone help me to deal it ? Thanks a lot !
I found the right way to match two algorithm:
Java part:
public static String encrypt() throws Exception {
try {
String data = "123456";
String key = "1234567812345678";
String iv = "1234567812345678";
Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");
int blockSize = cipher.getBlockSize();
byte[] dataBytes = data.getBytes();
int plaintextLength = dataBytes.length;
if (plaintextLength % blockSize != 0) {
plaintextLength = plaintextLength + (blockSize - (plaintextLength % blockSize));
}
byte[] plaintext = new byte[plaintextLength];
System.arraycopy(dataBytes, 0, plaintext, 0, dataBytes.length);
SecretKeySpec keyspec = new SecretKeySpec(key.getBytes(), "AES");
IvParameterSpec ivspec = new IvParameterSpec(iv.getBytes());
cipher.init(Cipher.ENCRYPT_MODE, keyspec, ivspec);
byte[] encrypted = cipher.doFinal(plaintext);
return new sun.misc.BASE64Encoder().encode(encrypted);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
public static String desEncrypt() throws Exception {
String encrypted = encrypt() ;
try
{
String data = encrypted ;
String key = "1234567812345678";
String iv = "1234567812345678";
byte[] encrypted1 = new BASE64Decoder().decodeBuffer(data);
Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");
SecretKeySpec keyspec = new SecretKeySpec(key.getBytes(), "AES");
IvParameterSpec ivspec = new IvParameterSpec(iv.getBytes());
cipher.init(Cipher.DECRYPT_MODE, keyspec, ivspec);
byte[] original = cipher.doFinal(encrypted1);
String originalString = new String(original);
return originalString;
}
catch (Exception e) {
e.printStackTrace();
return null;
}
}
React native part:
pre coding: npm install crypto-js
import CryptoJS from 'crypto-js' ;
encryptFun() {
var data = "123456";
var key = CryptoJS.enc.Latin1.parse('1234567812345678');
var iv = CryptoJS.enc.Latin1.parse('1234567812345678');
var encrypted = CryptoJS.AES.encrypt(
data,
key,
{iv:iv,mode:CryptoJS.mode.CBC,padding:CryptoJS.pad.ZeroPadding
});
console.log('encrypted: ' + encrypted) ;
var decrypted = CryptoJS.AES.decrypt(encrypted,key,{iv:iv,padding:CryptoJS.pad.ZeroPadding});
console.log('decrypted: '+decrypted.toString(CryptoJS.enc.Utf8));
}
the result :
encrypted: aK7+UX24ttBgfTnAndz9aQ==
decrypted: 123456
I hope my code would help someone:)

crypto-js - read and decrypt file

I have some Java functions for doing AES encryption, one for a string, and one for a file
private static final String AES_CIPHER_METHOD = "AES";
public static SecretKeySpec createAesKeySpec(byte[] aesKey) {
return new SecretKeySpec(aesKey, AES_CIPHER_METHOD);
}
public static String aesEncrypt(String data, SecretKeySpec aesKeySpec) throws EncryptionException {
try {
Cipher aesCipher = Cipher.getInstance(AES_CIPHER_METHOD);
aesCipher.init(Cipher.ENCRYPT_MODE, aesKeySpec);
byte[] encVal = aesCipher.doFinal(data.getBytes("UTF8"));
return new BASE64Encoder().encode(encVal);
} catch (NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException | IOException | BadPaddingException| IllegalBlockSizeException e) {
throw new EncryptionException(e.getMessage(), e);
}
}
public static void aesEncryptFile(File in, File out, SecretKeySpec aesKeySpec) throws EncryptionException {
try {
Cipher aesCipher = Cipher.getInstance(AES_CIPHER_METHOD);
aesCipher.init(Cipher.ENCRYPT_MODE, aesKeySpec);
try (InputStream inputStream = new FileInputStream(in)) {
try (OutputStream outputStream = new CipherOutputStream(new FileOutputStream(out), aesCipher)){
IOUtils.copy(inputStream, outputStream);
}
}
} catch (InvalidKeyException | NoSuchAlgorithmException | NoSuchPaddingException | IOException e){
throw new EncryptionException(e.getMessage(), e);
}
}
I also have some tests to output some test data
private static final String KEY_STRING = "DpiA4l0gvb7biWZtiN6Vjg==";
private SecretKeySpec createKeySpec() {
byte[] keyBytes = new Base64().decode(KEY_STRING.getBytes());
return EncryptionUtils.createAesKeySpec(keyBytes);
}
public void testAesEncryptString() throws EncryptionException {
String encryptedData = EncryptionUtils.aesEncrypt("A normal string", createKeySpec());
System.out.println(encryptedData); //outputs 3XLwlSHWLm98teIoIS6QTA==
}
public void testAesEncryptStringFile() throws EncryptionException, IOException {
File newFile = new File(FilenameUtils.concat(System.getProperty("java.io.tmpdir"), "myFile.txt"));
FileUtils.writeStringToFile(newFile, "A string in a file");
File encryptedFile = new File(FilenameUtils.concat(System.getProperty("java.io.tmpdir"), "myFile_encrypted.txt"));
EncryptionUtils.aesEncryptFile(newFile, encryptedFile, createKeySpec());
}
I now need to implement decryption in javascript.
I have managed to successfully decrypt the plain string using crypto-js, however, I just cant get the file part working, and I cant quite see what is wrong
var base64Key = "DpiA4l0gvb7biWZtiN6Vjg==";
var key = CryptoJS.enc.Base64.parse(base64Key);
var aesOptions = {
mode: CryptoJS.mode.ECB,
padding: CryptoJS.pad.Pkcs7
};
var decryptedData = CryptoJS.AES.decrypt( "3XLwlSHWLm98teIoIS6QTA==", key, aesOptions);
var decryptedText = decryptedData.toString( CryptoJS.enc.Utf8 );
console.log( "decryptedText = " + decryptedText ); //CORRECT outputs "A normal string"
var encryptedFilename = "https://dl.dropboxusercontent.com/u/30823828/myFile_encrypted.txt";
$.get(encryptedFilename, function(data){
console.log("encrypted file content", data);
var encryptedData = CryptoJS.enc.Base64.parse(data);
var decryptedData = CryptoJS.AES.decrypt( encryptedData, key, aesOptions);
var decryptedText = decryptedData.toString( CryptoJS.enc.Utf8 );
console.log( "decrypted file content = " + decryptedText ); //INCORRECT outputs "" SHOULD output "A string in a file"
});
link to jsfiddle - http://jsfiddle.net/pKNzV/46/
after a lot of trial and error, I was able to get this working.
the function base64ArrayBuffer comes from the following - https://gist.github.com/jonleighton/958841
var base64Key = "DpiA4l0gvb7biWZtiN6Vjg==";
var key = CryptoJS.enc.Base64.parse(base64Key);
var aesOptions = {
mode: CryptoJS.mode.ECB,
padding: CryptoJS.pad.Pkcs7
};
var encryptedFilename = "https://dl.dropboxusercontent.com/u/30823828/myFile_encrypted.txt";
var oReq = new XMLHttpRequest();
oReq.open("GET", encryptedFilename, true);
oReq.responseType = "arraybuffer";
oReq.onload = function (oEvent) {
var data = oReq.response;
if (data) {
encodedData = base64ArrayBuffer(data);
var decryptedData = CryptoJS.AES.decrypt( encodedData, key, aesOptions);
var decryptedText = decryptedData.toString( CryptoJS.enc.Utf8 );
console.log( "decryptedText = " + decryptedText );
console.log("file decrypt successful: ", "A string in a file" === decryptedText);
}
};
oReq.send(null);

Categories

Resources