密钥对的存储和加载

类别:Java 点击:0 评论:0 推荐:

主要用于数字签名:

1.存储密钥对

首先使用KeyPairGeneration产生密钥对:

        KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
        keyGen.initialize(1024);
        KeyPair keyPair = keyGen.genKeyPair();
        privateKey = keyPair.getPrivate();
        publicKey = keyPair.getPublic();

 

将密钥存储为文件的方法:

        FileOutputStream fs = new FileOutputStream(fileName);
        fs.write(privateKey.getEncoded());
        fs.close();

2.加载密钥对

假设公钥文件为public.dat、private.dat

首先读取公钥文件:

        //read public key
        FileInputStream fsPublicKey = new FileInputStream(publicKeyFile);
        BufferedInputStream bfsPublicKey = new BufferedInputStream(fsPublicKey);
        byte[] bytePublicKey = new byte[bfsPublicKey.available()];
        bfsPublicKey.read(bytePublicKey);
        bfsPublicKey.close();

使用KeyFactory产生公钥

        //build public key
        X509EncodedKeySpec  pubKeySpec = new X509EncodedKeySpec(
                byteEncodedPublicKey);
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        PublicKey pubKey = keyFactory.generatePublic(pubKeySpec);

 

主意,私钥的的处理和公钥相同,唯一不同的是私钥的KeySpec不同。私钥应使用PKCS8EncodedKeySpec

 

本文地址:http://com.8s8s.com/it/it15367.htm