java 公钥如何给
生成 Java 公钥的方法
Java 中生成公钥通常涉及密钥对(公钥和私钥)的生成,随后提取公钥部分。以下是常见的实现方式:
使用 KeyPairGenerator 生成密钥对
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.PublicKey;
public class GeneratePublicKey {
public static PublicKey generate() throws NoSuchAlgorithmException {
KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
keyPairGenerator.initialize(2048); // 密钥长度
KeyPair keyPair = keyPairGenerator.generateKeyPair();
return keyPair.getPublic(); // 获取公钥
}
}
从现有密钥材料加载公钥

如果已有公钥的字节数组或 Base64 编码字符串,可以通过 KeyFactory 还原:
import java.security.KeyFactory;
import java.security.NoSuchAlgorithmException;
import java.security.PublicKey;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.X509EncodedKeySpec;
import java.util.Base64;
public class LoadPublicKey {
public static PublicKey fromBase64(String base64PublicKey)
throws NoSuchAlgorithmException, InvalidKeySpecException {
byte[] keyBytes = Base64.getDecoder().decode(base64PublicKey);
X509EncodedKeySpec spec = new X509EncodedKeySpec(keyBytes);
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
return keyFactory.generatePublic(spec);
}
}
公钥的常见使用场景
加密数据

使用公钥加密敏感信息,确保只有持有对应私钥的一方可以解密:
import javax.crypto.Cipher;
public class EncryptWithPublicKey {
public static byte[] encrypt(PublicKey publicKey, byte[] data)
throws Exception {
Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
cipher.init(Cipher.ENCRYPT_MODE, publicKey);
return cipher.doFinal(data);
}
}
验证数字签名
公钥可用于验证由私钥生成的数字签名:
import java.security.Signature;
public class VerifySignature {
public static boolean verify(PublicKey publicKey, byte[] data, byte[] signature)
throws Exception {
Signature sig = Signature.getInstance("SHA256withRSA");
sig.initVerify(publicKey);
sig.update(data);
return sig.verify(signature);
}
}
注意事项
- 密钥长度建议至少为 2048 位以保证安全性。
- 存储公钥时通常使用 X.509 格式(通过
getEncoded()方法获取字节数组)。 - 实际应用中需处理
NoSuchAlgorithmException、InvalidKeySpecException等异常。 - 考虑使用 Bouncy Castle 等安全提供者支持更多算法。






