在Java中,是否有一种非常简单的本地方法来使用密钥加密/解密字符串?我并不太关心使用何种类型的加密(如AES、DES等),我只关心它是由密钥绑定且不容易被破解。
理想情况下,我希望它是一行代码解决的,就像这样:
String encryptedString = NativeEncryptionClass.encrypt("this is the data", "key123");
谢谢
在Java中,是否有一种非常简单的本地方法来使用密钥加密/解密字符串?我并不太关心使用何种类型的加密(如AES、DES等),我只关心它是由密钥绑定且不容易被破解。
理想情况下,我希望它是一行代码解决的,就像这样:
String encryptedString = NativeEncryptionClass.encrypt("this is the data", "key123");
谢谢
好的,也许这不是“一行代码”,但似乎足够简单:
使用Java的Cipher类。在这里看看...(此页面还有其他示例...)
http://download.oracle.com/javase/6/docs/technotes/guides/security/crypto/CryptoSpec.html#BlowKeyEx
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
public class SimpleMD5Example {
public static void main(String[] args) {
String passwordToHash = "0";
String generatedPassword = null;
try {
// Create MessageDigest instance for MD5
MessageDigest md = MessageDigest.getInstance("MD5");
// Add password bytes to digest
md.update(passwordToHash.getBytes());
// Get the hash's bytes
byte[] bytes = md.digest();
System.out.println(bytes);
// This bytes[] has bytes in decimal format;
// Convert it to hexadecimal format
StringBuilder sb = new StringBuilder();
for (int i = 0; i < bytes.length; i++) {
sb.append(Integer.toString((bytes[i] & 0xff), 16).substring(1));
}
// Get complete hashed password in hex format
generatedPassword = sb.toString();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
System.out.println(generatedPassword);
}
}