android keystore public key, private key, certificate complete resolution

Keywords: Java Apache

Preface

Before I did not understand the concept of public key, private key and certificate, I recently summarized and sorted it out. Now share it.

Note: The concept of public key, private key and certificate is derived from the generated signature.

Generate key.store

Run - CMD - DOS window
Generate java keystore file

C:\Users\weichyang>keytool -genkey -alias test -keyalg RSA -keystore key.keysto
e
 Enter the keystore password:
Enter a new password again:
What's your name and surname?
  [Unknown]:  yang
 What is the name of your organization?
  [Unknown]:  nuoyuan
 What is the name of your organization?
  [Unknown]:  nuoyuan
 What is the name of your city or region?
  [Unknown]:  bj
 What is the name of your province/city/autonomous region?
  [Unknown]:  bj
 What is the double-letter country/region code for the unit?
  [Unknown]:  010
 Is CN=yang, OU=nuoyuan, O=nuoyuan, L=bj, ST=bj, C=010 correct?
  [no]: Yes.

Enter the key password of <test>.
        (If the password is the same as the keystore password, press Enter):

Look at the three key points above:

The following steps for keystores, key passwords, and aliases will be used

Extracting public keys from keystore

1. First extract the certificate, then view the public key information

C:\Users\weichyang>keytool -export -alias test -keystore key.keystore -file zhen
gshu.cer
 Enter the keystore password:
Certificates stored in file < Zhengshu >

- Export export certificate
- alias certificate alias
- keystore extracts the keystore name of the certificate
- Filzhengshu. cer Extracts Certificate Name

Find the certificate generation path and double-click to view the public key

This extracts the public key

Private key extraction

The extraction of private keys is a little cumbersome. But there is no need to worry about ready-made extraction methods.

But we can't extract the private key through the KEYTOOL tool. We can only extract the private key through java's KeyStore class getEntry() or getKey().

Posting method

  import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.security.Key;
import java.security.KeyPair;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.UnrecoverableKeyException;
import java.security.cert.Certificate;

import sun.misc.BASE64Encoder;

public class ExportPrivateKey {
    private File keystoreFile;
    private String keyStoreType;
    private char[] password;
    private String alias;
    private File exportedFile;

    public static KeyPair getPrivateKey(KeyStore keystore, String alias,
            char[] password) {
        try {
            Key key = keystore.getKey(alias, password);
            if (key instanceof PrivateKey) {
                Certificate cert = keystore.getCertificate(alias);
                PublicKey publicKey = cert.getPublicKey();
                return new KeyPair(publicKey, (PrivateKey) key);
            }
        } catch (UnrecoverableKeyException e) {
        } catch (NoSuchAlgorithmException e) {
        } catch (KeyStoreException e) {
        }
        return null;
    }

    public void export() throws Exception {
        KeyStore keystore = KeyStore.getInstance(keyStoreType);
        BASE64Encoder encoder = new BASE64Encoder();
        keystore.load(new FileInputStream(keystoreFile), password);
        KeyPair keyPair = getPrivateKey(keystore, alias, password);
        PrivateKey privateKey = keyPair.getPrivate();
        String encoded = encoder.encode(privateKey.getEncoded());
        FileWriter fw = new FileWriter(exportedFile);
        fw.write("—–BEGIN PRIVATE KEY—–/n");
        System.out.println("—–BEGIN PRIVATE KEY—–/n");
        fw.write(encoded);
        System.out.println(encoded + "/n");
        fw.write("/n");
        fw.write("—–END PRIVATE KEY—–");
        System.out.println("—–END PRIVATE KEY—–");
        fw.close();

    }

    public static void main(String args[]) throws Exception {
        ExportPrivateKey export = new ExportPrivateKey();
        export.keystoreFile = new File("c:/Users/weichyang/key.keystore");
        export.keyStoreType = "JCEKS";
        export.password = "123456".toCharArray();
        export.alias = "test";
        export.exportedFile = new File("c:/Users/weichyang/11111.txt");
        export.export();
    }
}

