Статус: Участник
Группы: Участники
Зарегистрирован: 27.04.2015(UTC) Сообщений: 14 Откуда: Воронеж Сказал(а) «Спасибо»: 3 раз
|
Подскажите пожалуйста Нужно сформировать файл в формате CMS/PKCS#7 в DER кодировке. Нашёл на форуме пример и переделал под свои нужды. Но при отправке в сервис мне говорят что это не DER формат, хотя я вроде указываю кодировку. Может другой пример надо адаптировать?
Код:public class SignXmlFile {
private static final String PROVIDER = JCSP.PROVIDER_NAME; // provider name
private static final String KEY_MANAGERS_KEY_STORAGE = "p12.pfx";
private static final String TEST_FILE = "tests.xml"; // pfx for import
private static final String KEY_STORAGE_PASSWORD = "password";
String scope = "fullname";
String clientid = "NPCPN";
String responseType = "code";
String datetime = GetDateTime();
String state = GetState();
public static void main(String[] args) throws Exception {
X509Certificate x509Certificate = getCertificateFromPersonalStore();
InputStream inputStream = FileUtils.getFileResourceAsStream(TEST_FILE);
if (Objects.isNull(inputStream)) {
log.info("Error while uploading data");
return;
}
var signResult = sign(x509Certificate, inputStream.readAllBytes());
Files.write(Path.of("tests.xml.sig"), signResult);
log.info("CMS sign successfil");
}
public static X509Certificate getCertificateFromPersonalStore() {
Security.addProvider(new JCP());
Security.addProvider(new JCSP());
Security.addProvider(new RevCheck());
Security.addProvider(new CryptoProvider());// провайдер шифрования JCryptoP
X509Certificate x509 = null;
try {
KeyStore keyStore = KeyStore.getInstance(JCSP.PFX_STORE_NAME, PROVIDER);
keyStore.load(FileUtils.getFileResourceAsStream(KEY_MANAGERS_KEY_STORAGE), KEY_STORAGE_PASSWORD.toCharArray());
Enumeration en = keyStore.aliases();
while(en.hasMoreElements()) {
String s = (String)en.nextElement();
if (keyStore.isKeyEntry(s)) {
Certificate[] kcerts = keyStore.getCertificateChain(s);
if (kcerts[0] instanceof X509Certificate) {
x509 = (X509Certificate)kcerts[0];
}
}
if (keyStore.isCertificateEntry(s)) {
Certificate c = keyStore.getCertificate(s);
if (c instanceof X509Certificate) {
x509 = (X509Certificate)c;
}
}
}
} catch (Exception ex) {
log.error("Certificate reading error", ex);
return null;
}
return x509;
}
public static PrivateKey getPrivateKey(X509Certificate cert, char[] password) {
try {
KeyStore keyStore = KeyStore.getInstance(JCSP.PFX_STORE_NAME, PROVIDER);
keyStore.load(FileUtils.getFileResourceAsStream(KEY_MANAGERS_KEY_STORAGE), KEY_STORAGE_PASSWORD.toCharArray());
String alias = keyStore.aliases().nextElement();
return (PrivateKey) keyStore.getKey(alias, null);
} catch (Exception var7) {
log.error("Error while getting private key ", var7);
}
return null;
}
public static byte[] sign(X509Certificate cert, byte[] data) throws Exception {
char [] pass = KEY_STORAGE_PASSWORD.toCharArray();
PrivateKey privateKey = getPrivateKey(cert, pass);
return CMSSign(data, privateKey, cert, true);
}
public static byte[] CMSSign(byte[] data, PrivateKey key, Certificate cert, boolean detached) throws Exception {
//Алгоритм подписи
Signature signature = Signature.getInstance("GOST3411_2012_256withGOST3410_2012_256", "JCSP");
signature.initSign( key );
signature.update( data );
byte[] sign = signature.sign();
return createCMS( data, sign, cert, detached );
}
public static byte[] createCMS(byte[] buffer, byte[] sign, Certificate cert, boolean detached) throws Exception {
ContentInfo all = new ContentInfo();
all.contentType = new Asn1ObjectIdentifier((new OID("1.2.840.113549.1.7.2")).value);
SignedData cms = new SignedData();
all.content = cms;
cms.version = new CMSVersion(1L);
cms.digestAlgorithms = new DigestAlgorithmIdentifiers(1);
DigestAlgorithmIdentifier a = new DigestAlgorithmIdentifier((new OID("1.2.643.7.1.1.2.2")).value);
a.parameters = new Asn1Null();
cms.digestAlgorithms.elements[0] = a;
if (detached) {
cms.encapContentInfo = new EncapsulatedContentInfo(new Asn1ObjectIdentifier((new OID("1.2.840.113549.1.7.1")).value), (Asn1OctetString)null);
} else {
cms.encapContentInfo = new EncapsulatedContentInfo(new Asn1ObjectIdentifier((new OID("1.2.840.113549.1.7.1")).value), new Asn1OctetString(buffer));
}
cms.certificates = new CertificateSet(1);
ru.CryptoPro.JCP.ASN.PKIX1Explicit88.Certificate certificate = new ru.CryptoPro.JCP.ASN.PKIX1Explicit88.Certificate();
Asn1BerDecodeBuffer decodeBuffer = new Asn1BerDecodeBuffer(cert.getEncoded());
certificate.decode(decodeBuffer);
cms.certificates.elements = new CertificateChoices[1];
cms.certificates.elements[0] = new CertificateChoices();
cms.certificates.elements[0].set_certificate(certificate);
cms.signerInfos = new SignerInfos(1);
cms.signerInfos.elements[0] = new SignerInfo();
cms.signerInfos.elements[0].version = new CMSVersion(1L);
cms.signerInfos.elements[0].sid = new SignerIdentifier();
byte[] encodedName = ((X509Certificate)cert).getIssuerX500Principal().getEncoded();
Asn1BerDecodeBuffer nameBuf = new Asn1BerDecodeBuffer(encodedName);
Name name = new Name();
name.decode(nameBuf);
CertificateSerialNumber num = new CertificateSerialNumber(((X509Certificate)cert).getSerialNumber());
cms.signerInfos.elements[0].sid.set_issuerAndSerialNumber(new IssuerAndSerialNumber(name, num));
cms.signerInfos.elements[0].digestAlgorithm = new DigestAlgorithmIdentifier((new OID("1.2.643.7.1.1.2.2")).value);
cms.signerInfos.elements[0].digestAlgorithm.parameters = new Asn1Null();
cms.signerInfos.elements[0].signatureAlgorithm = new SignatureAlgorithmIdentifier((new OID("1.2.643.7.1.1.1.1")).value);
cms.signerInfos.elements[0].signatureAlgorithm.parameters = new Asn1Null();
cms.signerInfos.elements[0].signature = new SignatureValue(sign);
Asn1DerEncodeBuffer asnBuf = new Asn1DerEncodeBuffer();
all.encode(asnBuf, true);
return asnBuf.getMsgCopy();
}
public String getResponseType() {
return responseType;
}
public String getScope() {
return scope;
}
public String getClientid() {
return clientid;
}
public String getDatetime() {
return datetime;
}
public String getState() {
return state;
}
private String GetState(){
UUID uuid = UUID.randomUUID();
return uuid.toString();
}
private String GetDateTime(){
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy.MM.dd+HH:mm:ss");
LocalDateTime localDateTime = LocalDateTime.now();
return dtf.format(localDateTime).replace(":",":")+"++0300";
}
private String GetClientSecret(String state) throws Exception {
String msg = getScope() + getDatetime() + getClientid() + getState();
byte[] msgBytes = msg.getBytes("UTF8");
byte[] encodedSignature = sign(getCertificateFromPersonalStore(), msgBytes);
return Base64UrlEncode(encodedSignature);
}
public static String getThumbPrint(X509Certificate cert) throws NoSuchAlgorithmException, CertificateEncodingException {
MessageDigest md = MessageDigest.getInstance("SHA-1");
byte[] der = cert.getEncoded();
md.update(der);
byte[] digest = md.digest();
return new String(Hex.encodeHex(digest));
}
public static String Base64UrlEncode(byte[] arg)
{
String encodedString = Base64.getEncoder().encodeToString(arg);
encodedString = encodedString.replace("+","-");
encodedString = encodedString.replace("/","_");
encodedString = encodedString.replace("=","");
return encodedString;
}
}
|