我尝试使用Kalium作为Java warpper使用Libsodium库加密密码。我试图安装它,但我在一些问题上运行。我已经将Kalium依赖项添加到我的pom.xml中,并将libsoidum放在我的javapath中,如here所述。现在我实际上想要使用库来哈希我的密码,然后开始将它们保存在我的数据库中。 (我知道oAuth是首选,但这不是软件中的选项。)问题是我不知道如何实际使用包装器。我找不到任何文档或示例。有没有可以帮助我的消息来源?
答案 0 :(得分:1)
试试这个
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);
}
}