0

Apache Commons API の Base64 関数を使用し、DSA を使用して、ファイルから Base 64 でエンコードされた公開鍵をロードしようとしています。

/**
 * Load a base-64 encoded public key in X.509 format
 * @param pkfile the name of the file containing the public key 
 * @return an instance of PublicKey on success or null on failure
 */
public PublicKey loadBase64PublicKey(String pkfile) { 
    PublicKey pub;
    Base64InputStream bis;
    byte[] buffer;

    // load the contents of the pkfile into the buffer
    try {
        bis = new Base64InputStream(new FileInputStream(pkfile));
        buffer = new byte[bis.available()];
        bis.read(buffer);
        bis.close();
    } catch (Exception e) {
        System.err.println(e.toString());
        return null;
    }

    // use a KeyFactory to parse the data
    try {
        KeyFactory kf = KeyFactory.getInstance("DSA");
        pub = kf.generatePublic(new X509EncodedKeySpec(buffer));
    } catch (Exception e) {
        e.printStackTrace();
        return null;
    }

    return pub;
}

主な方法:

public static void main(String args[]) {
    DigitalSignatureA DSA = new DigitalSignatureA();

    // load public key
    PublicKey pubKey;
    pubKey = DSA.loadBase64PublicKey("sign\\pubkey-1.dat");
}   

ただし、main からメソッドを呼び出すと、次のエラーが発生します。

java.security.spec.InvalidKeySpecException: Inappropriate key specification: IOException: Short read of DER length
at sun.security.provider.DSAKeyFactory.engineGeneratePublic(Unknown Source)
at java.security.KeyFactory.generatePublic(Unknown Source)
at DigitalSignatureAssignment.loadBase64PublicKey(DigitalSignatureAssignment.java:147)
at DigitalSignatureAssignment.main(DigitalSignatureAssignment.java:224)

行 147 はpub = kf.generatePublic(new X509EncodedKeySpec(buffer)); 、ファイルの公開鍵は X509 でエンコードされていますが、base64 エンコードで保存され、Base64InputStream はすべての入力をデコードします。

4

1 に答える 1