I added a password checker for my program, I thought it works fine since I could save the password in a file (encoded) and could enter the password in the password field and it let me into the main program without problems. However, today I was testing more and I found out that some passwords do not work and I have no idea why that is the case.
I included both my methods, one does encode the password, the other one does decode it. The verify method I included is the one that reads from the password file, decodes the password and checks if the entered password equals the saved one. I couldnt find out what types of passwords do not work, its not the length, more like the characters which were used.
Thanks in advance
public static char[] encode(int offset, char[] charArray) {
char[] arrEnc = new char[charArray.length];
for (int i = 0; i < charArray.length; i++) {
int verschiebung = (charArray[i] + offset) % 128;
arrEnc[i] = (char) (verschiebung);
}
return arrEnc;
}
public static char[] decode(int offset, char[] charArray) {
char[] arrEnc = new char[charArray.length];
int verschiebung;
for (int i = 0; i < charArray.length; i++) {
if (charArray[i] - offset < 0) {
verschiebung = charArray[i] - offset + 128;
} else {
verschiebung = (charArray[i] - offset) % 128;
arrEnc[i] = (char) (verschiebung);
}
}
return arrEnc;
}
private void verify() {
try {
FileReader fr = new FileReader(pws);
BufferedReader br = new BufferedReader(fr);
char[] arr = br.readLine().toCharArray();
char[] newArr = decode(arr.length, arr);
String pw = new String(newArr);
String masterPw = "Kassa";
if (passwordField.getText().equals(pw) ||
passwordField.getText().equals(masterPw)) {
setVisible(false);
starto.setVisible(true);
br.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
Any password should be able to be saved and decoded
You have a mistake in the code.
if (charArray[i] - offset < 0) {
verschiebung = charArray[i] - offset + 128;
...
Here you forgot to put
arrEnc[i] = (char) (verschiebung);
So you should assign verschiebung to arrEnc[i] in the first condition block in the decode method.
everyone! I recently learned about variable byte encoding.
for example, if a file contains this sequence of number: 824 5 214577
applying variable byte encoding this sequence would be encoded as 000001101011100010000101000011010000110010110001.
Now I want to know how to write that in another file such that to produce a kind of compressed file from the original. and similarly how to read it. I'm using JAVA .
Have tried this:
LinkedList<Integer> numbers = new LinkedList<Integer>();
numbers.add(824);
numbers.add(5);
numbers.add(214577);
String code = VBEncoder.encodeToString(numbers);//returns 000001101011100010000101000011010000110010110001 into code
File file = new File("test.compressed");
DataOutputStream out = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(file)));
out.writeBytes(code);
out.flush();
this just writes the binary representation into the file..and this is not what I'm expecting.
I have also tried this:
LinkedList<Integer> code = VBEncoder.encode(numbers);//returns linked list of Byte(i give its describtion later)
File file = new File("test.compressed");
DataOutputStream out = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(file)));
for(Byte b:code){
out.write(b.toInt());
System.out.println(b.toInt());
}
out.flush();
// he goes the describtion of the class Byte
class Byte {
int[] abyte;
Byte() {
abyte = new int[8];
}
public void readInt(int n) {
String bin = Integer.toBinaryString(n);
for (int i = 0; i < (8 - bin.length()); i++) {
abyte[i] = 0;
}
for (int i = 0; i < bin.length(); i++) {
abyte[i + (8 - bin.length())] = bin.charAt(i) - 48;
}
}
public void switchFirst() {
abyte[0] = 1;
}
public int toInt() {
int res = 0;
for (int i = 0; i < 8; i++) {
res += abyte[i] * Math.pow(2, (7 - i));
}
return res;
}
public static Byte fromString(String codestring) {
Byte b = new Byte();
for(int i=0; i < 8; i++)
b.abyte[i] = (codestring.charAt(i)=='0')?0:1;
return b;
}
public String toString() {
String res = "";
for (int i = 0; i < 8; i++) {
res += abyte[i];
}
return res;
}
}
its prints this in the console:
6
184
133
13
12
177
this second attempt seems to work...the output file size is 6 bytes while for the first attemps it was 48 bytes.
but the problem in the second attempt is that I can't successfully read back the file.
InputStreamReader inStream = new InputStreamReader(new FileInputStream(file));
int c = -1;
while((c = inStream.read()) != -1){
System.out.println( c );
}
i get this:
6
184
8230
13
12
177
..so maybe I'm doing it the wrong way: expecting to receive some good advice from you. thanks!
It is solved; I was just not reading the file the right way:below is the right way:
DataInputStream inStream = null;
inStream = new DataInputStream(new BufferedInputStream(newFileInputStream(file)));
int c = -1;
while((c = inStream.read()) != -1){
Byte b = new Byte();
b.readInt(c);
System.out.println( c +":" + b.toString());
}
now I get this as the result:
6:00000110
184:10111000
133:10000101
13:00001101
12:00001100
177:10110001
Now the importance of writing the original sequence of integers into variable encoded bytes reduces the size of the file; if we normally write this sequence of integers in the file, its size would be 12 bytes (3 * 4 bytes). but now it is just 6 bytes.
int c = -1;
LinkedList<Byte> bytestream = new LinkedList<Byte>();
while((c = inStream.read()) != -1){
Byte b = new Byte();
b.readInt(c);
bytestream.add(b);
}
LinkedList<Integer> numbers = VBEncoder.decode(bytestream);
for(Integer number:numbers) System.out.println(number);
//
//here goes the code of VBEncoder.decode
public static LinkedList<Integer> decode(LinkedList<Byte> code) {
LinkedList<Integer> numbers = new LinkedList<Integer>();
int n = 0;
for (int i = 0; !(code.isEmpty()); i++) {
Byte b = code.poll();
int bi = b.toInt();
if (bi < 128) {
n = 128 * n + bi;
} else {
n = 128 * n + (bi - 128);
numbers.add(n);
n = 0;
}
}
return numbers;
}
I get back the sequence:
824
5
214577
how can i write less python2 code to achieve the same thing,need encryption results are the same.
b[i++] = (byte) 172; In what way cast int to byte in python2....
public static String encryptPassword(String content) {
String resultString = "";
String appkey = "ftjf,ckdfkl";
byte[] a = appkey.getBytes();
byte[] datSource = content.getBytes();
byte[] b = new byte[a.length + 4 + datSource.length];
int i;
for (i = 0; i < datSource.length; i++) {
b[i] = datSource[i];
}
b[i++] = (byte) 172;
b[i++] = (byte) 163;
b[i++] = (byte) 161;
b[i++] = (byte) 163;
for (int k = 0; k < a.length; k++) {
b[i] = a[k];
i++;
}
try {
MessageDigest md5 = MessageDigest.getInstance("MD5");
md5.update(b);
resultString = new HexBinaryAdapter().marshal(md5.digest());
} catch (Exception e) {
}
return resultString.toLowerCase();
}
public static void main(String[] args) {
System.out.print(encryptPassword("123456"));
}
Use chr to get the char of a byte in python.
from Crypto.Hash import MD5
key = 'ftjf,ckdfkl'
src= '123'
b = src+chr(172)+chr(163)+chr(161)+chr(163)+key
md5 = MD5.new()
md5.update(b)
text = md5.hexdigest()
print text
Given the src '123',output is:
eedb36cc3204923459dcf891224a0c1d
I am trying to upload .JPG file from android to WCF webservice.
To upload the file from Android i tried 2 ways:
1- Retrofit:
#Multipart
#POST("/UploadFile/{fileName}")
void UploadFile(#Path("fileName") String fileName, #Part("image") TypedFile image, Callback<String> callBack);
2- Android Asynchronous Http Client
here there was 2 options for uploading it:
a- Adding InputStream to the RequestParams:
RequestParams params = new RequestParams();
try {
InputStream stream = new FileInputStream(fileImage);
params.put("image", stream, fileImage.getName() );
client.post(Constants.SERVICE_URL + "/UploadFile/" + fileImage.getName()
, params, getResponseHandler());
} catch (Exception e) {
Utils.LogError("ERROR: " + e.getLocalizedMessage());
}
b- Ading File object to the RequestParams:
RequestParams params = new RequestParams();
try {
//InputStream stream = new FileInputStream(fileImage);
params.put("image", fileImage);
client.post(Constants.SERVICE_URL + "/UploadFile/" + fileImage.getName()
, params, getResponseHandler());
} catch (Exception e) {
Utils.LogError("ERROR: " + e.getLocalizedMessage());
}
All those, sent successfully to server, The received file before parsing looks something like this:
--b1b13fd2-4212-45bb-bb5c-fd4dc074fd1b
Content-Disposition: form-data; name="image"; filename="71d9d7fc-cfa8-40b6-b7aa-5c287cf31c72.jpg"
Content-Type: image/jpeg
Content-Length: 2906
Content-Transfer-Encoding: binary
���� JFIF �� C .................very long string of this stuff
Þq�Ã�9�A?� �0pi1�zq�<�#��:��PV���]|�e�K�mv �ǜ.1�q���&��8��u�m�?�ӵ/���0=8�x�:t�8��>�ׁ���1�POM�k����eea1��ǧq�}8�6��q� � �� .;p1K�g�Onz�Q�oås�a�p1�?>3#���z��0=��m$�H ǧ��Ӄ�v?��x��<q��.8܃��� ��2}1�� c���ϧ q�oA�Rt>��t�=�?����2y�q�큊A����:��q�#���_�~�Q�w��Pu��Ƿ�q�#q��{cۦ���}0:b�|�=#��9�BEV���?O��װ�g���z<N� ��� v�=�?������=�<}x�#'�d�8��e����,�\�4wVV���f�pB���㢁�L{��%$�v裶G8x��b�?���� �]�=:�ӕ����
--b1b13fd2-4212-45bb-bb5c-fd4dc074fd1b--
So I used mulipart parser in order to take out the bytes of the file, the write them to file on the server to finish the uploading.
Here is the code of the multipartparser i used:
public class MultipartParser
{
public MultipartParser(string contents)
{
this.Parse(contents);
}
private void Parse(string contents)
{
Encoding encoding = Encoding.UTF8;
this.Success = false;
// Read the stream into a byte array
byte[] data = encoding.GetBytes(contents);
// Copy to a string for header parsing
string content = contents;
// The first line should contain the delimiter
int delimiterEndIndex = content.IndexOf("\r\n");
if (delimiterEndIndex > -1)
{
string delimiter = content.Substring(0, content.IndexOf("\r\n"));
// Look for Content-Type
Regex re = new Regex(#"(?<=Content\-Type:)(.*?)(?=\r\n)");
Match contentTypeMatch = re.Match(content);
// Look for filename
re = new Regex(#"(?<=filename\=\"")(.*?)(?=\"")");
Match filenameMatch = re.Match(content);
#region added
re = new Regex(#"(?<=Content\-Transfer\-Encoding:)(.*?)(?=\r\n\r\n)");
Match contentTransferEncodingMatch = re.Match(content);
#endregion
// Did we find the required values?
if (contentTypeMatch.Success && filenameMatch.Success && contentTransferEncodingMatch.Success)
{
// Set properties
this.ContentType = contentTypeMatch.Value.Trim();
this.Filename = filenameMatch.Value.Trim();
this.ContentEncoding = contentTransferEncodingMatch.Value.Trim();
// Get the start & end indexes of the file contents
//int startIndex = contentTypeMatch.Index + contentTypeMatch.Length + "\r\n\r\n".Length;
int startIndex = contentTransferEncodingMatch.Index + contentTransferEncodingMatch.Length + "\r\n\r\n".Length;
byte[] delimiterBytes = encoding.GetBytes("\r\n" + delimiter);
string finalDelimeterStr = "\r\n"+delimiter + "--";
byte[] endDilimeterBytes = encoding.GetBytes(finalDelimeterStr);
//byte[] fileBytes = Array.Copy()
//int endIndex = IndexOf(data, endDilimeterBytes, startIndex);
int endIndex = SimpleBoyerMooreSearch(data, endDilimeterBytes);
int contentLength = endIndex - startIndex;
// Extract the file contents from the byte array
byte[] fileData = new byte[contentLength];
Buffer.BlockCopy(data, startIndex, fileData, 0, contentLength);
this.FileContents = fileData;
this.Success = true;
}
}
}
public int SimpleBoyerMooreSearch(byte[] haystack, byte[] needle)
{
int[] lookup = new int[256];
for (int i = 0; i < lookup.Length; i++) { lookup[i] = needle.Length; }
for (int i = 0; i < needle.Length; i++)
{
lookup[needle[i]] = needle.Length - i - 1;
}
int index = needle.Length - 1;
byte lastByte = needle.Last();
while (index < haystack.Length)
{
var checkByte = haystack[index];
if (haystack[index] == lastByte)
{
bool found = true;
for (int j = needle.Length - 2; j >= 0; j--)
{
if (haystack[index - needle.Length + j + 1] != needle[j])
{
found = false;
break;
}
}
if (found)
return index - needle.Length + 1;
else
index++;
}
else
{
index += lookup[checkByte];
}
}
return -1;
}
public static byte[] ToByteArray(Stream stream)
{
byte[] buffer = new byte[32768];
using (MemoryStream ms = new MemoryStream())
{
while (true)
{
int read = stream.Read(buffer, 0, buffer.Length);
if (read <= 0)
return ms.ToArray();
ms.Write(buffer, 0, read);
}
}
}
public bool Success
{
get;
private set;
}
public string ContentType
{
get;
private set;
}
public string ContentEncoding
{
get;
private set;
}
public string Filename
{
get;
private set;
}
public byte[] FileContents
{
get;
private set;
}
}
The parser is taking out the bytes, and parse the received multipart file.
The result file is not showing and it shows error reading file or something.
What i noticed after comparing the files it that the original and received file are different, here is the comparison in Notepad++:
some letters are exists in the original and not exists in the received!
here is the WCF Function declaration and code:
IService.cs:
[OperationContract]
[WebInvoke(Method = "POST", UriTemplate = "/UploadFile/{fileName}"
, ResponseFormat = WebMessageFormat.Json)]
string UploadFile(string fileName ,Stream image);
Service.cs:
public string UploadFile(string fileName, Stream image)
{
string dirPath = System.Web.Hosting.HostingEnvironment.MapPath("~/Logs/");
//string path = dirPath+"log.txt";
// Read the stream into a byte array
byte[] data = MultipartParser.ToByteArray(image);
// Copy to a string
string content = Encoding.UTF8.GetString(data);
File.WriteAllText(dirPath + fileName + ".txt", content); // for checking the result file
MultipartParser parser = new MultipartParser(content);
if (parser != null )
{
if (parser.Success)
{
if (parser.FileContents == null)
return "fail: Null Content";
byte[] bitmap = parser.FileContents;
File.WriteAllBytes(dirPath + fileName +"contents",bitmap);
try
{
using (Image outImage = Image.FromStream(new MemoryStream(bitmap)))
{
outImage.Save(fileName, ImageFormat.Jpeg);
}
return "success";
}
catch (Exception e)
{ // I get this exception all the time
return "Fail: e " + e.Message;
}
}
return "fail not success";
}
return "fail";
}
I tried every possible solution came to my mind, still could not get whats wrong!!! is the problem in the encoding while sending or the parser!??
Please what can be the problem!? i am struggling with this for 3 days!
Thank you ALL :)
The were 2 problems:
The parser
Decoding the bytes to string was not good idea.
I modified the parser to this one and it will take care of the rest:
public class MultipartParser
{
public MultipartParser(Stream stream)
{
this.Parse(stream);
}
private void Parse(Stream stream)
{
this.Success = false;
if(!stream.CanRead)
return;
// Read the stream into a byte array
byte[] data = MultipartParser.ToByteArray(stream);
if (data.Length < 1)
return;
// finding the delimiter (the string in the beginning and end of the file
int delimeterIndex = MultipartParser.SimpleBoyerMooreSearch(data, Encoding.UTF8.GetBytes("\r\n")); // here we got delimeter index
if (delimeterIndex == -1) return;
byte[] delimeterBytes = new byte[delimeterIndex];
Array.Copy(data, delimeterBytes, delimeterIndex);
// removing the very first couple of lines, till we get the beginning of the JPG file
byte[] newLineBytes = Encoding.UTF8.GetBytes("\r\n\r\n");
int startIndex = 0;
startIndex = MultipartParser.SimpleBoyerMooreSearch(data, newLineBytes);
if (startIndex == -1)
return;
int startIndexWith2Lines = startIndex + 4; // 4 is the bytes of "\r\n\r\n"
int newLength = data.Length - startIndexWith2Lines;
byte[] newByteArray = new byte[newLength];
Array.Copy(data, startIndex + 4, newByteArray, 0, newLength - 1);
// check for the end of the stream, is ther same delimeter
int isThereDelimeterInTheEnd = MultipartParser.SimpleBoyerMooreSearch(newByteArray, delimeterBytes);
if (isThereDelimeterInTheEnd == -1) return; // the file corrupted so
int endIndex = isThereDelimeterInTheEnd - delimeterBytes.Length;
byte[] lastArray = new byte[endIndex];
Array.Copy(newByteArray, 0, lastArray, 0, endIndex);
this.FileContents = lastArray;
this.Success = true;
}
static byte[] GetBytes(string str)
{
byte[] bytes = new byte[str.Length * sizeof(char)];
System.Buffer.BlockCopy(str.ToCharArray(), 0, bytes, 0, bytes.Length);
return bytes;
}
static string GetString(byte[] bytes)
{
char[] chars = new char[bytes.Length / sizeof(char)];
System.Buffer.BlockCopy(bytes, 0, chars, 0, bytes.Length);
return new string(chars);
}
public static int SimpleBoyerMooreSearch(byte[] haystack, byte[] needle)
{
int[] lookup = new int[256];
for (int i = 0; i < lookup.Length; i++) { lookup[i] = needle.Length; }
for (int i = 0; i < needle.Length; i++)
{
lookup[needle[i]] = needle.Length - i - 1;
}
int index = needle.Length - 1;
byte lastByte = needle.Last();
while (index < haystack.Length)
{
var checkByte = haystack[index];
if (haystack[index] == lastByte)
{
bool found = true;
for (int j = needle.Length - 2; j >= 0; j--)
{
if (haystack[index - needle.Length + j + 1] != needle[j])
{
found = false;
break;
}
}
if (found)
return index - needle.Length + 1;
else
index++;
}
else
{
index += lookup[checkByte];
}
}
return -1;
}
private int IndexOf(byte[] searchWithin, byte[] serachFor, int startIndex)
{
int index = 0;
int startPos = Array.IndexOf(searchWithin, serachFor[0], startIndex);
if (startPos != -1)
{
while ((startPos + index) < searchWithin.Length)
{
if (searchWithin[startPos + index] == serachFor[index])
{
index++;
if (index == serachFor.Length)
{
return startPos;
}
}
else
{
startPos = Array.IndexOf<byte>(searchWithin, serachFor[0], startPos + index);
if (startPos == -1)
{
return -1;
}
index = 0;
}
}
}
return -1;
}
public static byte[] ToByteArray(Stream stream)
{
byte[] buffer = new byte[32768];
using (MemoryStream ms = new MemoryStream())
{
while (true)
{
int read = stream.Read(buffer, 0, buffer.Length);
if (read <= 0)
return ms.ToArray();
ms.Write(buffer, 0, read);
}
}
}
public bool Success
{
get;
private set;
}
public byte[] FileContents
{
get;
private set;
}
}
So you can use this parser for this kind of multipart files encoding:
--b1b13fd2-4212-45bb-bb5c-fd4dc074fd1b
Content-Disposition: form-data; name="image"; filename="71d9d7fc-cfa8-40b6-b7aa-5c287cf31c72.jpg"
Content-Type: image/jpeg
Content-Length: 2906
Content-Transfer-Encoding: binary
���� JFIF �� C .................very long string of this stuff
Þq�Ã�9�A?� �0pi1�zq�<�#��:��PV���]|�e�K�mv �ǜ.1�q���&��8��u�m�?�ӵ/��Ƿ�q�#q��{cۦ���}0:b�|�=#��9�BEV���?O��װ�g���z<N� ��� v�=�?������=�<}x�#'�d�8��e����,�\�4wVV���f�pB���㢁�L{��%$�v裶G8x��b�?���� �]�=:�ӕ����
--b1b13fd2-4212-45bb-bb5c-fd4dc074fd1b--
Hope it helps somebody else.
You could try to encode the jpeg to base64 before sending it. As far as I know, this is a proper solution. Decoding it on the server, should be no problem. (Sry, I wanted to write a comment - but I'm not allowed to it)
I needed a method that would convert hex to ascii, and most seem to be a variation of the following:
public String hexToAscii(String hex) {
StringBuilder sb = new StringBuilder();
StringBuilder temp = new StringBuilder();
for(int i = 0; i < hex.length() - 1; i += 2){
String output = hex.substring(i, (i + 2));
int decimal = Integer.parseInt(output, 16);
sb.append((char)decimal);
temp.append(decimal);
}
return sb.toString();
}
The idea is to look at
hexToAscii("51d37bdd871c9e1f4d5541be67a6ab625e32028744d7d4609d0c37747b40cd2d");
If I print the result out, I get
-Í#{t7?`Ô×D?2^b«¦g¾AUM??Ý{ÓQ.
This is not the result I am needing though. A friend got the correct result in PHP which was the string reverse of the following:
QÓ{݇žMUA¾g¦«b^2‡D×Ô`7t{#Í-
There are clearly characters that his hexToAscii function is encoding whereas mine is not.
Not really sure why this is the case, but how can I implement this version in Java?
Assuming your input string is in, I would use a method like this
public static byte[] decode(String in) {
if (in != null) {
in = in.trim();
List<Byte> bytes = new ArrayList<Byte>();
char[] chArr = in.toCharArray();
int t = 0;
while (t + 1 < chArr.length) {
String token = "" + chArr[t] + chArr[t + 1];
// This subtracts 128 from the byte value.
int b = Byte.MIN_VALUE
+ Integer.valueOf(token, 16);
bytes.add((byte) b);
t += 2;
}
byte[] out = new byte[bytes.size()];
for (int i = 0; i < bytes.size(); ++i) {
out[i] = bytes.get(i);
}
return out;
}
return new byte[] {};
}
And then you could use it like this
new String(decode("51d37bdd871c9e1f4d5541be67a6ab625e"
+"32028744d7d4609d0c37747b40cd2d"))
How about trying like this:
public static void main(String[] args) {
String hex = "51d37bdd871c9e1f4d5541be67a6ab625e32028744d7d4609d0c37747b40cd2d";
StringBuilder output = new StringBuilder();
for (int i = 0; i < hex.length(); i+=2) {
String str = hex.substring(i, i+2);
output.append((char)Integer.parseInt(str, 16));
}
System.out.println(output);
}