試試這個
import com.muquit.libsodiumjna.SodiumLibrary;
import com.muquit.libsodiumjna.exceptions.SodiumLibraryException;
import java.nio.charset.StandardCharsets;
public class Encrypt2 {
private static String libraryPath = "D:/libsodium/libsodium.dll";
private static String ourPassPhrase = "your very secret password";
private static byte[] passPhrase = ourPassPhrase.getBytes();
private static String ourMessage = "password which you want to encrypt and decrypt";
private static byte[] privateKey = (ourMessage.getBytes());
public static void main(String[] args) throws Exception {
SodiumLibrary.setLibraryPath(libraryPath);
encrypt();
decrypt();
}
private static void encrypt() throws SodiumLibraryException {
System.out.println("----Encrypt-----");
// The salt (probably) can be stored along with the encrypted data
byte[] salt = SodiumLibrary.randomBytes(SodiumLibrary.cryptoPwhashSaltBytes());
byte[] key = SodiumLibrary.cryptoPwhashArgon2i(passPhrase, salt);
String saltedPrivateKey = new String(key, StandardCharsets.UTF_8);
System.out.println("saltedPrivateKey bytes - " + saltedPrivateKey);
/**
* nonce must be 24 bytes length, so we put int 24 to randomBytes method
* **/
byte[] nonce = SodiumLibrary.randomBytes(24);
byte[] encryptedPrivateKey = SodiumLibrary.cryptoSecretBoxEasy(privateKey, nonce, key);
String encryptedPW = new String(encryptedPrivateKey, StandardCharsets.UTF_8);
System.out.println("encryptedPrivateKey bytes - " + encryptedPW);
}
private static void decrypt() throws SodiumLibraryException {
System.out.println("----Decrypt-----");
byte[] salt = SodiumLibrary.randomBytes(SodiumLibrary.cryptoPwhashSaltBytes());
byte[] key = SodiumLibrary.cryptoPwhashArgon2i(passPhrase, salt);
byte[] nonce = SodiumLibrary.randomBytes(24);
byte[] encryptedPrivateKey = SodiumLibrary.cryptoSecretBoxEasy(privateKey, nonce, key);
privateKey = SodiumLibrary.cryptoSecretBoxOpenEasy(encryptedPrivateKey, nonce, key);
String dencryptedPW = new String(privateKey, StandardCharsets.UTF_8);
System.out.println("our secret phrase - " + dencryptedPW);
}
}
爲什麼該庫特別? – Tim
@Tim我現在正在使用Windows x64 .dll。我必須找到一些方法將其移植到heroku(可能使用其他庫),因爲最終應用程序將部署在那裏。 – Luminai
這不是我的意思;你說你想用Java加密密碼;您希望使用的'libsodium'中的哪些功能在更容易與Java集成的數百個其他加密庫中不可用? – Tim