GNU/Linux >> Tutoriels Linux >  >> Linux

Installez SoftHSM et accédez-y via le programme Java

SoftHSM est une implémentation logicielle de HSM (Hardware Security Module) qui vise à exécuter toutes les fonctions qu'un HSM approprié exécuterait sans fournir les protections de sécurité matérielles offertes par un vrai HSM. Si vous êtes un utilisateur qui n'est pas disposé à investir dans un nouveau périphérique matériel, vous pouvez utiliser SoftHSM qui est un magasin cryptographique accessible via une interface PKCS#11. Il est développé dans le cadre du projet OpenDNSSEC conçu pour répondre aux exigences d'OpenDNSSEC, mais peut également fonctionner avec d'autres produits cryptographiques grâce à son interface PKCS#11. Cet article vous aidera à installer SoftHSM.

Comment installer SoftHSM

Vous pouvez installer SoftHSM de plusieurs façons. Voyons d'abord à travers les gestionnaires de paquets tels que apt-get pour Ubuntu et yum pour CentOS.

SoftHSM dépend de la bibliothèque cryptographique ci-dessous et de sa version requise :

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

Comment installer SoftHSM sur Ubuntu

Utilisez les commandes ci-dessous pour installer SoftHSM

# sudo apt-get install softhsm
Ancienne version de SoftHSM

Si la version de SoftHSM est ancienne et si vous avez besoin de la dernière version, suivez l'installation source ci-dessous.

Comment installer SoftHSM sur CentOS

Utilisez YUM pour installer SoftHSM

$ sudo yum install softhsm

Vous pouvez également télécharger le package RPM SoftHSM et l'installer comme ci-dessous :

$ 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

Comment installer SoftHSM via la compilation source

Assurez-vous d'avoir GNU Autotools (Autoconf, Automake, Libtool) pour construire le logiciel. Il est également recommandé d'installer pkg-config afin que le script de configuration puisse trouver le logiciel installé. Vous avez également besoin de libp11-kit-dev pour installer SoftHSM en tant que module PKCS#11 sur le système.

Étape 1 : Assurez-vous que les packages automake, autoconf, libtool, pkg-config git sont installés

Étape 2 : Télécharger le pack SoftHSM

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

Étape 3 : Configurer le script d'installation

$ ./configure

Suivez si vous rencontrez que la bibliothèque OpenSSL n'a pas de support GOST

Étape 4 : Compiler

$ make

Étape 5 : Installer SoftHSM

$ sudo make install

Comment utiliser SoftHSM

Après avoir installé SoftHSM, vous pouvez y accéder via les commandes de l'utilitaire SoftHSM, comme indiqué ci-dessous.

$ softhsm2-util

Pour initialiser le jeton logiciel, exécutez la commande ci-dessous :

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

Lors de l'initialisation du jeton logiciel, il vous sera demandé de définir le code PIN utilisateur et le code PIN SO. Le code utilisateur est utilisé par une application pour interagir avec le jeton et la broche SO pour réinitialiser le jeton. Vous devez donc vous souvenir de la broche que vous allez définir.

La commande ci-dessous listera les slots :

$ 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:

Ça y est, le SoftHSM a été installé et configuré avec succès. Allons-nous maintenant communiquer avec lui par programmation ?

Afin de communiquer avec SoftHSM, nous devons créer un fichier de configuration qui doit être stocké dans le répertoire racine du projet.

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
}
Remplacer l'emplacement

Vous devez remplacer l'ID d'emplacement par le vôtre.

Laissez-moi vous présenter un programme Java pour communiquer avec SoftHSM. Le programme prendra une chaîne en entrée, la chiffrera et la déchiffrera pour nous.

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 {

}
}
}

Exemple de résultat :

Si vous êtes bloqué avec une erreur :Exception de taille de bloc illégale - CKR_ENCRYPTED_DATA_LEN_RANGE, alors voici la solution pour résoudre le même problème.


Linux
  1. Comment installer Proxychains et accéder à Internet via Proxy dans CentOS ?

  2. Debian – Installer Java Jdk et Jre sur Debian 8 ?

  3. Sortie de LibreOffice 7.0 - Installez-le via PPA sur Ubuntu et Mint

  4. Comment installer et gérer les versions Java sur Rocky Linux 8

  5. Autoriser le processus non root à se lier aux ports 80 et 443 ?

Comment installer Oracle Java 8 sur Ubuntu 16.10 via PPA

Comment installer Java sur Ubuntu et Linux Mint

Comment installer Java 16 dans Rocky Linux et AlmaLinux

Comment installer et gérer Java sur Debian 11

Comment installer Tomcat et Java sur CentOS 8

Accès à distance à Windows 10 via Ubuntu Linux et Vise Versa