java中的密钥Key接口及其相关类

在项目中使用到加密加签功能,记录一下:

涉及到加解密必然涉及到加密算法,加密格式,公私钥的编码字节等。

java中java.security.Key接口具有这三个方法:
	public String getAlgorithm();
    public String getFormat();
    public byte[] getEncoded();

 与这个Key密切相关的几个接口和类:

公钥接口PublicKey,私钥接口PrivateKey继承接口Key

不可变类KeyPair密钥对,

KeyPairGenerator类用来生成KeyPair密钥对,继承KeyPairGeneratorSpi这个抽象类.这个类有多个生成KeyPair密钥对的静态工厂方法,

KeyFactory类也可得到公私钥,比如此公钥兼容多种密钥规范,可根据不同的秘钥规范获取公钥值,比如javadoc中写到的例子:

byte[] signature ;
X509EncodedKeySpec bobPubKeySpec = new X509EncodedKeySpec(bobEncodedPubKey);
 KeyFactory keyFactory = KeyFactory.getInstance("DSA");
 PublicKey bobPubKey = keyFactory.generatePublic(bobPubKeySpec);
 Signature sig = Signature.getInstance("DSA");
 sig.initVerify(bobPubKey);
 sig.update(data);
 sig.verify(signature);

  KeyRep类用于序列化证书的,其中主要的方法是:

 protected Object readResolve() throws ObjectStreamException

 这个方法可以返回:X509标准的公钥,PKCS #8标准的私钥,SecretKeySpec对象

KeySpec接口是一个空接口,包java.security.spec有多个类采用不同的加密算法(RSA,DSA)实现这个接口,也有不同的编码标准(X509,PKCS #8)。

加密解密主要使用到的几个类:

java.security.spec.X509EncodedKeySpec , java.security.spec.PKCS8EncodedKeySpec,

java.security.KeyStore .

在项目中使用的证书是用RSA算法,采用X509规范生成的1024位pfx证书,公钥是cer证书。

 在导出证书环节使用java平台规范的:

Every implementation of the Java platform is required to support the following standard KeyStore type:

  • PKCS12



 

可以使用这行代码读取PKCS格式的证书,存入KeyStore中:

KeyStore ks = KeyStore.getInstance("PKCS12"); //获取KeyStore实例
char[] password = getPassword();//获取证书密码的字节组
try (FileInputStream fis = new FileInputStream("filefolder/a.pfx")) {
    ks.load(fis, password);
}

KeyStore 的文档中,说明keystore 中的每个Entry是采用alias来识别的。

Each entry in a keystore is identified by an "alias" string. In the case of private keys and their associated certificate chains, these strings distinguish among the different ways in which the entity may authenticate itself. For example, the entity may authenticate itself using different certificate authorities, or using different public key algorithms. 

Enumeration<String> enumas =ks.aliases();
if(enumas.hasMoreElements()){
    String    keyAlias = (String) enumas.nextElement(); //获取证书Entry
}

 采用类keyStore的静态方法: 

public final Key getKey(String alias, char[] password) throws KeyStoreException, NoSuchAlgorithmException,UnrecoverableKeyException来获取私钥。

可通过public final Certificate getCertificate(String alias)  throws KeyStoreException获取

 再使用Certificate 的getPublicKey()方法获取公钥,getPublicKey()的实现类是sun.security.x509.X509CertImpl,在jre/rt.jar里面,openjdk中可以看到源码,可以自己编译openjdk源码,也可在这个网站上看到:

http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/8u40-b25/sun/security/x509/X509CertImpl.java#X509CertImpl.getPublicKey%28%29。到目前就扯完了Key的加载及获取公私钥的方法。

 

也可使用CertificateFactory这个类来获取Certificate,然后通过上文中Certificate的getPublicKey()方法获取公钥。使用姿势如下:

CertificateFactory cf = CertificateFactory.getInstance("X.509");
Certificate cert = cf.generateCertificate(new FileInputStream(file));
return cert.getPublicKey();

 

 

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
在Spring Boot项目生成接口密钥key可以使用和Java原生似的方式,主要是通过Java加密解密相关的API来实现。以下是一种基于Spring Boot的生成AES加密算法密钥的方式: 1. 在Spring Boot项目的配置文件application.properties配置密钥长度,例如: ``` encryption.key.length=128 ``` 2. 创建一个用于生成密钥的工具EncryptionUtils,包含一个用于生成密钥的静态方法getSecretKey,如下: ```java import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; import javax.crypto.KeyGenerator; import javax.crypto.SecretKey; import javax.crypto.spec.SecretKeySpec; @Component public class EncryptionUtils { @Value("${encryption.key.length}") private int keyLength; public SecretKey getSecretKey() throws Exception { KeyGenerator keyGen = KeyGenerator.getInstance("AES"); keyGen.init(keyLength); SecretKey secretKey = keyGen.generateKey(); byte[] keyBytes = secretKey.getEncoded(); return new SecretKeySpec(keyBytes, "AES"); } } ``` 3. 在需要使用密钥的地方,注入EncryptionUtils并调用getSecretKey方法获取密钥,例如: ```java import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import javax.crypto.Cipher; import javax.crypto.SecretKey; @Service public class EncryptionService { @Autowired private EncryptionUtils encryptionUtils; public String encrypt(String strToEncrypt) throws Exception { Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding"); SecretKey secretKey = encryptionUtils.getSecretKey(); cipher.init(Cipher.ENCRYPT_MODE, secretKey); byte[] encryptedBytes = cipher.doFinal(strToEncrypt.getBytes()); return Base64.getEncoder().encodeToString(encryptedBytes); } public String decrypt(String strToDecrypt) throws Exception { Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5PADDING"); SecretKey secretKey = encryptionUtils.getSecretKey(); cipher.init(Cipher.DECRYPT_MODE, secretKey); byte[] decryptedBytes = cipher.doFinal(Base64.getDecoder().decode(strToDecrypt)); return new String(decryptedBytes); } } ``` 需要注意的是,密钥的生成方式应该根据具体的使用场景和安全需求进行选择。如果需要更高的安全性,可以使用更复杂的生成方式,比如使用RSA算法生成密钥对等。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值