2017-06-10 26 views
0

我試圖使用Kalium作爲Java warpper使用Libsodium庫加密密碼。我試圖安裝它,但我在幾個問題上運行。我已經將Kalium依賴項添加到我的pom.xml中,並將libsoidum放置在我的javapath中,如here所述。現在我真的想使用庫來散列我的密碼,並開始將它們保存在我的數據庫中。 (我知道oAuth是首選,但這不是軟件中的選項)。問題是我不知道如何實際使用包裝。我找不到任何文檔或示例。有源可以幫助我嗎?在java項目中使用Libsodium/Kalium

+0

爲什麼該庫特別? – Tim

+0

@Tim我現在正在使用Windows x64 .dll。我必須找到一些方法將其移植到heroku(可能使用其他庫),因爲最終應用程序將部署在那裏。 – Luminai

+1

這不是我的意思;你說你想用Java加密密碼;您希望使用的'libsodium'中的哪些功能在更容易與Java集成的數百個其他加密庫中不可用? – Tim

回答

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

    } 
}