有人能做到这一点吗?我有很少的Java知识,并希望得到一个脚本,通过与程序相同的散列运行一个单词,看看我是否可以从相同的代码获得类似的结果。爪哇..
import java.util.List;
import java.security.MessageDigest;
/*
BASIC FORMAT OF WHAT I WOULD LIKE SOMEONE TO FIX
ONLY WANT TO ENCRYPT VIA THIS METHOD*/
public class encrypt {
/* WANT TO GET USER-INPUT AND RUN IT THROUGH THIS METHOD OF HASHING*/
String code = array[0];
String encrypted = encrypt(code);
/*ERRORS SO*/
public static void main(String[] args) {
/* WANT TO PRINT OUT RESULT HERE
AIM IS TO GET A HASH THAT LOOKS LIKE:
"2473511743116990591436219521516221715316",
"101208251115150352340242201171221515066157"
FROM THE WORD "pizzaroma"*/
System.out.println(encrypted);
}
/*NO CLUE WHAT THIS DOES ^^^^ Array?*/
private String getString(byte[] bytes) {
StringBuffer sb = new StringBuffer();
for (int i = 0; i < bytes.length; i++) {
byte b = bytes[i];
sb.append(0xFF & b);
}
return sb.toString();
}
public String encrypt(String source) {
try {
MessageDigest md = MessageDigest.getInstance("MD5");
byte[] bytes = md.digest(source.getBytes());
return getString(bytes);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
/*FAR:encrypt.java:6:error:cannot find symbol
String code=array[0];
symbol:variable array
location:*/
/*
class encrypt
encrypt.java:35:error:non-static variable encrypted cannot be
referenced from a static context
System.out.println(encrypted);^
2 errors*/
答案 0 :(得分:-1)
您可以在base64 lib的帮助下完成此操作,首先需要像
一样导入它import org.apache.commons.codec.binary.Base64;
然后更改您的Class以使用BASE64类。 这里有一些示例代码:
byte[] encodedBytes = Base64.encodeBase64("Test".getBytes());
System.out.println("encodedBytes " + new String(encodedBytes));
byte[] decodedBytes = Base64.decodeBase64(encodedBytes);
System.out.println("decodedBytes " + new String(decodedBytes));
答案 1 :(得分:-2)
试试这段代码。
import java.security.MessageDigest;
public class Test {
String code = null;
String encrypted = null;
private String getString(byte[] bytes) {
StringBuffer sb = new StringBuffer();
for (int i = 0; i < bytes.length; i++)
{
byte b = bytes[i];
sb.append(0xFF & b);
}
return sb.toString();
}
public String encrypt(String source) {
try {
MessageDigest md = MessageDigest.getInstance("MD5");
byte[] bytes = md.digest(source.getBytes());
return getString(bytes);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public static void main(String args[]) {
Test t = new Test();
t.code = "pizzaroma";
t.encrypted = t.encrypt(t.code);
System.out.println(t.encrypted);
}
}