Executing the above code generates a private key in the specified file and outputs it to the console

Output private key:

MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQCltQnLjqHJOry7T3iP15XV1VVn
ORP9MPi/J03j52ygU948L4iSHIJymtS8wtm+XhqVPTTn/a5aqc4D+lqPXiok0NKgWGNFZbnKc2eQ
b2KXOWg3yaqPIXrvtKQ9vDPeJvNobf9+wILH7L80B4D135/S+lIbHS6V2PxQH5LkWQHx+0R3OBbs
lzs1FbGL2KEL4UWxUbVeCtfW2wkD2H+u7NeBHq5nSvXfHagjYDHXAGZbUCeZ4ESvKpJf7u5f0wRx
pyhDHtv/G+rixnLL0PO50HfAW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N2iyXNgOlOM2NCpDkQdbEqGrBKdAPiWVEiJzs+BuGuMRi/c9yRE+GoI
MxFlAoGBALHWCUJNKCGYSz6Azf1Nscr/PJusGKFCMd1IoHlPrQKMKaxI62ohiyAqyBY0q4EiRg0K
yzVvP8T3PHHgAaREUAWhUjTbGUk56PiEWwMtIfrLxuFJA0ZsviWKkQXopHgf8r1fhpfBWJUQkNgz
tK0rNFvbmRQh2TchFpopgwPxpn0y/n

Public key in certificate:

30 82 01 0a 02 82 01 01 00 a5 b5 09 cb 8e a1 c9 3a bc bb 4f 78 8f d7 95 d5 
d5 55 67 39 13 fd 30 f8 bf 27 4d e3 e7 6c a0 53 de 3c 2f 88 92 1c 82 72 9a 
d4 bc c2 d9 be 5e 1a 95 3d 34 e7 fd ae 5a a9 ce 03 fa 5a 8f 5e 2a 24 d0 d2 
a0 58 63 45 65 b9 ca 73 67 90 6f 62 97 39 68 37 c9 aa 8f 21 7a ef b4 a4 3d
bc 33 de 26 f3 68 6d ff 7e c0 82 c7 ec bf 34 07 80 f5 df 9f d2 fa 52 1b 1d 
2e 95 d8 fc 50 1f 92 e4 59 01 f1 fb 44 77 38 16 ec 97 3b 35 15 b1 8b d8 a1
0b e1 45 b1 51 b5 5e 0a d7 d6 db 09 03 d8 7f ae ec d7 81 1e ae 67 4a f5 df 
1d a8 23 60 31 d7 00 66 5b 50 27 99 e0 44 af 2a 92 5f ee ee 5f d3 04 71 a7 
28 43 1e db ff 1b ea e2 c6 72 cb d0 f3 b9 d0 77 c0 58 7f 2c 2f 55 2e f6 3c
0b 1a e3 f2 fe e0 18 46 ef 01 99 c4 4c da 82 5c d9 1f b2 d9 ac cb 5b 0a 4a
35 27 c3 b0 56 36 19 93 1e 86 f3 b8 2c 93 d1 02 03 01 00 01

Public-key and private-key verification methods:

Public key encryption, private key decryption, and vice versa.

Verify whether public and private keys are paired

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.security.Key;
import java.security.KeyPair;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.UnrecoverableKeyException;
import java.security.cert.Certificate;
import java.security.cert.CertificateException;
import java.security.cert.CertificateFactory;

import javax.crypto.Cipher;

import com.sun.org.apache.bcel.internal.generic.NEW;

import sun.misc.BASE64Encoder;

public class ExportPrivateKey {
    private File keystoreFile;
    private String keyStoreType;
    private char[] password;
    private String alias;
    private File exportedFile;

