在Java中,使用私鑰進行數字簽名通常涉及到以下幾個步驟:
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.util.Base64;
import javax.crypto.Cipher;
public static KeyPair generateKeyPair() {
try {
KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
keyPairGenerator.initialize(2048);
return keyPairGenerator.generateKeyPair();
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
public static String signWithPrivateKey(String data, PrivateKey privateKey) {
try {
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.ENCRYPT_MODE, privateKey);
byte[] encryptedData = cipher.doFinal(data.getBytes());
return Base64.getEncoder().encodeToString(encryptedData);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
public static boolean verifySignature(String data, String signature, PublicKey publicKey) {
try {
byte[] decodedSignature = Base64.getDecoder().decode(signature);
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.DECRYPT_MODE, publicKey);
byte[] decryptedData = cipher.doFinal(decodedSignature);
return data.equals(new String(decryptedData));
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
public static void main(String[] args) {
KeyPair keyPair = generateKeyPair();
PublicKey publicKey = keyPair.getPublic();
PrivateKey privateKey = keyPair.getPrivate();
String data = "Hello, world!";
String signature = signWithPrivateKey(data, privateKey);
System.out.println("Signature: " + signature);
boolean isValid = verifySignature(data, signature, publicKey);
System.out.println("Signature is valid: " + isValid);
}
請注意,這里的示例使用了RSA算法進行數字簽名。在實際應用中,您可能需要根據具體需求選擇合適的算法。同時,為了確保安全性,請妥善保管私鑰。