如何在java中生成,签名和读取数字签名?

时间:2014-04-22 01:27:04

标签: java digital-signature public-key-encryption private-key digital-certificate

我正在成为中级java程序员。我一直在努力寻找如何在java中为我正在研究的网络程序签名和读取数字签名。我已经能够使用http://docs.oracle.com/javase/tutorial/security/apisign/index.html上的教程生成私钥和公钥,但无法对它们执行任何操作。虽然我知道如何生成密钥但我没有把它放进去,因为我不确定我是否已经正确地完成了它们。 这是我的代码的简化版本: 主要课程:

    import java.io.File;
    import java.io.FileInputStream;
    import java.io.IOException;
    import java.security.KeyFactory;
    import java.security.KeyPair;
    import java.security.NoSuchAlgorithmException;
    import java.security.PrivateKey;
    import java.security.PublicKey;
    import java.security.spec.InvalidKeySpecException;
    import java.security.spec.PKCS8EncodedKeySpec;
    import java.security.spec.X509EncodedKeySpec;
    import java.util.Scanner;

public class Main {
public static void main(String[] args) throws IOException {
    Main main = new Main();
    Scanner s = new Scanner(System.in);
    while (true) {
        //This is where i added a command detector so that the program can be in one class
        System.out.println("Choose a command from the following:\nGenerate keys\nSign message\nRead message");
        String command = s.nextLine();
        if (command.equalsIgnoreCase("Generate key")
                || command.equalsIgnoreCase("Generate")) {

            /* The code for generating the keys is here */
            File f = new File("C:\\Users\\spencer\\Documents\\Stack ex\\src\\app","public.key");
            File fi = new File("C:\\Users\\spencer\\Documents\\Stack ex\\src\\app","private.key");
            if(!f.isFile()||!fi.isFile()) {
                Make make =new Make();
                Make.main(args);
            }
            else{
                try {
                    String path = "C:\\Users\\spencer\\Documents\\ds test 3\\src\\app";

                    KeyPair loadedKeyPair = main.LoadKeyPair(path, "DSA");
                    System.out.println("Key pair already exists!");
                    System.out.println("Loaded Key Pair:");
                    main.dumpKeyPair(loadedKeyPair);
                } catch (Exception e) {
                    e.printStackTrace();
                    return;
                }
            }

        }
        if (command.equalsIgnoreCase("Sign message")
                || command.equalsIgnoreCase("Sign")) {
            long signature = 0;
            System.out.println("What is your private key");
            String pkey = s.nextLine();
            long prkey = Long.parseLong(pkey);
            System.out.println("What is you message");
            String message = s.nextLine();
            /* The code for signing the message goes here */
            System.out.println("Signature:"+signature);
        } else if (command.equalsIgnoreCase("Read message")
                || command.equalsIgnoreCase("Read")) {
            String message = null;
            System.out.println("What is the signature");
            String sign = s.nextLine();
            long signature = Long.parseLong(sign);
            /* The code for reading the message goes here */
            System.out.println(message);
        }
    }
}
private void dumpKeyPair(KeyPair keyPair) {
    PublicKey pub = keyPair.getPublic();
    System.out.println("Public Key: " + getHexString(pub.getEncoded()));

    PrivateKey priv = keyPair.getPrivate();
    System.out.println("Private Key: " + getHexString(priv.getEncoded()));
}
private String getHexString(byte[] b) {
    String result = "";
    for (int i = 0; i < b.length; i++) {
        result += Integer.toString((b[i] & 0xff) + 0x100, 16).substring(1);
    }
    return result;
}
public KeyPair LoadKeyPair(String path, String algorithm)
        throws IOException, NoSuchAlgorithmException,
        InvalidKeySpecException {
    // Read Public Key.
    File filePublicKey = new File(path + "/public.key");
    FileInputStream fis = new FileInputStream(path + "/public.key");
    byte[] encodedPublicKey = new byte[(int) filePublicKey.length()];
    fis.read(encodedPublicKey);
    fis.close();

    // Read Private Key.
    File filePrivateKey = new File(path + "/private.key");
    fis = new FileInputStream(path + "/private.key");
    byte[] encodedPrivateKey = new byte[(int) filePrivateKey.length()];
    fis.read(encodedPrivateKey);
    fis.close();

    // Generate KeyPair.
    KeyFactory keyFactory = KeyFactory.getInstance(algorithm);
    X509EncodedKeySpec publicKeySpec = new X509EncodedKeySpec(
            encodedPublicKey);
    PublicKey publicKey = keyFactory.generatePublic(publicKeySpec);

    PKCS8EncodedKeySpec privateKeySpec = new PKCS8EncodedKeySpec(
            encodedPrivateKey);
    PrivateKey privateKey = keyFactory.generatePrivate(privateKeySpec);

    return new KeyPair(publicKey, privateKey);
}
    }

上课:

    import java.io.*;
    import java.security.*;
    import java.security.spec.*;

  public class Make {

public static void main(String args[]) {
    Make adam = new Make();
    try {
        String path = "C:\\Users\\spencer\\Documents\\Stack ex\\src\\app";

        KeyPairGenerator keyGen = KeyPairGenerator.getInstance("DSA");

        keyGen.initialize(512);
        KeyPair generatedKeyPair = keyGen.genKeyPair();

        System.out.println("Generated Key Pair");
        adam.dumpKeyPair(generatedKeyPair);
        adam.SaveKeyPair(path, generatedKeyPair);


    } catch (Exception e) {
        e.printStackTrace();
        return;
    }
}

private void dumpKeyPair(KeyPair keyPair) {
    PublicKey pub = keyPair.getPublic();
    System.out.println("Public Key: " + getHexString(pub.getEncoded()));

    PrivateKey priv = keyPair.getPrivate();
    System.out.println("Private Key: " + getHexString(priv.getEncoded()));
}

private String getHexString(byte[] b) {
    String result = "";
    for (int i = 0; i < b.length; i++) {
        result += Integer.toString((b[i] & 0xff) + 0x100, 16).substring(1);
    }
    return result;
}

public void SaveKeyPair(String path, KeyPair keyPair) throws IOException {
    PrivateKey privateKey = keyPair.getPrivate();
    PublicKey publicKey = keyPair.getPublic();

    // Store Public Key.
    X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(
            publicKey.getEncoded());
    FileOutputStream fos = new FileOutputStream(path + "/public.key");
    fos.write(x509EncodedKeySpec.getEncoded());
    fos.close();

    // Store Private Key.
    PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(
            privateKey.getEncoded());
    fos = new FileOutputStream(path + "/private.key");
    fos.write(pkcs8EncodedKeySpec.getEncoded());
    fos.close();
}
    }

我需要帮助签名和阅读签名。

0 个答案:

没有答案