openssl_conf = openssl_def [openssl_def] engines = engine_section [engine_section] gost = gost_section [gost_section] engine_id = gost dynamic_path = gost.dll default_algorithms = ALL CRYPT_PARAMS = id-Gost28147-89-CryptoPro-A-ParamSet
set OPENSSL_CONF=C:\__openssl\bin\openssl.cfg
openssl pkcs12 -in my.pfx -nocerts -nodes -out my.pem
openSSL pkcs8 -in my.pem -topk8 -nocrypt -out key.pk8
openssl pkcs12 -in my.pfx -nokeys -out my.cer
<dependency> <groupId>org.bouncycastle</groupId> <artifactId>bcprov-jdk15on</artifactId> <version>1.59</version> </dependency> <dependency> <groupId>org.bouncycastle</groupId> <artifactId>bcpkix-jdk15on</artifactId> <version>1.59</version> </dependency>
public static byte[] signWithGost3410(byte[] data, X509Certificate certificate, byte[] encodedPrivateKey) throws Exception { X509Certificate[] certificates = new X509Certificate[1]; certificates[0] = certificate; PKCS8EncodedKeySpec privateKeySpec = new PKCS8EncodedKeySpec(encodedPrivateKey); KeyFactory keyFactory = KeyFactory.getInstance("ECGOST3410", "BC"); PrivateKey privateKey = keyFactory.generatePrivate(privateKeySpec); CMSTypedData msg = new CMSProcessableByteArray(data); Store certStore = new JcaCertStore(Arrays.asList(certificates)); CMSSignedDataGenerator gen = new CMSSignedDataGenerator(); ContentSigner signer = new org.bouncycastle.operator.jcajce.JcaContentSignerBuilder("GOST3411withECGOST3410").setProvider("BC").build(privateKey); gen.addSignerInfoGenerator(new JcaSignerInfoGeneratorBuilder(new JcaDigestCalculatorProviderBuilder().setProvider("BC").build()).build(signer, (X509Certificate) certificates[0])); gen.addCertificates(certStore); CMSSignedData sigData = gen.generate(msg, true); return sigData.getEncoded(); }
public static byte[] readEncodedKeyFromPk8File(String filename) throws Exception { byte[] content = Files.readAllBytes(Paths.get(filename)); ArrayList<String> lines = new ArrayList<>(Arrays.asList(new String(content).split("\n"))); lines.remove(0); lines.remove(lines.size() -1); String base64 = String.join("", lines); byte[] encoded = Base64.getDecoder().decode(base64); return encoded; }
public static X509Certificate readX509CertificateFromCerFile(String filename) throws Exception { CertificateFactory factory = CertificateFactory.getInstance("X.509"); Certificate certificate = factory.generateCertificate(new FileInputStream(filename)); return (X509Certificate) certificate; }
@Test public void signTest() throws Exception{ Security.addProvider(new BouncyCastleProvider()); byte[] key = readEncodedKeyFromPk8File("key.pk8"); X509Certificate certificate = readX509CertificateFromCerFile("my.cer"); byte[] data = Files.readAllBytes(Paths.get("my.xml")); byte[] signedData = signWithGost3410(data, certificate, key); try(FileOutputStream stream = new FileOutputStream("signed.dat")){ stream.write(signedData); } }
Source: https://habr.com/ru/post/353586/
All Articles