All Downloads are FREE. Search and download functionalities are using the official Maven repository.

spring.turbo.util.crypto.pem.ECDSAPemHelper Maven / Gradle / Ivy

package spring.turbo.util.crypto.pem;

import org.springframework.core.io.Resource;

import java.io.IOException;
import java.io.InputStream;
import java.io.UncheckedIOException;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.interfaces.ECPrivateKey;
import java.security.interfaces.ECPublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;

/**
 * 这是一个小工具。可以从PEM文件中读取ECDSA公钥和私钥 
* 此工具依赖 Bouncy Castle * * @author 应卓 * @see 2024‐07‐02‐openssl‐cheatsheet * @see OpenSSL官方文档 * @see X509 wiki * @see PKCS#8 wiki * @since 3.3.1 */ public final class ECDSAPemHelper { private static final String ALGORITHM = "EC"; /** * 私有构造方法 */ private ECDSAPemHelper() { } /** * 读取公钥和私钥 * * @param publicKeyResource 公钥资源 * @param privateKeyResource 私钥资源 * @return {@link KeyPair} 实例 * @throws UncheckedIOException IO错误 */ public static KeyPair readKeyPair(Resource publicKeyResource, Resource privateKeyResource) { return new KeyPair( readX509PublicKey(publicKeyResource), readPKCS8PrivateKey(privateKeyResource) ); } /** * 读取公钥
* 注意: 必须是X509格式 * * @param resource 资源 * @return 公钥 * @throws UncheckedIOException IO错误 */ public static ECPublicKey readX509PublicKey(Resource resource) { try { return readX509PublicKey(resource.getInputStream()); } catch (IOException e) { throw new UncheckedIOException(e); } } /** * 读取公钥
* 注意: 必须是X509格式 * * @param inputStream 资源 * @return 公钥 * @throws UncheckedIOException IO错误 */ public static ECPublicKey readX509PublicKey(InputStream inputStream) { try { var factory = KeyFactory.getInstance(ALGORITHM); var spec = new X509EncodedKeySpec(PemHelper.readPemBytes(inputStream)); return (ECPublicKey) factory.generatePublic(spec); } catch (Exception e) { throw new IllegalArgumentException(e.getMessage(), e); } } /** * 读取私钥
* 注意: 必须是PKCS8格式 * * @param resource 资源 * @return 私钥 * @throws UncheckedIOException IO错误 */ public static ECPrivateKey readPKCS8PrivateKey(Resource resource) { try { return readPKCS8PrivateKey(resource.getInputStream()); } catch (IOException e) { throw new UncheckedIOException(e); } } /** * 读取私钥
* 注意: 必须是PKCS8格式 * * @param inputStream 资源 * @return 私钥 * @throws UncheckedIOException IO错误 */ public static ECPrivateKey readPKCS8PrivateKey(InputStream inputStream) { try { var factory = KeyFactory.getInstance(ALGORITHM); var spec = new PKCS8EncodedKeySpec(PemHelper.readPemBytes(inputStream)); return (ECPrivateKey) factory.generatePrivate(spec); } catch (Exception e) { throw new IllegalArgumentException(e.getMessage(), e); } } }




© 2015 - 2025 Weber Informatics LLC | Privacy Policy