GNU/Linux >> Linux Esercitazione >  >> Linux

Installa SoftHSM e accedi tramite il programma Java

SoftHSM è un'implementazione software di HSM (Hardware Security Module) che mira a svolgere tutte le funzioni che un vero HSM svolgerebbe senza fornire le protezioni di sicurezza hardware offerte da un vero HSM. Se sei un utente che non è disposto a investire in un nuovo dispositivo hardware, puoi utilizzare SoftHSM che è un archivio crittografico accessibile tramite un'interfaccia PKCS#11. È sviluppato come parte del progetto OpenDNSSEC progettato per soddisfare i requisiti di OpenDNSSEC, ma può anche funzionare insieme ad altri prodotti crittografici grazie alla sua interfaccia PKCS#11. Questo articolo ti aiuterà a installare SoftHSM.

Come installare SoftHSM

È possibile installare SoftHSM in più modi. Per prima cosa, vediamo attraverso gestori di pacchetti come apt-get per Ubuntu e yum per CentOS.

SoftHSM dipende dalla libreria crittografica sottostante e dalla sua versione richiesta:

Botan 2.0.0 (Use at least 2.6.0 for better performance)
or
OpenSSL 1.0.0

Come installare SoftHSM su Ubuntu

Utilizzare i comandi seguenti per installare SoftHSM

# sudo apt-get install softhsm
Vecchia versione di SoftHSM

Se la versione di SoftHSM è vecchia e se hai bisogno dell'ultima versione, segui l'installazione di origine di seguito.

Come installare SoftHSM su CentOS

Usa YUM per installare SoftHSM

$ sudo yum install softhsm

Puoi anche scaricare il pacchetto rpm di SoftHSM e installarlo come di seguito:

$ wget http://mirror.centos.org/centos/7/os/x86_64/Packages/softhsm-2.1.0-3.el7.x86_64.rpm
$ sudo yum install softhsm-2.1.0-3.el7.x86_64.rpm -y
or
$ sudo rpm -Uvh softhsm-2.1.0-3.el7.x86_64.rpm

Come installare SoftHSM tramite la compilazione del codice sorgente

Assicurati di avere GNU Autotools (Autoconf, Automake, Libtool) per la creazione del software. Si consiglia inoltre di installare pkg-config in modo che lo script di configurazione possa trovare il software installato. Hai anche bisogno di libp11-kit-dev per installare SoftHSM come modulo PKCS#11 sul sistema.

Passaggio 1: Assicurati di aver installato i pacchetti automake, autoconf, libtool, pkg-config git

Passaggio 2: Scarica il pacchetto SoftHSM

# git clone https://github.com/opendnssec/SoftHSMv2.git
# cd SoftHSMv2

Passaggio 3: Configura lo script di installazione

$ ./configure

Segui se la libreria OpenSSL non ha supporto GOST

Passaggio 4: Compila

$ make

Passaggio 5: Installa SoftHSM

$ sudo make install

Come usare SoftHSM

Dopo aver installato SoftHSM, puoi accedervi tramite i comandi SoftHSM Utility come mostrato di seguito.

$ softhsm2-util

Per inizializzare il soft token, eseguire il comando seguente:

$ softhsm2-util --init-token --slot 0 --label "encryptionkey"

Durante l'inizializzazione del token software, ti verrà chiesto di impostare il PIN utente e il PIN SO. Il Pin utente viene utilizzato da un'applicazione per interagire con il token e il pin SO per reinizializzare il token. Quindi devi ricordare il pin che intendi impostare.

Il comando seguente elencherà gli slot:

$ softhsm2-util --show-slots
Available slots:
Slot 462451351
Slot info:
Description: SoftHSM slot ID 0x1b907297
Manufacturer ID: SoftHSM project
Hardware version: 2.5
Firmware version: 2.5
Token present: yes
Token info:
Manufacturer ID: SoftHSM project
Model: SoftHSM v2
Hardware version: 2.5
Firmware version: 2.5
Serial number: 360a5ad59b907297
Initialized: yes
User PIN init.: yes
Label: encryptionkey
Slot 1
Slot info:
Description: SoftHSM slot ID 0x1
Manufacturer ID: SoftHSM project
Hardware version: 2.5
Firmware version: 2.5
Token present: yes
Token info:
Manufacturer ID: SoftHSM project
Model: SoftHSM v2
Hardware version: 2.5
Firmware version: 2.5
Serial number:
Initialized: no
User PIN init.: no
Label:

Ecco fatto, SoftHSM è stato installato e configurato con successo. Possiamo ora comunicare con esso a livello di codice?

Per comunicare con SoftHSM, dobbiamo creare un file di configurazione che deve essere archiviato nella directory principale del progetto.

name = SoftHSM
library = /usr/local/lib/softhsm/libsofthsm2.so
slot = 462451351
attributes(generate, *, *) = {
   CKA_TOKEN = true
}
attributes(generate, CKO_CERTIFICATE, *) = {
   CKA_PRIVATE = false
}
attributes(generate, CKO_PUBLIC_KEY, *) = {
   CKA_PRIVATE = false
}
Sostituire lo slot

Devi sostituire l'ID slot con il tuo.

Lascia che ti guidi attraverso un programma Java per comunicare con SoftHSM. Il programma prenderà una stringa come input, la crittograferà e la decrittograferà di nuovo per noi.

package tg.blr;

import java.io.FileWriter;
import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.Key;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.Provider;
import java.security.Security;
import java.security.UnrecoverableKeyException;
import java.security.cert.CertificateException;
import java.util.Scanner;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;

import org.bouncycastle.jce.provider.BouncyCastleProvider;

