Java 加密 - 快速指南



Java 加密 - 簡介

密碼學是設計能夠提供資訊安全的密碼系統的藝術和科學。

密碼學處理數字資料的實際保護。它指的是基於提供基本資訊安全服務的數學演算法的設計機制。您可以將密碼學視為建立了一個包含安全應用程式中不同技術的龐大工具包。

什麼是密碼分析?

破解密文的藝術和科學被稱為密碼分析。

密碼分析是密碼學的姊妹分支,它們共同存在。密碼過程產生用於傳輸或儲存的密文。它涉及研究密碼機制以試圖破解它們。密碼分析也用於新密碼技術的設計中,以測試其安全性。

密碼學原語

密碼學原語只不過是密碼學中的工具和技術,可以選擇性地使用它們來提供一組所需的安全性服務 -

  • 加密
  • 雜湊函式
  • 訊息認證碼(MAC)
  • 數字簽名

Java中的密碼學

Java 密碼體系結構 (JCA) 是一組 API,用於實現現代密碼學的概念,例如數字簽名、訊息摘要、證書、加密、金鑰生成和管理以及安全隨機數生成等。

使用 JCA,開發人員可以構建整合安全性的應用程式。

為了在您的應用程式中整合安全性,而不是依賴於複雜的安全性演算法,您可以輕鬆地呼叫 JCA 中提供的相應 API 以獲取所需的服務。

Java 加密 - 訊息摘要

雜湊函式非常有用,幾乎出現在所有資訊安全應用程式中。

雜湊函式是一種數學函式,它將數值輸入值轉換為另一個壓縮的數值值。雜湊函式的輸入長度任意,但輸出始終是固定長度的。

雜湊函式返回的值稱為訊息摘要或簡稱為雜湊值。下圖說明了雜湊函式。

Message Digest

Java 提供了一個名為MessageDigest的類,它屬於包 java.security。此類支援 SHA-1、SHA 256、MD5 等演算法,用於將任意長度的訊息轉換為訊息摘要。

要將給定訊息轉換為訊息摘要,請按照以下步驟操作 -

步驟 1:建立 MessageDigest 物件

MessageDigest 類提供了一個名為getInstance()的方法。此方法接受一個指定要使用的演算法名稱的 String 變數,並返回一個實現指定演算法的 MessageDigest 物件。

使用getInstance()方法建立 MessageDigest 物件,如下所示。

MessageDigest md = MessageDigest.getInstance("SHA-256");

步驟 2:將資料傳遞到建立的 MessageDigest 物件

建立訊息摘要物件後,您需要將訊息/資料傳遞給它。您可以使用MessageDigest類的update()方法來執行此操作,此方法接受表示訊息的位元組陣列並將其新增到上面建立的 MessageDigest 物件中。

md.update(msg.getBytes());

步驟 3:生成訊息摘要

您可以使用MessageDigest類的digest()方法生成訊息摘要,此方法計算當前物件上的雜湊函式,並以位元組陣列的形式返回訊息摘要。

使用 digest 方法生成訊息摘要。

byte[] digest = md.digest();

示例

以下是一個示例,它從檔案中讀取資料並生成訊息摘要並列印它。

import java.security.MessageDigest;
import java.util.Scanner;

public class MessageDigestExample {
   public static void main(String args[]) throws Exception{
      //Reading data from user
      Scanner sc = new Scanner(System.in);
      System.out.println("Enter the message");
      String message = sc.nextLine();
	  
      //Creating the MessageDigest object  
      MessageDigest md = MessageDigest.getInstance("SHA-256");

      //Passing data to the created MessageDigest Object
      md.update(message.getBytes());
      
      //Compute the message digest
      byte[] digest = md.digest();      
      System.out.println(digest);  
     
      //Converting the byte array in to HexString format
      StringBuffer hexString = new StringBuffer();
      
      for (int i = 0;i<digest.length;i++) {
         hexString.append(Integer.toHexString(0xFF & digest[i]));
      }
      System.out.println("Hex format : " + hexString.toString());     
   }
}

輸出

以上程式生成以下輸出 -

