【发布时间】:2019-06-11 03:35:52
【问题描述】:
以下是加密用户字符串的代码:
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import sun.misc.BASE64Encoder;
import java.io.*;
class Encrypter {
public synchronized String encrypt(String plainText) throws Exception {
MessageDigest md = null;
try {
md = MessageDigest.getInstance("SHA");
}catch(Exception exc) {
throw new Exception(exc.getMessage());
}
try {
md.update(plainText.getBytes("UTF-8"));
}catch(Exception exc) {
throw new Exception(exc.getMessage());
}
byte raw[] = md.digest();
String hash = (new BASE64Encoder()).encode(raw);
return hash;
}
public static void main(String args[]) {
try {
Encrypter encrypter = new Encrypter();
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String userInput = br.readLine();
String encryptedPassword = encrypter.encrypt(userInput);
System.out.println(encryptedPassword);
} catch(Exception exc) {
System.out.println(exc);
}
}
}
当我编译代码时,我得到了这些警告:
Encrypter.java:4: warning: BASE64Encoder is internal proprietary API and may be removed in a future release
import sun.misc.BASE64Encoder;
^
Encrypter.java:23: warning: BASE64Encoder is internal proprietary API and may be removed in a future release
String hash = (new BASE64Encoder()).encode(raw);
^
2 warnings
还有其他方法可以在java中加密字符串吗?
MessageDigest 类的方法update 有什么作用?即md.update(plainText.getBytes("UTF-8")); 的声明是做什么的?
什么是BASE64Encoder 类?我找不到它的 DOC
【问题讨论】:
-
“加密”表示可逆操作。这是散列(在这种情况下使用 SHA)。
-
你不妨使用
[DatatypeConverter.printBase64Binary(byte[])](docs.oracle.com/javase/6/docs/api/javax/xml/bind/…)
标签: java encryption cryptography