使用来自 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 解码任何输入。