use of com.itrus.Exception.GenP10Exception in project portal by ixinportal.
the class GenUtil method GenP10.
public static String GenP10(String userid, String subject, String alg) throws GenP10Exception {
if (!"".equalsIgnoreCase(userid)) {
if (keyMap.containsKey(userid)) {
throw new GenP10Exception("用户唯一标识【" + userid + "】不能重复");
}
} else {
throw new GenP10Exception("用户唯一标识不能为空");
}
KeyPairGenerator kpg = null;
try {
kpg = KeyPairGenerator.getInstance(alg);
} catch (NoSuchAlgorithmException e1) {
throw new GenP10Exception("输入秘钥对产生算法不正确:" + alg);
}
if ("SM2".equalsIgnoreCase(alg)) {
kpg.initialize(256);
} else {
kpg.initialize(2048);
}
KeyPair kp = kpg.generateKeyPair();
keyMap.put(userid, kp);
byte[] publickey = kp.getPublic().getEncoded();
final String pubAlg = kp.getPublic().getAlgorithm();
String sAlg = null;
try {
sAlg = AlgorithmId.get(pubAlg).getOID().toString();
} catch (NoSuchAlgorithmException e1) {
throw new GenP10Exception("输入秘钥对产生算法不正确:" + sAlg);
}
SubjectPublicKeyInfo spki = null;
if (sAlg.equals("1.2.156.10197.1.301")) {
spki = SubjectPublicKeyInfo.getInstance(publickey);
} else {
spki = new SubjectPublicKeyInfo(ASN1Sequence.getInstance(publickey));
}
if ("".equals(subject)) {
subject = "CN=defaultName";
}
X500Name x500 = new X500Name(subject);
PKCS10CertificationRequestBuilder prb = new PKCS10CertificationRequestBuilder(x500, spki);
ContentSigner signer = null;
PrivateKey privateKey = kp.getPrivate();
final Signature sign;
try {
if (privateKey.getAlgorithm().equals("SM2")) {
sign = Signature.getInstance("SM3withSM2");
} else {
sign = Signature.getInstance("SHA1withRSA");
}
sign.initSign(privateKey);
} catch (NoSuchAlgorithmException e) {
throw new GenP10Exception("输入秘钥对产生算法不正确:SHA1withRSA");
} catch (InvalidKeyException e) {
throw new GenP10Exception("无效的私钥信息");
}
signer = new ContentSigner() {
ByteArrayOutputStream originStream = new ByteArrayOutputStream();
public byte[] getSignature() {
try {
sign.update(this.originStream.toByteArray());
return sign.sign();
} catch (SignatureException e) {
throw new RuntimeException(e);
}
}
public OutputStream getOutputStream() {
return this.originStream;
}
public AlgorithmIdentifier getAlgorithmIdentifier() {
try {
return new AlgorithmIdentifier(AlgorithmId.get(pubAlg).getOID().toString());
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException(e);
}
}
};
PKCS10CertificationRequestHolder pr = prb.build(signer);
try {
return new String(Base64.encode(pr.getEncoded()));
} catch (IOException e) {
throw new GenP10Exception("产生CSR错误,请检查输入参数");
}
}
Aggregations