1

我正在尝试使用 Libsodium 库使用 Kalium 作为 Java 变形器来加密密码。我正在尝试安装它,但我遇到了一些问题。我已将 Kalium 依赖项添加到我的 pom.xml 中,并将 libsoidum 放置在我的 javapath 中,如此处所述。现在我实际上想使用该库对我的密码进行哈希处理,然后开始将它们保存在我的数据库中。(我知道 oAuth 是首选,但这不是软件中的一个选项。)问题是我不知道如何实际使用包装器。我找不到任何文档或示例。有没有可以帮助我的来源?

4

1 回答 1

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);

    }
}
于 2017-12-14T20:15:00.543 回答