Enter the message
Hello how are you
[B@55f96302
Hex format: 2953d33828c395aebe8225236ba4e23fa75e6f13bd881b9056a3295cbd64d3

Java 加密 - 建立MAC

MAC(Message Authentication Code)演算法是一種對稱金鑰加密技術,用於提供訊息認證。為了建立 MAC 過程,傳送方和接收方共享一個對稱金鑰 K。

本質上,MAC 是對傳送的訊息生成的加密校驗和,該校驗和與訊息一起傳送以確保訊息認證。

以下插圖描述了使用 MAC 進行身份驗證的過程 -

Creating MAC

在 Java 中,javax.crypto包的Mac類提供了訊息認證碼的功能。請按照以下步驟使用此類建立訊息認證碼。

步驟 1:建立 KeyGenerator 物件

KeyGenerator類提供getInstance()方法,該方法接受一個表示所需金鑰生成演算法的 String 變數,並返回一個生成秘密金鑰的KeyGenerator物件。

使用getInstance()方法建立KeyGenerator物件,如下所示。

//Creating a KeyGenerator object
KeyGenerator keyGen = KeyGenerator.getInstance("DES");

步驟 2:建立 SecureRandom 物件

java.Security包的SecureRandom類提供了一個強大的隨機數生成器,用於在 Java 中生成隨機數。例項化此類,如下所示。

//Creating a SecureRandom object
SecureRandom secRandom = new SecureRandom();

步驟 3:初始化 KeyGenerator

KeyGenerator類提供了一個名為init()的方法,此方法接受SecureRandom物件並初始化當前KeyGenerator

使用此方法初始化上一步中建立的 KeyGenerator 物件。

//Initializing the KeyGenerator
keyGen.init(secRandom);

步驟 4:生成金鑰

使用KeyGenerator類的generateKey()方法生成金鑰,如下所示。

//Creating/Generating a key
Key key = keyGen.generateKey();

步驟 5:初始化 Mac 物件

Mac 類的init()方法接受一個 Key 物件並使用給定金鑰初始化當前 Mac 物件。

//Initializing the Mac object
mac.init(key);

步驟 6:完成 mac 操作

Mac 類的doFinal()方法用於完成 Mac 操作。將所需資料以位元組陣列的形式傳遞給此方法並完成操作,如下所示。

//Computing the Mac
String msg = new String("Hi how are you");
byte[] bytes = msg.getBytes();
byte[] macResult = mac.doFinal(bytes);

示例

以下示例演示瞭如何使用 JCA 生成訊息認證碼 (MAC)。在這裡,我們取一個簡單的訊息“Hi how are you”,併為該訊息生成一個 Mac。

import java.security.Key;
import java.security.SecureRandom;

import javax.crypto.KeyGenerator;
import javax.crypto.Mac;

public class MacSample {
   public static void main(String args[]) throws Exception{
      //Creating a KeyGenerator object
      KeyGenerator keyGen = KeyGenerator.getInstance("DES");

      //Creating a SecureRandom object
      SecureRandom secRandom = new SecureRandom();

      //Initializing the KeyGenerator
      keyGen.init(secRandom);

      //Creating/Generating a key
      Key key = keyGen.generateKey();	 

      //Creating a Mac object
      Mac mac = Mac.getInstance("HmacSHA256");

      //Initializing the Mac object
      mac.init(key);

      //Computing the Mac
      String msg = new String("Hi how are you");
      byte[] bytes = msg.getBytes();      
      byte[] macResult = mac.doFinal(bytes);

      System.out.println("Mac result:");
      System.out.println(new String(macResult));     
   }
}

輸出

以上程式將生成以下輸出 -

Mac result:
HÖ„^ǃÎ_Utbh…?š_üzØSSÜh_ž_œa0ŽV?

Java 加密 - 金鑰

密碼系統是加密技術的實現及其伴隨的基礎設施,用於提供資訊安全服務。密碼系統也稱為密碼系統

基本密碼系統的各個組成部分是明文、加密演算法、密文、解密演算法、加密金鑰和解密金鑰。

其中,

  • 加密金鑰是傳送方已知的值。傳送方將加密金鑰與明文一起輸入加密演算法,以計算密文。

  • 解密金鑰是接收方已知的值。解密金鑰與加密金鑰相關,但不總是與其相同。接收方將解密金鑰與密文一起輸入解密演算法,以計算明文。

從根本上講,根據加密解密演算法的型別,金鑰/密碼系統有兩種型別。

對稱金鑰加密

使用相同的金鑰加密和解密資訊的加密過程稱為對稱金鑰加密。

對稱密碼系統的研究稱為對稱密碼學。對稱密碼系統有時也稱為秘密金鑰密碼系統

以下是一些常見的對稱金鑰加密示例 -

  • 數字加密標準 (DES)
  • 三重 DES (3DES)
  • IDEA
  • BLOWFISH

非對稱金鑰加密

使用不同的金鑰加密和解密資訊的加密過程稱為非對稱金鑰加密。雖然金鑰不同,但它們在數學上是相關的,因此,透過解密密文檢索明文是可行的。

Java 加密 - 儲存金鑰

使用的/生成的金鑰和證書儲存在稱為金鑰庫的資料庫中。預設情況下,此資料庫儲存在一個名為.keystore的檔案中。

您可以使用java.security包的KeyStore類訪問此資料庫的內容。它管理三個不同的條目,即 PrivateKeyEntry、SecretKeyEntry、TrustedCertificateEntry。

  • PrivateKeyEntry
  • SecretKeyEntry
  • TrustedCertificateEntry

將金鑰儲存在金鑰庫中

在本節中,我們將學習如何將金鑰儲存在金鑰庫中。要將金鑰儲存在金鑰庫中,請按照以下步驟操作。

步驟 1:建立 KeyStore 物件

java.security包的KeyStore類的getInstance()方法接受一個表示金鑰庫型別的字串值,並返回一個 KeyStore 物件。

使用getInstance()方法建立 KeyStore 類的物件,如下所示。

//Creating the KeyStore object
KeyStore keyStore = KeyStore.getInstance("JCEKS");

步驟 2:載入 KeyStore 物件

KeyStore 類的load()方法接受一個表示金鑰庫檔案的 FileInputStream 物件和一個指定 KeyStore 密碼的 String 引數。

通常,KeyStore 儲存在名為cacerts的檔案中,位於C:/Program Files/Java/jre1.8.0_101/lib/security/位置,其預設密碼為changeit,使用load()方法載入它,如下所示。

//Loading the KeyStore object
char[] password = "changeit".toCharArray();
String path = "C:/Program Files/Java/jre1.8.0_101/lib/security/cacerts";
java.io.FileInputStream fis = new FileInputStream(path);
keyStore.load(fis, password);

步驟 3:建立 KeyStore.ProtectionParameter 物件

例項化 KeyStore.ProtectionParameter,如下所示。

//Creating the KeyStore.ProtectionParameter object
KeyStore.ProtectionParameter protectionParam = new KeyStore.PasswordProtection(password);

步驟 4:建立 SecretKey 物件

透過例項化其子類SecretKeySpec來建立SecretKey(介面)物件。在例項化時,您需要將密碼和演算法作為引數傳遞給其建構函式,如下所示。

//Creating SecretKey object
SecretKey mySecretKey = new SecretKeySpec(new String(keyPassword).getBytes(), "DSA");

步驟 5:建立 SecretKeyEntry 物件

透過傳遞在上面步驟中建立的SecretKey物件,建立SecretKeyEntry類的物件,如下所示。

//Creating SecretKeyEntry object
KeyStore.SecretKeyEntry secretKeyEntry = new KeyStore.SecretKeyEntry(mySecretKey);

步驟 6:將條目設定為 KeyStore

KeyStore類的setEntry()方法接受一個表示金鑰庫條目別名的字串引數、一個SecretKeyEntry物件、一個ProtectionParameter物件,並將條目儲存在給定的別名下。

使用setEntry()方法將條目設定為金鑰庫,如下所示。

//Set the entry to the keystore
keyStore.setEntry("secretKeyAlias", secretKeyEntry, protectionParam);

示例

以下示例將金鑰儲存到“cacerts”檔案(Windows 10 作業系統)中存在的金鑰庫中。

import java.io.FileInputStream;
import java.security.KeyStore;

import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;

public class StoringIntoKeyStore{
   public static void main(String args[]) throws Exception {
      //Creating the KeyStore object
      KeyStore keyStore = KeyStore.getInstance("JCEKS");

      //Loading the KeyStore object
      char[] password = "changeit".toCharArray();
      String path = "C:/Program Files/Java/jre1.8.0_101/lib/security/cacerts";
      java.io.FileInputStream fis = new FileInputStream(path);
      keyStore.load(fis, password);
      
      //Creating the KeyStore.ProtectionParameter object
      KeyStore.ProtectionParameter protectionParam = new KeyStore.PasswordProtection(password);

      //Creating SecretKey object
      SecretKey mySecretKey = new SecretKeySpec("myPassword".getBytes(), "DSA");
      
      //Creating SecretKeyEntry object
      KeyStore.SecretKeyEntry secretKeyEntry = new KeyStore.SecretKeyEntry(mySecretKey);
      keyStore.setEntry("secretKeyAlias", secretKeyEntry, protectionParam);

      //Storing the KeyStore object
      java.io.FileOutputStream fos = null;
      fos = new java.io.FileOutputStream("newKeyStoreName");
      keyStore.store(fos, password);
      System.out.println("data stored");
   }
}

輸出

以上程式生成以下輸出 -

System.out.println("data stored");

Java 加密 - 檢索金鑰

在本章中,我們將學習如何使用 Java 加密從金鑰庫中檢索金鑰。

要從金鑰庫中檢索金鑰,請按照以下步驟操作。

步驟 1:建立 KeyStore 物件

java.security包的KeyStore類的getInstance()方法接受一個表示金鑰庫型別的字串值,並返回一個 KeyStore 物件。

使用此方法建立 KeyStore 類的物件,如下所示。

//Creating the KeyStore object
KeyStore keyStore = KeyStore.getInstance("JCEKS");

步驟 2:載入 KeyStore 物件

KeyStore 類的load()方法接受一個表示金鑰庫檔案的FileInputStream物件和一個指定 KeyStore 密碼的字串引數。

通常,KeyStore 儲存在名為cacerts的檔案中,位於C:/Program Files/Java/jre1.8.0_101/lib/security/位置,其預設密碼為changeit,使用load()方法載入它,如下所示。

//Loading the KeyStore object
char[] password = "changeit".toCharArray();
String path = "C:/Program Files/Java/jre1.8.0_101/lib/security/cacerts";
java.io.FileInputStream fis = new FileInputStream(path);
keyStore.load(fis, password);

步驟 3:建立 KeyStore.ProtectionParameter 物件

例項化 KeyStore.ProtectionParameter,如下所示。

//Creating the KeyStore.ProtectionParameter object
KeyStore.ProtectionParameter protectionParam = new KeyStore.PasswordProtection(password);

步驟 4:建立 SecretKey 物件

透過例項化其子類SecretKeySpec來建立SecretKey(介面)物件。在例項化時,您需要將密碼和演算法作為引數傳遞給其建構函式,如下所示。

//Creating SecretKey object
SecretKey mySecretKey = new SecretKeySpec(new String(keyPassword).getBytes(), "DSA");

步驟 5:建立 SecretKeyEntry 物件

透過傳遞在上面步驟中建立的SecretKey物件,建立SecretKeyEntry類的物件,如下所示。

//Creating SecretKeyEntry object
KeyStore.SecretKeyEntry secretKeyEntry = new KeyStore.SecretKeyEntry(mySecretKey);

步驟 6:將條目設定為 KeyStore

KeyStore類的setEntry()方法接受一個表示金鑰庫條目別名的字串引數、一個SecretKeyEntry物件、一個ProtectionParameter物件,並將條目儲存在給定的別名下。

使用setEntry()方法將條目設定為金鑰庫,如下所示。

//Set the entry to the keystore
keyStore.setEntry("secretKeyAlias", secretKeyEntry, protectionParam);

步驟 7:建立 KeyStore.SecretKeyEntry 物件

KeyStore類的getEntry()方法接受一個別名(字串引數)和一個ProtectionParameter類的物件作為引數,並返回一個KeyStoreEntry物件,然後您可以將其轉換為KeyStore.SecretKeyEntry物件。

透過將所需金鑰的別名和在前面步驟中建立的保護引數物件傳遞給getEntry()方法,建立KeyStore.SecretKeyEntry類的物件,如下所示。

//Creating the KeyStore.SecretKeyEntry object
KeyStore.SecretKeyEntry secretKeyEnt = (KeyStore.SecretKeyEntry)keyStore.getEntry("secretKeyAlias", protectionParam);

步驟 8:建立檢索到的條目的金鑰物件

SecretKeyEntry類的getSecretKey()方法返回一個SecretKey物件。使用此方法建立SecretKey物件,如下所示。

//Creating SecretKey object
SecretKey mysecretKey = secretKeyEnt.getSecretKey();      
System.out.println(mysecretKey);

示例

以下示例演示瞭如何從金鑰庫中檢索金鑰。在這裡,我們將金鑰儲存在“cacerts”檔案(Windows 10 作業系統)中的金鑰庫中,檢索它,並顯示其某些屬性,例如用於生成金鑰的演算法和檢索金鑰的格式。

import java.io.FileInputStream;
import java.security.KeyStore;
import java.security.KeyStore.ProtectionParameter;
import java.security.KeyStore.SecretKeyEntry;

import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;

public class RetrievingFromKeyStore{
   public static void main(String args[]) throws Exception{
      //Creating the KeyStore object
      KeyStore keyStore = KeyStore.getInstance("JCEKS");

      //Loading the the KeyStore object
      char[] password = "changeit".toCharArray();
      java.io.FileInputStream fis = new FileInputStream(
         "C:/Program Files/Java/jre1.8.0_101/lib/security/cacerts");
      
      keyStore.load(fis, password);
      
      //Creating the KeyStore.ProtectionParameter object
      ProtectionParameter protectionParam = new KeyStore.PasswordProtection(password);

      //Creating SecretKey object
      SecretKey mySecretKey = new SecretKeySpec("myPassword".getBytes(), "DSA");
      
      //Creating SecretKeyEntry object
      SecretKeyEntry secretKeyEntry = new SecretKeyEntry(mySecretKey);
      keyStore.setEntry("secretKeyAlias", secretKeyEntry, protectionParam);

      //Storing the KeyStore object
      java.io.FileOutputStream fos = null;
      fos = new java.io.FileOutputStream("newKeyStoreName");
      keyStore.store(fos, password);
      
      //Creating the KeyStore.SecretKeyEntry object
      SecretKeyEntry secretKeyEnt = (SecretKeyEntry)keyStore.getEntry("secretKeyAlias", protectionParam);

      //Creating SecretKey object
      SecretKey mysecretKey = secretKeyEnt.getSecretKey();      
      System.out.println("Algorithm used to generate key : "+mysecretKey.getAlgorithm());   
      System.out.println("Format used for the key: "+mysecretKey.getFormat());
   }
}

輸出

以上程式生成以下輸出 -

Algorithm used to generate key: DSA
Format of the key: RAW

Java 加密 - KeyGenerator

Java 提供了KeyGenerator類,此類用於生成金鑰和此類的可重用物件。

要使用 KeyGenerator 類生成金鑰,請按照以下步驟操作。

步驟 1:建立 KeyGenerator 物件

KeyGenerator類提供getInstance()方法,該方法接受一個表示所需金鑰生成演算法的字串變數,並返回一個生成金鑰的KeyGenerator物件。

使用getInstance()方法建立KeyGenerator物件,如下所示。

//Creating a KeyGenerator object
KeyGenerator keyGen = KeyGenerator.getInstance("DES");

步驟 2:建立 SecureRandom 物件

java.Security包的SecureRandom類提供了一個強大的隨機數生成器,用於在 Java 中生成隨機數。例項化此類,如下所示。

//Creating a SecureRandom object
SecureRandom secRandom = new SecureRandom();

步驟 3:初始化 KeyGenerator

KeyGenerator類提供了一個名為init()的方法,此方法接受SecureRandom物件並初始化當前KeyGenerator

使用init()方法初始化在前面步驟中建立的KeyGenerator物件。

//Initializing the KeyGenerator
keyGen.init(secRandom);

示例

以下示例演示了使用javax.crypto包的KeyGenerator類生成金鑰。

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;

import java.security.Key;
import java.security.SecureRandom;

public class KeyGeneratorExample {
   public static void main(String args[]) throws Exception{
      //Creating a KeyGenerator object
      KeyGenerator keyGen = KeyGenerator.getInstance("DES");
      
      //Creating a SecureRandom object
      SecureRandom secRandom = new SecureRandom();
      
      //Initializing the KeyGenerator
      keyGen.init(secRandom);
      
      //Creating/Generating a key
      Key key = keyGen.generateKey();
      
      System.out.println(key);      
      Cipher cipher = Cipher.getInstance("DES/ECB/PKCS5Padding");      
      cipher.init(cipher.ENCRYPT_MODE, key);      

      String msg = new String("Hi how are you");
      byte[] bytes = cipher.doFinal(msg.getBytes());      
      System.out.println(bytes);      
   }
}

輸出

以上程式生成以下輸出 -

com.sun.crypto.provider.DESKey@18629
[B@2ac1fdc4

Java 加密 - KeyPairGenerator

Java 提供了KeyPairGenerator類。此類用於生成公鑰和私鑰對。要使用KeyPairGenerator類生成金鑰,請按照以下步驟操作。

步驟 1:建立一個 KeyPairGenerator 物件

KeyPairGenerator類提供getInstance()方法,該方法接受一個表示所需金鑰生成演算法的字串變數,並返回一個生成金鑰的KeyPairGenerator物件。

使用getInstance()方法建立KeyPairGenerator物件,如下所示。

//Creating KeyPair generator object
KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance("DSA");

步驟 2:初始化 KeyPairGenerator 物件

KeyPairGenerator類提供了一個名為initialize()的方法,此方法用於初始化金鑰對生成器。此方法接受一個表示金鑰大小的整數值。

使用此方法初始化在前面步驟中建立的KeyPairGenerator物件,如下所示。

//Initializing the KeyPairGenerator
keyPairGen.initialize(2048);

步驟 3:生成 KeyPairGenerator

您可以使用KeyPairGenerator類的generateKeyPair()方法生成KeyPair。使用此方法生成金鑰對,如下所示。

//Generate the pair of keys
KeyPair pair = keyPairGen.generateKeyPair();

步驟 4:獲取私鑰/公鑰

您可以使用getPrivate()方法從生成的KeyPair物件中獲取私鑰,如下所示。

//Getting the private key from the key pair
PrivateKey privKey = pair.getPrivate();

您可以使用getPublic()方法從生成的KeyPair物件中獲取公鑰,如下所示。

//Getting the public key from the key pair
PublicKey publicKey = pair.getPublic();

示例

以下示例演示了使用javax.crypto包的KeyPairGenerator類生成金鑰。

import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.PrivateKey;
import java.security.PublicKey;

public class KeyPairGenertor {
   public static void main(String args[]) throws Exception{
      //Creating KeyPair generator object
      KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance("DSA");
      
      //Initializing the KeyPairGenerator
      keyPairGen.initialize(2048);
      
      //Generating the pair of keys
      KeyPair pair = keyPairGen.generateKeyPair();
      
      //Getting the private key from the key pair
      PrivateKey privKey = pair.getPrivate();   
      
      //Getting the public key from the key pair
      PublicKey publicKey = pair.getPublic(); 
      System.out.println("Keys generated");
   }
}

輸出

以上程式生成以下輸出 -

Keys generated

Java 加密 - 建立簽名

數字簽名允許我們驗證簽名者的身份、日期和時間,並對訊息內容進行身份驗證。它還包括用於其他功能的身份驗證功能。

Creating Signature

數字簽名的優勢

在本節中,我們將瞭解需要使用數字簽名的不同原因。實施數字簽名到通訊中有幾個原因:

身份驗證

數字簽名有助於對訊息來源進行身份驗證。例如,如果銀行的分支機構向中央辦公室傳送訊息,請求更改某個賬戶的餘額。如果中央辦公室無法驗證該訊息是否來自授權的來源,則對該請求採取行動可能是嚴重的錯誤。

完整性

訊息一旦簽名,任何對訊息的更改都會使簽名無效。

不可否認性

透過此屬性,任何已簽名某些資訊的人員日後都不能否認已簽名該資訊。

建立數字簽名

現在讓我們學習如何建立數字簽名。您可以按照以下步驟使用 Java 建立數字簽名。

步驟 1:建立一個 KeyPairGenerator 物件

KeyPairGenerator類提供getInstance()方法,該方法接受一個表示所需金鑰生成演算法的字串變數,並返回一個生成金鑰的KeyPairGenerator物件。

使用getInstance()方法建立KeyPairGenerator物件,如下所示。

//Creating KeyPair generator object
KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance("DSA");

步驟 2:初始化 KeyPairGenerator 物件

KeyPairGenerator類提供了一個名為initialize()的方法,此方法用於初始化金鑰對生成器。此方法接受一個表示金鑰大小的整數值。

使用initialize()方法初始化在前面步驟中建立的KeyPairGenerator物件,如下所示。

//Initializing the KeyPairGenerator
keyPairGen.initialize(2048);

步驟 3:生成 KeyPairGenerator

您可以使用generateKeyPair()方法生成KeyPair。使用generateKeyPair()方法生成金鑰對,如下所示。

//Generate the pair of keys
KeyPair pair = keyPairGen.generateKeyPair();

步驟 4:從對中獲取私鑰

您可以使用getPrivate()方法從生成的KeyPair物件中獲取私鑰。

使用getPrivate()方法獲取私鑰,如下所示。

//Getting the private key from the key pair
PrivateKey privKey = pair.getPrivate();   

步驟 5:建立一個簽名物件

Signature類的getInstance()方法接受一個表示所需簽名演算法的字串引數,並返回相應的Signature物件。

使用getInstance()方法建立Signature類的物件。

//Creating a Signature object
Signature sign = Signature.getInstance("SHA256withDSA");

步驟 6:初始化簽名物件

Signature類的initSign()方法接受一個PrivateKey物件並初始化當前的Signature物件。

使用initSign()方法初始化在前面步驟中建立的Signature物件,如下所示。

//Initialize the signature
sign.initSign(privKey);

步驟 7:將資料新增到簽名物件

Signature類的update()方法接受一個表示要簽名或驗證的資料的位元組陣列,並使用給定的資料更新當前物件。

透過將要簽名的資料以位元組陣列的形式傳遞給update()方法,更新初始化的Signature物件,如下所示。

byte[] bytes = "Hello how are you".getBytes();      

//Adding data to the signature
sign.update(bytes);

步驟 8:計算簽名

Signature類的sign()方法返回更新資料的簽名位元組。

使用sign()方法計算簽名,如下所示。

//Calculating the signature
byte[] signature = sign.sign();

示例

以下 Java 程式接受使用者輸入的訊息,併為給定訊息生成數字簽名。

import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.PrivateKey;
import java.security.Signature;
import java.util.Scanner;

public class CreatingDigitalSignature {
   public static void main(String args[]) throws Exception {
      //Accepting text from user
      Scanner sc = new Scanner(System.in);
      System.out.println("Enter some text");
      String msg = sc.nextLine();
      
      //Creating KeyPair generator object
      KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance("DSA");
      
      //Initializing the key pair generator
      keyPairGen.initialize(2048);
      
      //Generate the pair of keys
      KeyPair pair = keyPairGen.generateKeyPair();
      
      //Getting the private key from the key pair
      PrivateKey privKey = pair.getPrivate();
      
      //Creating a Signature object
      Signature sign = Signature.getInstance("SHA256withDSA");
      
      //Initialize the signature
      sign.initSign(privKey);
      byte[] bytes = "msg".getBytes();
      
      //Adding data to the signature
      sign.update(bytes);
      
      //Calculating the signature
      byte[] signature = sign.sign();
      
      //Printing the signature
      System.out.println("Digital signature for given text: "+new String(signature, "UTF8"));
   }
}

輸出

以上程式生成以下輸出 -

Enter some text
Hi how are you
Digital signature for given text: 0=@gRD???-?.???? /yGL?i??a!?

Java 加密 - 驗證簽名

您可以使用 Java 建立數字簽名並按照以下步驟驗證它。

步驟 1:建立一個 KeyPairGenerator 物件

KeyPairGenerator類提供getInstance()方法,該方法接受一個表示所需金鑰生成演算法的字串變數,並返回一個生成金鑰的KeyPairGenerator物件。

使用getInstance()方法建立KeyPairGenerator物件,如下所示。

//Creating KeyPair generator object
KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance("DSA");

步驟 2:初始化 KeyPairGenerator 物件

KeyPairGenerator類提供了一個名為initialize()的方法。此方法用於初始化金鑰對生成器。此方法接受一個表示金鑰大小的整數值。

使用initialize()方法初始化在前面步驟中建立的KeyPairGenerator物件,如下所示。

//Initializing the KeyPairGenerator
keyPairGen.initialize(2048);

步驟 3:生成 KeyPairGenerator

您可以使用generateKeyPair()方法生成KeyPair。使用此方法生成金鑰對,如下所示。

//Generate the pair of keys
KeyPair pair = keyPairGen.generateKeyPair();

步驟 4:從對中獲取私鑰

您可以使用getPrivate()方法從生成的KeyPair物件中獲取私鑰。

使用getPrivate()方法獲取私鑰,如下所示。

//Getting the private key from the key pair
PrivateKey privKey = pair.getPrivate();   

步驟 5:建立一個簽名物件

Signature類的getInstance()方法接受一個表示所需簽名演算法的字串引數,並返回相應的Signature物件。

使用getInstance()方法建立Signature類的物件。

//Creating a Signature object
Signature sign = Signature.getInstance("SHA256withDSA");

步驟 6:初始化簽名物件

Signature類的initSign()方法接受一個PrivateKey物件並初始化當前的Signature物件。

使用initSign()方法初始化在前面步驟中建立的Signature物件,如下所示。

//Initialize the signature
sign.initSign(privKey);

步驟 7:將資料新增到簽名物件

Signature類的update()方法接受一個表示要簽名或驗證的資料的位元組陣列,並使用給定的資料更新當前物件。

透過將要簽名的資料以位元組陣列的形式傳遞給update()方法,更新初始化的Signature物件,如下所示。

byte[] bytes = "Hello how are you".getBytes();      

//Adding data to the signature
sign.update(bytes);

步驟 8:計算簽名

Signature類的sign()方法返回更新資料的簽名位元組。

使用sign()方法計算簽名,如下所示。

//Calculating the signature
byte[] signature = sign.sign();

步驟 9:初始化用於驗證的簽名物件

要驗證Signature物件,您需要先使用initVerify()方法對其進行初始化,該方法接受一個PublicKey物件。

因此,使用initVerify()方法初始化用於驗證的Signature物件,如下所示。

//Initializing the signature
sign.initVerify(pair.getPublic());

步驟 10:更新要驗證的資料

使用update方法更新初始化(用於驗證)的物件,其中包含要驗證的資料,如下所示。

//Update the data to be verified
sign.update(bytes);

步驟 11:驗證簽名

Signature類的verify()方法接受另一個簽名物件並將其與當前物件進行驗證。如果匹配,則返回true,否則返回false。

使用此方法驗證簽名,如下所示。

//Verify the signature
boolean bool = sign.verify(signature);

示例

以下 Java 程式接受使用者輸入的訊息,為給定訊息生成數字簽名,並對其進行驗證。

import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.PrivateKey;
import java.security.Signature;

import java.util.Scanner;

public class SignatureVerification {
   public static void main(String args[]) throws Exception{
      //Creating KeyPair generator object
      KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance("DSA");
	      
      //Initializing the key pair generator
      keyPairGen.initialize(2048);
	      
      //Generate the pair of keys
      KeyPair pair = keyPairGen.generateKeyPair();
      
      //Getting the privatekey from the key pair
      PrivateKey privKey = pair.getPrivate();

      //Creating a Signature object
      Signature sign = Signature.getInstance("SHA256withDSA");

      //Initializing the signature
      sign.initSign(privKey);
      byte[] bytes = "Hello how are you".getBytes();
      
      //Adding data to the signature
      sign.update(bytes);
      
      //Calculating the signature
      byte[] signature = sign.sign();      
      
      //Initializing the signature
      sign.initVerify(pair.getPublic());
      sign.update(bytes);
      
      //Verifying the signature
      boolean bool = sign.verify(signature);
      
      if(bool) {
         System.out.println("Signature verified");   
      } else {
         System.out.println("Signature failed");
      }
   }
}

輸出

以上程式生成以下輸出 -

Signature verified

Java 加密 - 資料加密

您可以使用javax.crypto包的Cipher類加密給定資料。請按照以下步驟使用 Java 加密給定資料。

步驟 1:建立一個 KeyPairGenerator 物件

KeyPairGenerator類提供getInstance()方法,該方法接受一個表示所需金鑰生成演算法的字串變數,並返回一個生成金鑰的KeyPairGenerator物件。

使用getInstance()方法建立KeyPairGenerator物件,如下所示。

//Creating KeyPair generator object
KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance("DSA");

步驟 2:初始化 KeyPairGenerator 物件

KeyPairGenerator類提供了一個名為initialize()的方法,此方法用於初始化金鑰對生成器。此方法接受一個表示金鑰大小的整數值。

使用initialize()方法初始化在前面步驟中建立的KeyPairGenerator物件,如下所示。

//Initializing the KeyPairGenerator
keyPairGen.initialize(2048);

步驟 3:生成 KeyPairGenerator

您可以使用KeyPairGenerator類的generateKeyPair()方法生成KeyPair。使用此方法生成金鑰對,如下所示。

//Generate the pair of keys
KeyPair pair = keyPairGen.generateKeyPair();

步驟 4:獲取公鑰

您可以使用getPublic()方法從生成的KeyPair物件中獲取公鑰,如下所示。

使用此方法獲取公鑰,如下所示。

//Getting the public key from the key pair
PublicKey publicKey = pair.getPublic();

步驟 5:建立一個 Cipher 物件

Cipher類的getInstance()方法接受一個表示所需轉換的字串變數,並返回一個實現給定轉換的Cipher物件。

使用getInstance()方法建立Cipher物件,如下所示。

//Creating a Cipher object
Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");

步驟 6:初始化 Cipher 物件

Cipher類的init()方法接受兩個引數:一個表示操作模式(加密/解密)的整數引數和一個表示公鑰的Key物件。

使用init()方法初始化Cypher物件,如下所示。

//Initializing a Cipher object
cipher.init(Cipher.ENCRYPT_MODE, publicKey);

步驟 7:將資料新增到 Cipher 物件

Cipher類的update()方法接受一個表示要加密的資料的位元組陣列,並使用給定的資料更新當前物件。

透過將資料以位元組陣列的形式傳遞給update()方法,更新初始化的Cipher物件,如下所示。

//Adding data to the cipher
byte[] input = "Welcome to Tutorialspoint".getBytes();	  
cipher.update(input);

步驟 8:加密資料

Cipher類的doFinal()方法完成加密操作。因此,使用此方法完成加密,如下所示。

//Encrypting the data
byte[] cipherText = cipher.doFinal();

示例

以下 Java 程式接受使用者輸入的文字,使用 RSA 演算法對其進行加密,並列印給定文字的加密格式。

import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.Signature;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;

public class CipherSample {
   public static void main(String args[]) throws Exception{
      //Creating a Signature object
      Signature sign = Signature.getInstance("SHA256withRSA");
      
      //Creating KeyPair generator object
      KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance("RSA");
      
      //Initializing the key pair generator
      keyPairGen.initialize(2048);
      
      //Generating the pair of keys
      KeyPair pair = keyPairGen.generateKeyPair();      
	
      //Creating a Cipher object
      Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
        
      //Initializing a Cipher object
      cipher.init(Cipher.ENCRYPT_MODE, pair.getPublic());
	  
      //Adding data to the cipher
      byte[] input = "Welcome to Tutorialspoint".getBytes();	  
      cipher.update(input);
	  
      //encrypting the data
      byte[] cipherText = cipher.doFinal();	 
      System.out.println(new String(cipherText, "UTF8"));
   }
}

輸出

以上程式生成以下輸出 -

Encrypted Text: 
"???:]J_?]???;Xl??????*@??u???r??=T&???_?_??.??i?????(?$_f?zD??????ZGH??g???
g?E:_??bz^??f?~o???t?}??u=uzp\UI????Z??l[?G?3??Y?UAEfKT?f?O??N_?d__?????a_?15%?^?
'p?_?$,9"{??^??y??_?t???,?W?PCW??~??[?$??????e????f?Y-Zi__??_??w?_?&QT??`?`~?[?K_??_???

Java 加密 - 資料解密

您可以使用javax.crypto包的Cipher類解密加密的資料。請按照以下步驟使用 Java 解密給定資料。

步驟 1:建立一個 KeyPairGenerator 物件

KeyPairGenerator類提供getInstance()方法,該方法接受一個表示所需金鑰生成演算法的字串變數,並返回一個生成金鑰的KeyPairGenerator物件。

使用getInstance()方法建立KeyPairGenerator物件,如下所示。

//Creating KeyPair generator object
KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance("DSA");

步驟 2:初始化 KeyPairGenerator 物件

KeyPairGenerator類提供了一個名為initialize()的方法,此方法用於初始化金鑰對生成器。此方法接受一個表示金鑰大小的整數值。

使用initialize()方法初始化在前面步驟中建立的KeyPairGenerator物件,如下所示。

//Initializing the KeyPairGenerator
keyPairGen.initialize(2048);

步驟 3:生成 KeyPairGenerator

您可以使用KeyPairGenerator類的generateKeyPair()方法生成KeyPair。使用此方法生成金鑰對,如下所示。

//Generate the pair of keys
KeyPair pair = keyPairGen.generateKeyPair();

步驟 4:獲取公鑰

您可以使用getPublic()方法從生成的KeyPair物件中獲取公鑰,如下所示。

//Getting the public key from the key pair
PublicKey publicKey = pair.getPublic();

步驟 5:建立一個 Cipher 物件

Cipher類的getInstance()方法接受一個表示所需轉換的字串變數,並返回一個實現給定轉換的Cipher物件。

使用getInstance()方法建立Cipher物件,如下所示。

//Creating a Cipher object
Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");

步驟 6:初始化 Cipher 物件

Cipher類的init()方法接受兩個引數

  • 一個表示操作模式(加密/解密)的整數引數
  • 表示公鑰的Key物件

使用init()方法初始化Cypher物件,如下所示。

//Initializing a Cipher object
cipher.init(Cipher.ENCRYPT_MODE, publicKey);

步驟 7:將資料新增到 Cipher 物件

Cipher類的update()方法接受一個表示要加密的資料的位元組陣列,並使用給定的資料更新當前物件。

透過將資料以位元組陣列的形式傳遞給update()方法,更新初始化的Cipher物件,如下所示。

//Adding data to the cipher
byte[] input = "Welcome to Tutorialspoint".getBytes();	  
cipher.update(input);

步驟 8:加密資料

Cipher類的doFinal()方法完成加密操作。因此,使用此方法完成加密,如下所示。

//Encrypting the data
byte[] cipherText = cipher.doFinal();

步驟 9:初始化用於解密的 Cipher 物件

要解密在前面步驟中加密的密碼,您需要將其初始化以進行解密。

因此,透過傳遞引數Cipher.DECRYPT_MODE和PrivateKey物件初始化密碼物件,如下所示。

//Initializing the same cipher for decryption
cipher.init(Cipher.DECRYPT_MODE, pair.getPrivate());

步驟 10:解密資料

最後,使用doFinal()方法解密加密的文字,如下所示。

//Decrypting the text
byte[] decipheredText = cipher.doFinal(cipherText);

示例

以下 Java 程式接受使用者輸入的文字,使用 RSA 演算法對其進行加密,並列印給定文字的密碼,解密密碼並再次列印解密的文字。

import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.Signature;

import javax.crypto.Cipher;

public class CipherDecrypt {
   public static void main(String args[]) throws Exception{
	   //Creating a Signature object
      Signature sign = Signature.getInstance("SHA256withRSA");
      
      //Creating KeyPair generator object
      KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance("RSA");
      
      //Initializing the key pair generator
      keyPairGen.initialize(2048);
      
      //Generate the pair of keys
      KeyPair pair = keyPairGen.generateKeyPair();   
      
      //Getting the public key from the key pair
      PublicKey publicKey = pair.getPublic();  

      //Creating a Cipher object
      Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");

      //Initializing a Cipher object
      cipher.init(Cipher.ENCRYPT_MODE, publicKey);
	  
      //Add data to the cipher
      byte[] input = "Welcome to Tutorialspoint".getBytes();	  
      cipher.update(input);
	  
      //encrypting the data
      byte[] cipherText = cipher.doFinal();	 
      System.out.println( new String(cipherText, "UTF8"));

      //Initializing the same cipher for decryption
      cipher.init(Cipher.DECRYPT_MODE, pair.getPrivate());
      
      //Decrypting the text
      byte[] decipheredText = cipher.doFinal(cipherText);
      System.out.println(new String(decipheredText));
   }
}

輸出

以上程式生成以下輸出 -

Encrypted Text:
]/[?F3?D?p
v?w?!?H???^?A??????P?u??FA?
?
???_?? ???_jMH-??>??OP?'?j?_?n`
?_??'`????o??_GL??g???g_f?????f|???LT?|?Vz_TDu#??\?<b,,?$C2???Bq?#?lDB`??g,^??K?_?v???`}
?;LX?a?_5e???#???_?6?/B&B_???^?__Ap^#_?q?IEh????_?,??*??]~_?_?D?
_y???lp??a?P_U{

Decrypted Text:
Welcome to Tutorialspoint
廣告
© . All rights reserved.