不好意思问一个具体的问题,但我需要在Java代码中生成一个像红宝石下面的代码行“签名”:加密数据与红宝石生成的RSA public.pem文件
signature = OpenSSL::PKey::RSA.new(File.read("PUBLIC_PEM_PATH")).public_encrypt('SECRET_KEY')
我的.PEM密钥文件,这就是是SECRET_KEY一样的东西:F6qxlwQTYWRM3gRfgftryKJHKYZiGXdoy5lDm4
我怎样才能做到这一点?
谢谢!
更新1 我尝试这样做:
File pubKeyFile = new File(keyFileName);
DataInputStream inputStream;
byte[] signature = null;
try {
inputStream = new DataInputStream(new FileInputStream(pubKeyFile));
byte[] pubKeyBytes = new byte[(int)pubKeyFile.length()];
inputStream.readFully(pubKeyBytes);
inputStream.close();
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
X509EncodedKeySpec pubSpec = new X509EncodedKeySpec(pubKeyBytes);
RSAPublicKey pubKey = (RSAPublicKey) keyFactory.generatePublic(pubSpec);
Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
cipher.init(Cipher.ENCRYPT_MODE, pubKey);
signature = cipher.doFinal(secretKey.getBytes());
} catch (Exception e) {
e.printStackTrace();
}
return signature;
而得到这个错误:
java.security.spec.InvalidKeySpecException: java.lang.RuntimeException: error:0D0680A8:asn1 encoding routines:ASN1_CHECK_TLEN:wrong tag
UPDATE2 我设法加载从.PEM文件中的公钥。但是现在,我从密码中得到一个错误。
public static byte[] getSignature(String keyFileName, byte[] secretKey){
byte[] signature = null;
try {
PublicKey pubKey = readKeyFromFile(keyFileName);
Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
cipher.init(Cipher.ENCRYPT_MODE, pubKey);
signature = cipher.doFinal(secretKey);
} catch (Exception e) {
e.printStackTrace();
}
return signature;
}
private static PublicKey readKeyFromFile(String keyFileName) throws IOException {
InputStream in = new FileInputStream(keyFileName);
DataInputStream din = new DataInputStream(in);
try {
BigInteger m = BigInteger.valueOf(din.readLong());
BigInteger e = BigInteger.valueOf(din.readLong());
RSAPublicKeySpec keySpec = new RSAPublicKeySpec(m, e);
KeyFactory fact = KeyFactory.getInstance("RSA");
RSAPublicKey pubKey = (RSAPublicKey) fact.generatePublic(keySpec);
return pubKey;
} catch (Exception e) {
throw new RuntimeException("Spurious serialisation error", e);
} finally {
din.close();
}
}
错误日志:
javax.crypto.IllegalBlockSizeException: input must be under 8 bytes
有什么想法?
使用Signature类。 – EJP
这看起来不像签名方案。你有什么要求? – Henry
“要求”是什么意思?我只是想用Java生成'签名'。 – dum4ll3