I have a wordlist with ~68000 words from level 20 at 0xf.at and want to hash two words to get a hash. Then compare this hash to an existing hash until i found the two words.
I have tried it in java but I am unexpirenced and it is to slow.
import java.io.*;
public class Main {
public static void main(String[] args) throws FileNotFoundException,
IOException {
try (BufferedReader br = new BufferedReader(new FileReader("E:/Trojan/Desktop/wordlist.txt"))) {
StringBuilder sb = new StringBuilder();
String line = br.readLine();
Hash h = new Hash();
String myHash = "cd48323bcf01557f5deadc2ec301affb";
while (line != null) {
sb.append(line);
sb.append(System.lineSeparator());
line = br.readLine();
}
String everything = sb.toString();
String lines[] = everything.split("\\r?\\n");
for (int j = 1; j <= 68848; j++) {
for (int i = 1; i <= 68847; i++) {
//System.out.println(i+":"+lines[i]+" "+j+":"+lines[j]);
if (h.getHash(lines[i]+lines[j], "MD5") == myHash){
System.out.println(lines[i]+lines[j]);
break;
}
}
}
}
}
}
And the md5 hash function i took from an exmaple of stackoverflow:
public class Hash {
/**
*
* #param txt, text in plain format
* #param hashType MD5 OR SHA1
* #return hash in hashType
*/
public static String getHash(String txt, String hashType) {
try {
java.security.MessageDigest md = java.security.MessageDigest.getInstance(hashType);
byte[] array = md.digest(txt.getBytes());
StringBuffer sb = new StringBuffer();
for (int i = 0; i < array.length; ++i) {
sb.append(Integer.toHexString((array[i] & 0xFF) | 0x100).substring(1,3));
}
return sb.toString();
} catch (java.security.NoSuchAlgorithmException e) {
//error action
}
return null;
}
public static String md5(String txt) {
return Hash.getHash(txt, "MD5");
}
public static String sha1(String txt) {
return Hash.getHash(txt, "SHA1");
}
}
How can I get this faster?
You create too many temporary objects inside method getHash. Try reduce. E.g.
private static final char[] HEX ={'0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f',};
public static String getHash(String txt, MessageDigest md) {
byte[] array = md.digest(txt.getBytes());
char[] result = new char[array.length*2];
for (int i = 0; i < array.length; ++i) {
byte b = array[i];
result[2*i] = HEX[(b&0x0f0)>>>4];
result[2*i+1] = HEX[b&0x0f];
}
return new String(result);
}
EDIT
Moreover you do not need String objects at all. You should return byte[] and use Arrays.equals method.
Related
hey i write e java Obfuscator and build it using IntelliJ IDEA Artefact but when I enter arguments for obf file, the console outputs:
Error: Could not find or load main class JavaCodeObfuscator
Caused by: java.lang.ClassNotFoundException: JavaCodeObfuscator
Console Argument : java JavaCodeObfuscator hello.java
code:
import java.io.*;
import java.util.*;
public class JavaCodeObfuscator {
private static final int MIN_NAME_LENGTH = 4;
private static final int MAX_NAME_LENGTH = 8;
private static final int NAME_CHAR_SET_SIZE = 26;
private static final Random RANDOM = new Random();
public static void main(String[] args) {
if (args.length < 1) {
return;
}
String inputFile = args[0];
try {
String sourceCode = readSourceCode(inputFile);
String obfuscatedCode = obfuscate(sourceCode);
String outputFilePath = getOutputFilePath(inputFile);
writeObfuscatedCode(obfuscatedCode, outputFilePath);
} catch (IOException e) {
System.err.println("Error: " + e.getMessage());
}
}
private static String readSourceCode(String inputFile) throws IOException {
BufferedReader reader = new BufferedReader(new FileReader(inputFile));
StringBuilder sourceCodeBuilder = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
sourceCodeBuilder.append(line).append("\n");
}
reader.close();
return sourceCodeBuilder.toString();
}
private static String obfuscate(String sourceCode) {
Map<String, String> nameMap = new HashMap<>();
StringBuilder obfuscatedCodeBuilder = new StringBuilder();
int nameCounter = 0;
for (int i = 0; i < sourceCode.length(); i++) {
char c = sourceCode.charAt(i);
if (Character.isJavaIdentifierStart(c)) {
StringBuilder nameBuilder = new StringBuilder();
nameBuilder.append(c);
while (i < sourceCode.length() - 1 && Character.isJavaIdentifierPart(c = sourceCode.charAt(++i))) {
nameBuilder.append(c);
}
String name = nameBuilder.toString();
String obfuscatedName = nameMap.get(name);
if (obfuscatedName == null) {
obfuscatedName = generateName(nameCounter++);
nameMap.put(name, obfuscatedName);
}
obfuscatedCodeBuilder.append(obfuscatedName);
i--;
} else {
obfuscatedCodeBuilder.append(c);
}
}
return obfuscatedCodeBuilder.toString();
}
private static String generateName(int index) {
StringBuilder nameBuilder = new StringBuilder();
int nameLength = MIN_NAME_LENGTH + RANDOM.nextInt(MAX_NAME_LENGTH - MIN_NAME_LENGTH + 1);
for (int i = 0; i < nameLength; i++) {
char c = (char) ('a' + RANDOM.nextInt(NAME_CHAR_SET_SIZE));
nameBuilder.append(c);
}
return nameBuilder.toString();
}
private static String getOutputFilePath(String inputFile) {
int dotIndex = inputFile.lastIndexOf('.');
String extension = dotIndex >= 0 ? inputFile.substring(dotIndex) : "";
String outputFileName = inputFile.substring(0, inputFile.length() - extension.length()) + "_obfuscated" + extension;
return outputFileName;
}
private static void writeObfuscatedCode(String obfuscatedCode, String outputFilePath) throws IOException {
PrintWriter writer = new PrintWriter(new FileWriter(outputFilePath));
writer.print(obfuscatedCode);
writer.close();
System.out.println("Protected");
}
}
Yes, I'm new to programming and maybe I did something wrong when building the original jar file
After running a Junit test for String serialization, it is failed and gave me the following results:
Expected: "netmodel"
Actual: "l"
The serialize method as follows
public static void serializeString(String objectToSerialize, OutputStream outputStream) {
byte[] bytesArr = objectToSerialize.getBytes();
serializeInt(bytesArr.length, outputStream);
try {
outputStream.write(bytesArr);
} catch (IOException e) {
e.printStackTrace();
}
}
And my deserialize method as follows
public static String deserializeString(InputStream inputStream) {
String deserializeObject = "";
char asciiToChar;
int stringByteArrayLength = deserializeInt(inputStream);
byte[] databytesArr = new byte[stringByteArrayLength];
try {
inputStream.read(databytesArr, 0, stringByteArrayLength);
}
catch (IOException e) {
e.printStackTrace();
}
for (int i = 0; i < databytesArr.length; i++) {
asciiToChar = (char) databytesArr[i];
deserializeObject = "" + Character.toString(asciiToChar);
}
return deserializeObject;
}
Finally, I wrote a unit test as follows
public class StringSerializerTest {
private InputStream iStream;
private ByteArrayOutputStream oStream;
#Before
public void init() {
oStream = new ByteArrayOutputStream();
}
String serialzeAndDeserializeObject(String stringValue) {
OutputStreamUtil.serializeString(stringValue, oStream);
iStream = new ByteArrayInputStream(oStream.toByteArray());
return InputStreamUtil.deserializeString(iStream);
}
#Test
public void equals_equal() {
String stringValue = "netmodel";
String deserializedStringValue = serialzeAndDeserializeObject(stringValue);
assertThat(deserializedStringValue).isEqualTo(stringValue);
}
}
what was wrong? and how to fix it?
You are reassigning the entire value of deserializeObject during each iteration of
for (int i = 0; i < databytesArr.length; i++) {
asciiToChar = (char) databytesArr[i];
deserializeObject = "" + Character.toString(asciiToChar);
}
This results in only the last character (l in this case) being stored in deserializeObject. This loop should append the next character to the deserializeObject as in the following:
for (int i = 0; i < databytesArr.length; i++) {
asciiToChar = (char) databytesArr[i];
deserializeObject += Character.toString(asciiToChar);
}
The corrected deserialization logic would be:
public static String deserializeString(InputStream inputStream) {
String deserializeObject = "";
char asciiToChar;
int stringByteArrayLength = deserializeInt(inputStream);
byte[] databytesArr = new byte[stringByteArrayLength];
try {
inputStream.read(databytesArr, 0, stringByteArrayLength);
}
catch (IOException e) {
e.printStackTrace();
}
for (int i = 0; i < databytesArr.length; i++) {
asciiToChar = (char) databytesArr[i];
deserializeObject += Character.toString(asciiToChar);
}
return deserializeObject;
}
The error was already reported by Justin Albano.
However take also care of strings with non-ASCII: like special characters.
Something like the following. Also one should close at the end to ensure flushing in case of a buffered stream. And theoretically a read could yield only a non-blocking part of the array. DataOutputStream has nice methods, though you seem to roll your own serialisation.
public static void serializeString(String objectToSerialize, OutputStream outputStream)
throws IOException {
byte[] bytesArr = objectToSerialize.getBytes(StandardCharsets.UTF_8);
serializeInt(bytesArr.length, outputStream);
outputStream.write(bytesArr);
}
public static String deserializeString(InputStream inputStream)
throws IOException {
int stringByteArrayLength = deserializeInt(inputStream);
byte[] databytesArr = new byte[stringByteArrayLength];
readFully(inputStream, databytesArr);
return new String(databytesArr, StandardCharsets.UTF_8);
}
private static void readFully(InputStream inputStream, byte[] bytes) throws IOException {
int i = 0;
while (i < bytes.length) {
int nread = inputStream.read(bytes, i, bytes.length - i);
if (nread <= 0) {
throw new IOException("Premature EOF");
}
i += nread;
}
}
Mind that StandardCharsets is not in Android SDK, only standard Java.
I am trying to find a CRC32 collision in Java then checking the hash with pycrc. I tried what was described in this thread, but I still can't get my implementation to match with pycrc. What am I doing wrong?
public static void print() {
Checksum h = new CRC32();
Map<Long, String> seen = new HashMap<Long, String>();
while (true) {
String s = randomString();
byte[] b = s.getBytes(StandardCharsets.UTF_8);
h.update(b, 0, b.length);
Long l = h.getValue();
if (!seen.containsKey(l)) {
seen.put(l, s);
} else {
System.out.println(s + "; " + seen.get(l));
return;
}
}
}
Edit
After some more investigation, I found that it isn't that pycrc is hashing differently from Java's implementation, but that Java is simply giving me two strings with different hashes. For example, "93C7946B05" hashes to "0xf2792761" and "323C239466" hashes to "0x59fc1818", but when Java is comparing the hashes (using the implementation below), they appear to be "equal."
Updated code:
static char[] chars = "0123456789ABCDEF".toCharArray();
public static void print() {
Checksum h = new CRC32();
String key;
Map<String, String> seen = new HashMap<String, String>();
while (true) {
String s = randomString();
byte[] b = s.getBytes(StandardCharsets.UTF_8);
h.update(b, 0, b.length);
Long l = h.getValue();
key = Long.toHexString(l);
if (!seen.containsKey(key)) {
seen.put(key, s);
} else {
System.out.println(s + "; " + seen.get(key));
return;
}
}
}
public static String randomString() {
StringBuilder sb = new StringBuilder();
Random random = new Random();
//int len = random.nextInt(32) + 1;
//for (int i = 0; i < len; i++) {
for (int i = 0; i < 10; i++) {
char c = chars[random.nextInt(chars.length)];
sb.append(c);
}
String output = sb.toString();
return output;
}
Your problem is that you re-use the CRC32 instance without calling h.reset();.
Therefore the CRC32 you get is not for the current string to be tested but for the concat of all strings you have tested so far.
Can any one help me write decrypt method for my XOR encryptor. So how i'm encrypt:
I'm making XOR
public static String idEncrypt(String id, String key)throws Exception
{
if (id == null)
return null;
if (key.length() == 0)
return id;
String utfID="", utfKey="";
try
{
utfID = new String(id.getBytes(), "UTF-8");
utfKey = new String(key.getBytes(), "UTF-8");
}
catch (UnsupportedEncodingException e)
{
Log.e("utf8", "conversion", e);
}
StringBuilder sb = new StringBuilder();
for(int i = 0; i < utfID.length(); i++)
sb.append((char)(utfID.charAt(i) ^ utfKey.charAt(i % utfKey.length())));
String result = sb.toString();
return toHex(result.getBytes());
}
Converting bytes to hex:
public static String toHex(byte[] buf) {
if (buf == null)
return "";
StringBuffer result = new StringBuffer(2*buf.length);
for (int i = 0; i < buf.length; i++) {
appendHex(result, buf[i]);
}
return result.toString();
}
private final static String HEX = "0123456789abcdef";
private static void appendHex(StringBuffer sb, byte b) {
sb.append(HEX.charAt((b>>4)&0x0f)).append(HEX.charAt(b&0x0f));
}
Actually all of my trying to decrypt result of this crypts failed =(
May be some on explains me how work with it?
P.S: the results of my trying is strings like "X¨»¾RkÖ_êQ", but must be 16 symbols of numbers and letters.
UPD:
My fromHEX() method
public static String fromHex(String hex) {
return new String(toByte(hex));
}
public static byte[] toByte(String hexString) {
int len = hexString.length()/2;
byte[] result = new byte[len];
for (int i = 0; i < len; i++)
result[i] = Integer.valueOf(hexString.substring(2*i, 2*i+2), 16).byteValue();
return result;
}
I'm getting an error can someone help me with the following code:
it is supposed to perform preprocesing
// program to perform preprocess
public static void main(String[] args) {
//public class PreProcess {
// Read a file into a string. Takes file path, returns string
/**
*
* #param path
* #return
*/
public String readFileIntoString(String path) {
char[] line = new char[1024];
StringBuilder dataString;
dataString = new StringBuilder(5000);
try {
try (BufferedReader input = new BufferedReader(new FileReader(path))) {
while (true) {
int readLength = input.read(line);
if (readLength == -1)
break;
dataString.append(line, 0, readLength);
}
}
return dataString.toString();
}
catch (IOException e) {
return " ";
}
}
// Removes stop words from a string. Takes stop word file path and returns
// string
public static String removeStopWords(String fileData, String stopWordFilePath) {
String newfile = fileData;
String line;
try {
BufferedReader input = new BufferedReader(new FileReader(stopWordFilePath));
while ((line = input.readLine()) != null) {
if (line.compareTo("") == 0)
continue;
line = " " + line + " ";
newfile = newfile.replaceAll(line, " ");
}
input.close();
}
catch (IOException e) {
e.printStackTrace();
}
return newfile;
}
public static String removeHTMLTags(String fileData) {
return strip(fileData);
}
// Filtering to a given windowsize for query terms. Takes query and size,
// returns string
public static String filterToWindow(String query, String fileData, int windowSize) {
StringBuffer dataString = new StringBuffer(5000);
String[] fileWords = fileData.split(" ");
String[] queryWords = query.split(" ");
int[] markWords = new int[fileWords.length];
for (int i = 0; i < fileWords.length; i++) {
markWords[i] = 0;
}
for (int i = 0; i < fileWords.length; i++) {
for (int j = 0; j < queryWords.length; j++) {
if (fileWords[i].compareTo(queryWords[j]) == 0) {
for (int k = 0; k < windowSize; k++) {
if (i + k < fileWords.length)
markWords[i + k] = 1;
if (i - k > 0)
markWords[i - k] = 1;
}
}
}
}
for (int i = 0; i < fileWords.length; i++) {
if (markWords[i] == 1) {
dataString.append(fileWords[i]);
dataString.append(" ");
}
}
return dataString.toString();
}
public static void extractMetaData(String fileData, String linkFilePath, int docId) {
int urlEnd = 0, urlStart = 0;
StringBuilder b3 = new StringBuilder();
StringBuilder b2 = new StringBuilder();
fileData = fileData.toLowerCase();
try {
String title = fileData.substring(fileData.indexOf("<title"), fileData.indexOf("</title>")).replaceAll("\\<.*?>", "");
writeStringIntoFile(title, linkFilePath + docId + ".title");
}
catch (Exception e) {
}
while (true) {
urlStart = fileData.indexOf("a href=\"", urlEnd) + 8;
if (urlStart == 7)
break;
urlEnd = fileData.indexOf('\"', urlStart + 1);
String link = fileData.substring(urlStart, urlEnd);
int linkstart = 0;
int linkend = link.length() - 1;
if (link.startsWith("http"))
link = link.substring(7);
while (link.startsWith("/"))
link = link.substring(1);
if (!link.startsWith("#")) {
if (link.indexOf('/') != -1)
link = link.substring(0, link.indexOf('/'));
if (!link.contains("wiki") && !link.contains("myspace.com") && !link.contains("javascript")) {
b3.append(link);
b3.append("\n");
}
}
}
writeStringIntoFile(b3.toString(), linkFilePath + docId + ".links");
urlEnd = 0;
while (true) {
urlStart = fileData.indexOf("src=\"", urlEnd) + 5;
if (urlStart == 4)
break;
urlEnd = fileData.indexOf('\"', urlStart + 1);
String link = fileData.substring(urlStart, urlEnd);
if (!link.startsWith("#")) {
if (!link.startsWith("/")) {
link = link.substring(0, link.lastIndexOf('/') + 1);
}
b2.append(link);
b2.append("\n");
}
}
writeStringIntoFile(b2.toString(), linkFilePath + docId + ".images");
}
// Saves a string to a file. Takes string and file path
public static void writeStringIntoFile(String fileData, String path) {
try {
try (BufferedWriter output = new BufferedWriter(new FileWriter(path))) {
output.write(fileData);
}
}
catch (IOException e) {
}
}
private static String strip(String inputString) {
inputString = inputString.replaceAll("\\<style.*?</style>", " ");
inputString = inputString.replaceAll("\\<script.*?</script>", " ");
inputString = inputString.replaceAll("\\<.*?>", " ").replaceAll("[^A-Za-z]+", " ").replaceAll("\\s+", " ");
inputString = inputString.trim();
// inputString = PorterStemmer.applyStemmer(inputString);
return inputString;
}
}
}
You've declared methods inside your main()
public static void main(String[] args) {
public String readFileIntoString(String path) {
char[] line = new char[1024];
StringBuilder dataString;
...
You cannot do this. Methods cannot be nested inside methods. Take them out
public static void main(String[] args) {
...
}
public String readFileIntoString(String path) {
char[] line = new char[1024];
StringBuilder dataString;
...