以下都没有做异常处理,只是简单抛出,如果抽取成工具类,使用时应仔细处理
SM2 解析数字证书
public void subject()
{
String demo = "证书";
byte[] decode = Base64.getDecoder().decode(demo);
getCert(decode);
}
public static void getCert(byte[] buf){
ByteArrayInputStream bIn;
ASN1InputStream aIn;
bIn = new ByteArrayInputStream(buf);
aIn = new ASN1InputStream(bIn);
try {
ASN1Sequence seq = (ASN1Sequence) aIn.readObject();
X509CertificateStructure cert = new X509CertificateStructure(seq);
System.out.println("****************************");
System.out.println("证书版本:\t"+cert.getVersion());
System.out.println("序列号:\t\t"+cert.getSerialNumber().getValue().toString(16));
System.out.println("算法标识:\t"+cert.getSignatureAlgorithm().getAlgorithm());
System.out.println("签发者:\t\t"+cert.getIssuer()); //GMT 格林威治标准时间
System.out.println("开始时间:\t"+cert.getStartDate().getTime());
System.out.println("结束时间:\t"+cert.getEndDate().getTime());
System.out.println("主体名:\t\t"+cert.getSubject());
System.out.print("签名值:\t");
DERBitString signature=cert.getSignature();
String strSign=new String(Hex.encode(signature.getBytes()));
System.out.println(strSign);
System.out.println("主体公钥:\t");
SubjectPublicKeyInfo pukinfo=cert.getSubjectPublicKeyInfo();
System.out.println("\t标识符:\t"+pukinfo.getAlgorithmId().getAlgorithm());
byte[] byPuk=pukinfo.getPublicKeyData().getBytes();
String strPuk=new String(Hex.encode(byPuk));
System.out.println("\t公钥值:\t"+strPuk);
System.out.println("****************************");
} catch (IOException e) {
e.printStackTrace();
}
}
=======================================================
### SM2 验签
在实际应用的时候,签名实际上并不是针对原始消息,而是针对原始消息的哈希进行签名 ,对签名进行验证实际上就是用公钥解密,然后把解密后的哈希与原始消息的哈希进行对比。因为用户总是使用自己的私钥进行签名,所以,私钥就相当于用户身份。而公钥用来给外部验证用户身份。
```java
public static void main(String[] args) throws CertificateException, InvalidKeyException, NoSuchAlgorithmException, SignatureException, UnsupportedEncodingException {
String certStr = "证书";
String plaintext = "原文";
String temp = "签名值";
byte[] signValue = Base64.decode(temp);
CertificateFactory factory = new CertificateFactory();
X509Certificate certificate = (X509Certificate) factory.engineGenerateCertificate(
new ByteArrayInputStream(Base64.decode(certStr)));
System.out.println(certificate.getSigAlgName());
Signature signature = Signature.getInstance(certificate.getSigAlgName()
,new BouncyCastleProvider());
signature.initVerify(certificate);
signature.update(plaintext.getBytes("GBK"));
System.out.println(signature.verify(signValue));
/**
* 打印原文不同格式的各种编码
*/
System.out.println(Arrays.toString(plaintext.getBytes("GBK")));
System.out.println(Arrays.toString(plaintext.getBytes("UTF8")));
System.out.println(Arrays.toString(plaintext.getBytes(StandardCharsets.UTF_8)));
System.out.println(Arrays.toString(plaintext.getBytes(StandardCharsets.ISO_8859_1)));
}