0
我已經加載了兩個密鑰,並且我想在與其中一個簽名後驗證它們,但是我遇到了困難。最後我得到「驗證:錯誤」,沒有任何錯誤。有人可以指出缺陷嗎?驗證私鑰和公鑰RSA密鑰匹配
package fliesigning;
import static fliesigning.FlieSigning.verifySig;
import java.io.*;
import java.nio.ByteBuffer;
import java.security.*;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.math.BigInteger;
import java.security.Provider;
import java.security.Security;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.RSAPrivateKeySpec;
import java.security.spec.RSAPublicKeySpec;
import javax.crypto.Cipher;
import org.apache.commons.codec.binary.Base64;
public class Signing {
private static final String BEGIN_RSA_PRIVATE_KEY = "<PRIVATE KEY>";
private static final String BEGIN_RSA_PUBLIC_KEY = "<PUBLIC KEY>";
public static void main(String[] args) throws Exception {
// Remove the first and last lines
String privKeyPEM = BEGIN_RSA_PRIVATE_KEY.replace("-----BEGIN RSA PRIVATE KEY-----\n", "");
privKeyPEM = privKeyPEM.replace("-----END RSA PRIVATE KEY-----", "");
System.out.println(privKeyPEM);
String publicKeyPEM = BEGIN_RSA_PUBLIC_KEY.replace("-----BEGIN PUBLIC KEY-----\n", "");
publicKeyPEM = publicKeyPEM.replace("-----END PUBLIC KEY-----", "");
System.out.println(publicKeyPEM);
// Base64 decode the data
Base64 b64 = new Base64();
byte [] encoded = b64.decode(privKeyPEM);
byte [] encoded_pub = b64.decode(publicKeyPEM);
// PKCS8 decode the encoded RSA private key
PKCS8EncodedKeySpec privateKeySpec = new PKCS8EncodedKeySpec(encoded);
KeyFactory kf = KeyFactory.getInstance("RSA");
PrivateKey privKey = kf.generatePrivate(privateKeySpec);
X509EncodedKeySpec publicKeySpec = new X509EncodedKeySpec(encoded_pub);
KeyFactory pk = KeyFactory.getInstance("RSA");
PublicKey publicKey = pk.generatePublic(publicKeySpec);
// Display the results
System.out.println(privKey);
String file = "qwerty";
byte[] fileBytes = file.getBytes();
byte[] digitalSignature = signData(fileBytes, privKey);
System.out.println("SIGNATURE MADE");
boolean verified;
verified = verifySig(fileBytes, publicKey, digitalSignature);
System.out.println("verified: " + verified) ;
}
public static byte[] signData(byte[] data, PrivateKey key) throws Exception {
Signature signer = Signature.getInstance("SHA256withRSA");
signer.initSign(key);
signer.update(data);
return (signer.sign());
}
public static boolean verifySig(byte[] data, PublicKey key, byte[] sig) throws Exception {
Signature signer = Signature.getInstance("SHA256withRSA");
signer.initVerify(key);
signer.update(data);
return (signer.verify(sig));
}
}
嗯,它的作品,謝謝!只是想問一下,我是否可以以某種方式優化代碼,使其更好? – 2014-10-08 13:29:30
另一個問題,我怎樣才能從文件而不是字符串中讀取密鑰? – 2014-10-08 13:39:16
@davidguetta你的第一個問題可能適用於http://codereview.stackexchange.com。在發佈之前請檢查幫助頁面。對於第二個問題,我認爲Google會幫助你。 – 2014-10-08 13:42:16