簡體   English   中英

在java中使用pfx文件簽署文本文件

[英]Signing a text file using a pfx file in java

我對java密碼學很陌生。 我正在嘗試使用包含公鑰、私鑰和數字證書的 .pfx 文件來簽署文本文件。 我已經能夠通過將 .pfx 文件加載到 java 密鑰庫來訪問私鑰和證書。 我想使用 .pfx 文件中的私鑰對數據進行簽名,然后附加數字證書。

        Certificate[] certificatechain = null;
    PrivateKey signerkey = null;
    Certificate certificate = null;
    PrivateKey pvtkey = null;
    File file = new File("C:\\Users\\21617\\Desktop\\Uttara Pers\\uttararead.txt"); 
    BufferedReader br = new BufferedReader(new FileReader(file));
    Enumeration<String> aliasList;
    String alias;
    String pfxPath = "D:\\Document Signer\\Test-Class3DocumentSigner2014\\Class 3 Docsigntest.pfx", certPassword = "password";
    File securityFileKeyPair = new File(pfxPath);
    InputStream cerFileStream = new FileInputStream(securityFileKeyPair);
    KeyStore keyStore = KeyStore.getInstance("PKCS12"); 
    keyStore.load(cerFileStream, certPassword.toCharArray());
    aliasList = keyStore.aliases();
    while (aliasList.hasMoreElements()) {
        alias = aliasList.nextElement();
    KeyStore.ProtectionParameter entryPassword = new KeyStore.PasswordProtection(certPassword.toCharArray());
    KeyStore.PrivateKeyEntry privateKeyEntry = (KeyStore.PrivateKeyEntry) keyStore.getEntry(alias, entryPassword);
    pvtkey = privateKeyEntry.getPrivateKey();
    System.out.println("Private key is:" +pvtkey);
    certificate = (X509Certificate) keyStore.getCertificate(alias);
    signerkey = (PrivateKey) keyStore.getKey(alias, certPassword.toCharArray());
    certificatechain = keyStore.getCertificateChain(alias);
    }

這就是我所在的地方,我希望能夠使用從相應 .pfx 文件加載的內容創建數字簽名。 我希望能夠使用從 .pfx 文件中獲得的私鑰和證書來執行相同的操作。

        File file = new File("C:\\Users\\21617\\Desktop\\Uttara Pers\\uttararead.txt"); 
    BufferedReader br = new BufferedReader(new FileReader(file));
    KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance("RSA");
    keyPairGen.initialize(2048);
    KeyPair pair = keyPairGen.generateKeyPair();
    PrivateKey privKey = pair.getPrivate();
    Signature sign = Signature.getInstance("SHA256withRSA");
    sign.initSign(privKey);
    byte[] bytes = "br".getBytes();
    sign.update(bytes);
    byte[] signature = sign.sign();
    String base64encodedString = Base64.getEncoder().encodeToString("signature".getBytes("utf-8"));
    System.out.println("Digital signature of the file: "+base64encodedString);  

這段代碼 ^ 是我為生成原始簽名而編寫的。 這里的sign對象用於調用和使用這里簽名所需的其他東西。 我必須為我的問題創建什么對象,它相當於此代碼中的符號對象。

我已經被困在這一點上很長一段時間了。 請指出我正確的方向。 謝謝你。

您幾乎擁有從 pfx 文件(它是 PKCS12 密鑰庫)中檢索 RSA 私鑰和證書的所有功能。