    public static KeyPair getPrivateKey(KeyStore keystore, String alias,
            char[] password) {
        try {
            Key key = keystore.getKey(alias, password);
            if (key instanceof PrivateKey) {
                Certificate cert = keystore.getCertificate(alias);
                PublicKey publicKey = cert.getPublicKey();
                return new KeyPair(publicKey, (PrivateKey) key);
            }
        } catch (UnrecoverableKeyException e) {
        } catch (NoSuchAlgorithmException e) {
        } catch (KeyStoreException e) {
        }
        return null;
    }

    public PrivateKey export() throws Exception {
        KeyStore keystore = KeyStore.getInstance(keyStoreType);
        BASE64Encoder encoder = new BASE64Encoder();
        keystore.load(new FileInputStream(keystoreFile), password);
        KeyPair keyPair = getPrivateKey(keystore, alias, password);
        PrivateKey privateKey = keyPair.getPrivate();
        String encoded = encoder.encode(privateKey.getEncoded());
        FileWriter fw = new FileWriter(exportedFile);
        fw.write("—–BEGIN PRIVATE KEY—–/n");
        System.out.println("—–BEGIN PRIVATE KEY—–/n");
        fw.write(encoded);
        System.out.println(encoded + "/n");
        fw.write("/n");
        fw.write("—–END PRIVATE KEY—–");
        System.out.println("—–END PRIVATE KEY—–");
        fw.close();

        return privateKey;

    }

    public static void main(String args[]) throws Exception {
        ExportPrivateKey export = new ExportPrivateKey();
        export.keystoreFile = new File("c:/Users/weichyang/key.keystore");
        export.keyStoreType = "JCEKS";
        export.password = "123456".toCharArray();
        export.alias = "test";
        export.exportedFile = new File("c:/Users/weichyang/11111.txt");
        PrivateKey  privateKey=export.export();



      // Verify encryption and decryption
        PublicKey pKey = gePublic();
        byte[] plainText = "I encrypt with this string of characters".getBytes("UTF-8");
        Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
        cipher.init(Cipher.ENCRYPT_MODE, pKey);
        // Encrypted with a public key, returning a byte stream
        byte[] cipherText = cipher.doFinal(plainText);


        System.out.println("====================================");

        System.out.println(new String(cipherText,"Utf-8"));

        System.out.println("====================================");



        cipher.init(Cipher.DECRYPT_MODE, privateKey);
        // Decrypt with the private key and return a byte stream
        byte[] newPlainText = cipher.doFinal(cipherText);
        System.out.println(new String(newPlainText, "UTF-8"));

    }


private static PublicKey gePublic() {
    // Generate a certificate object and initialize it with the data read from the input stream inStream.
    try {
        CertificateFactory cf = CertificateFactory.getInstance("X.509");
        FileInputStream in = new FileInputStream(
                "C:/Users/weichyang/zhengshu.cer");
        Certificate c = cf.generateCertificate(in);
        PublicKey publicKey = c.getPublicKey();

        return publicKey;
    } catch (CertificateException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    return null;
}
}

Output:

Encryption String: I use this string to encrypt
 Public key encryption byte []====================================
:K??+
H????? P??? Y??????] <4???? w?? u_5??(?????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????
====================================
Decrypted String: I use this string to encrypt

The results show that the extracted public key and private key are correct.

Conclusion:

The generation of public key and private key has something to do with the content in our keystore, that is to say, the content is encrypted with algorithm. Generate public key and private key.
There are public and private keys in the keystore. When we sign apk with keystore, we publish public key information and certificates in the *. RSA file of MET-INF. Provide the platform for later apk uniqueness checking.
The key store password, the key password is the password used by the extracted key. That is to say, the password you enter when you generate the keystore. Without the password, you can't extract the information. An alias is an alias given to the generated keystore file

Quote:
Extracting Private Key and Certificate from Java Keystore File http://blog.csdn.net/zbuger/article/details/51690900
keystore extracts private keys and certificates http://ieroot.com/2014/06/03/1623.html

Posted by touchingvirus on Mon, 20 May 2019 10:59:59 -0700