public class SoftHsmTest {

private static final String TRANSFORMATION = "AES/ECB/PKCS5Padding";
public static String encodedString = new String();

static { 
Security.addProvider(new BouncyCastleProvider()); 
}

static byte[] decryptbytes;

public static void main(String[] args) {

System.out.println("Enter the text to be encrypted: ");
Scanner s = new Scanner(System.in);
String inputtext = s.nextLine();
s.close();

try {
String filePath = "/usr/local/lib/softhsm/libsofthsm2.so";
//To create softhsm.cfg
FileWriter fw = new FileWriter("softhsm.cfg");
fw.write("name = SoftHSM\n" + "library = " + filePath);
//Change the slot ID
fw.write("\n slot = 462451351\n" + "attributes(generate, *, *) = {\n");
fw.write("\t CKA_TOKEN = true\n}\n" + "attributes(generate, CKO_CERTIFICATE, *) = {\n");
fw.write("\t CKA_PRIVATE = false\n}\n" + "attributes(generate, CKO_PUBLIC_KEY, *) = {\n");
fw.write("\t CKA_PRIVATE = false\n}\n");
fw.close();
} catch (IOException e2) {
e2.printStackTrace();
}
String pkcs11ConfigData = "softhsm.cfg";
Provider pkcs11Provider = Security.getProvider("SunPKCS11");
pkcs11Provider = pkcs11Provider.configure(pkcs11ConfigData);

if (-1 == Security.addProvider(pkcs11Provider)) {
throw new RuntimeException("could not add security provider");
} else {
System.out.println("provider initialized !!!");
}

Security.addProvider(pkcs11Provider);
//User pin created while initializing soft token
char[] pin = "sukumar123".toCharArray();
KeyStore keyStore;
try {
keyStore = KeyStore.getInstance("PKCS11", pkcs11Provider);
keyStore.load(null, pin); 
SecretKeySpec secretKeySpec = new SecretKeySpec("0123456789ABCDEF".getBytes(), 0, 16, "AES");
Key key = new SecretKeySpec(secretKeySpec.getEncoded(), 0, 16, "AES");
keyStore.setKeyEntry("AA", key, "sukumar123".toCharArray(), null);
keyStore.store(null);
SecretKey key1 = (SecretKey) keyStore.getKey("AA", "sukumar123".toCharArray());
System.out.println("the algorithm: "+key1.getAlgorithm()+", the key: "+key1.toString()+", format: "+key1.serialVersionUID);

String encryptedString = performEncryption(key1, inputtext);

System.out.println("encryptedString : "+encryptedString);

performDecryption(key1, encryptedString);

} catch (KeyStoreException e) {
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (CertificateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (UnrecoverableKeyException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}


private static String performEncryption(Key secretKey, String inputtext) throws Exception {
String encryptedText = new String();
Cipher cipher;
try {
cipher = Cipher.getInstance(TRANSFORMATION);
cipher.init(Cipher.ENCRYPT_MODE, secretKey);
byte[] cipherText = cipher.doFinal(inputtext.getBytes("utf-8"));
encryptedText = java.util.Base64.getEncoder().encodeToString(cipherText);
} catch (NoSuchAlgorithmException e) {
System.out.println("No such algorithm exception");
e.printStackTrace();
} catch (NoSuchPaddingException e) {
System.out.println("No such padding exception");
e.printStackTrace();
} catch (InvalidKeyException e) {
System.out.println("Invalid key exception");
e.printStackTrace();
} catch (IllegalBlockSizeException e) {
System.out.println("Illegal block size exception");
e.printStackTrace();
} catch (BadPaddingException e) {
System.out.println("Bad padding exception");
e.printStackTrace();
} finally {

}
return encryptedText;
}


private static void performDecryption(Key key, String encryptedString) throws Exception {
Key secretKey = key;
Cipher cipher;
try {
cipher = Cipher.getInstance(TRANSFORMATION);
cipher.init(Cipher.DECRYPT_MODE, secretKey);
byte[] deciphered = cipher.doFinal(java.util.Base64.getDecoder().decode(encryptedString));
System.out.println("decrypted text: "+new String(deciphered));
} catch (NoSuchAlgorithmException e) {
System.out.println("No such algorithm exception");
e.printStackTrace();
} catch (NoSuchPaddingException e) {
System.out.println("No such padding exception");
e.printStackTrace();
} catch (InvalidKeyException e) {
System.out.println("Invalid key exception");
e.printStackTrace();
} catch (IllegalBlockSizeException e) {
System.out.println("Illegal block size exception");
e.printStackTrace();
} catch (BadPaddingException e) {
System.out.println("Bad padding exception");
e.printStackTrace();
} finally {

}
}
}

Risultato di esempio:

Se sei bloccato con un errore:Eccezione dimensione blocco illegale – CKR_ENCRYPTED_DATA_LEN_RANGE, allora ecco la soluzione per risolvere lo stesso.


Linux
  1. Come installare Proxychain e accedere a Internet tramite Proxy in CentOS?

  2. Debian – Installa Java Jdk e Jre su Debian 8?

  3. Rilasciato LibreOffice 7.0:installalo tramite PPA su Ubuntu e Mint

  4. Come rimuovere la vecchia versione di Java e installare la nuova versione

  5. Consentire al processo non root di collegarsi alla porta 80 e 443?

Come installare Oracle Java 8 su Ubuntu 16.10 tramite PPA

Come installare Java su Ubuntu e Linux Mint

Come installare Java 16 in Rocky Linux e AlmaLinux

Come installare e gestire Java su Debian 11

Come installare Tomcat e Java su CentOS 8

Accesso remoto a Windows 10 tramite Ubuntu Linux e Vise Versa