我將您的兩部分代碼組合成一個完整的運行示例。 對於驗證,有兩個選項可用:

  • 選項 1:使用公鑰驗證簽名(使用“certificate.getPublicKey()”獲取密鑰

  • 選項 2:使用證書驗證簽名

請注意,代碼沒有任何異常處理。 所選擇的簽名算法也是確定性的——有更好的簽名算法可用。

這是代碼的輸出:

RSA signature with PFX file
Private key is:SunRsaSign RSA private CRT key, 2048 bits
  params: null
  modulus: 20745681504295693338677598037425633054507196204877617419598634508842069647867075532992638954699743584297973637862386311040528331616364569181369404804703632552254162535558790075462853537556395029598445155559243819343605229254467273028470726088176140177653714749221474473368350858555614299113027040172126183258283581653894576374347297382002730107326970070574009149026236812216305173786045476886384540029067882067718179791112458402510855090943584133554670768670628348813208331767176300365697917644826900592782794277988966122352778692005555958605707879606264701810912582675085618198935971375640570974842583935544764079181
  private exponent: 7885872371866492400523922704859047113140413382606942721776113994907817554475557100232122642774005709324978550535236092293538639199641029455823040610567723486606889193674421751986368117667957229921364507305672856973738399242981654724587068805539527352575023907603420542297516770501204867777037850752521590511057404116851028618930420914266791736061751403423747879412785083579614624025989162418565474432973854813362120531945085369119091233141833194635650026465869705622286632392621017540662631025145908079890706307098133032113785352742799568343731292342294933488080974275377487016175861831017175736029834746462206620673
certificate is: [
[
  Version: V3
  Subject: EMAILADDRESS=Test@Test.com, CN=Test, OU=Test, O=Test, L=Test, ST=Test, C=DE
  Signature Algorithm: SHA256withRSA, OID = 1.2.840.113549.1.1.11

  Key:  Sun RSA public key, 2048 bits
  params: null
  modulus: 20745681504295693338677598037425633054507196204877617419598634508842069647867075532992638954699743584297973637862386311040528331616364569181369404804703632552254162535558790075462853537556395029598445155559243819343605229254467273028470726088176140177653714749221474473368350858555614299113027040172126183258283581653894576374347297382002730107326970070574009149026236812216305173786045476886384540029067882067718179791112458402510855090943584133554670768670628348813208331767176300365697917644826900592782794277988966122352778692005555958605707879606264701810912582675085618198935971375640570974842583935544764079181
  public exponent: 65537
  Validity: [From: Wed Jul 28 18:06:11 CEST 2021,
               To: Sat Jul 26 18:06:11 CEST 2031]
  Issuer: EMAILADDRESS=Test@Test.com, CN=Test, OU=Test, O=Test, L=Test, ST=Test, C=DE
  SerialNumber: [    7512a982 8d398731 a0e27f4d 4b0e2be2 45b2041c]

Certificate Extensions: 3
[1]: ObjectId: 2.5.29.35 Criticality=false
AuthorityKeyIdentifier [
KeyIdentifier [
0000: 83 B4 2A 8D 55 76 07 5F   DF 2C 62 9F DC 76 69 55  ..*.Uv._.,b..viU
0010: 56 64 EE C5                                        Vd..
]
]

[2]: ObjectId: 2.5.29.19 Criticality=true
BasicConstraints:[
  CA:true
  PathLen:2147483647
]

[3]: ObjectId: 2.5.29.14 Criticality=false
SubjectKeyIdentifier [
KeyIdentifier [
0000: 83 B4 2A 8D 55 76 07 5F   DF 2C 62 9F DC 76 69 55  ..*.Uv._.,b..viU
0010: 56 64 EE C5                                        Vd..
]
]

]
  Algorithm: [SHA256withRSA]
  Signature:
0000: 3C 69 CD 56 0B BF 4E 0E   B3 8C B4 D6 C3 AB D7 C4  <i.V..N.........
...
00F0: E1 81 C5 D8 F5 90 D4 09   CA ED 12 76 8C 12 F7 A3  ...........v....

]
Digital signature of the file: LiJEB4cjSNxmcibSg5V2dgFwydvyQ4xaCJswkIHZtCPkCu17jMZszFkv6kFOhXaPLuQ49vnghXXqdXzuuX5r5y3aNyoSZMjNtk+p9cG1t+eX9FrDMkUQ7Krrl6+K/Z5vMpKlfdxC6eZx6D4qlng1isHAlVSu9yzpgE3Wxtyl7I6v5Y7kFsx+LcAztoGVpZnH8Ta96HoG+B6NhmwfsgZ2GvrN9c5jA/S3bqEb4tFplkhFAwCWWEL1PvCTMREv8Y/Y7Muew9c35hAJKdweo/CCudrSflciEUUR1Emi+Z3KzDBMNgGZQmxBnZa4X88E5HJZdHl5HHnPeB6vStQLvtyg2g==
signatureVerified: true

這是完整的代碼:

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.security.*;
import java.security.cert.Certificate;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.Base64;
import java.util.Enumeration;

public class TestRsaSignatureWithPfxFile {
    public static void main(String[] args) throws IOException, KeyStoreException, CertificateException, NoSuchAlgorithmException, UnrecoverableEntryException, InvalidKeyException, SignatureException {
        System.out.println("RSA signature with PFX file");

        Certificate certificate = null;
        PrivateKey pvtkey = null;

        // load key from pfx keystore
        Enumeration<String> aliasList;
        String alias;
        String pfxPath = "pfxCertificate.pfx", certPassword = "password";
        File securityFileKeyPair = new File(pfxPath);
        InputStream cerFileStream = new FileInputStream(securityFileKeyPair);
        KeyStore keyStore = KeyStore.getInstance("PKCS12");
        keyStore.load(cerFileStream, certPassword.toCharArray());
        aliasList = keyStore.aliases();
        while (aliasList.hasMoreElements()) {
            alias = aliasList.nextElement();
            KeyStore.ProtectionParameter entryPassword = new KeyStore.PasswordProtection(certPassword.toCharArray());
            KeyStore.PrivateKeyEntry privateKeyEntry = (KeyStore.PrivateKeyEntry) keyStore.getEntry(alias, entryPassword);
            pvtkey = privateKeyEntry.getPrivateKey();
            System.out.println("Private key is:" + pvtkey);
            certificate = (X509Certificate) keyStore.getCertificate(alias);
            System.out.println("certificate is: " + certificate);

            // sign
            PrivateKey privKey = pvtkey;
            Signature sign = Signature.getInstance("SHA256withRSA");
            sign.initSign(privKey);
            byte[] bytes = "some testdata to sign".getBytes(StandardCharsets.UTF_8);
            sign.update(bytes);
            byte[] signature = sign.sign();
            String base64encodedString = Base64.getEncoder().encodeToString(signature);
            System.out.println("Digital signature of the file: " + base64encodedString);

            // verify
            PublicKey pubKey = certificate.getPublicKey();
            Signature verify = Signature.getInstance("SHA256withRSA");
            // verification with the public key inside certificate
            verify.initVerify(pubKey);
            // verification with the certificate itself
            //verify.initVerify(certificate);
            verify.update(bytes);
            boolean signatureVerified = verify.verify(signature);
            System.out.println("signatureVerified: " + signatureVerified);
        }
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM