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();