使用DSA生成数字签名

时间:2015-09-03 09:55:46

标签: java security cryptography

我想要一个如下代码的数字签名:签名[publickey,a || b]。

Integer a;
String b,c;
a=12; b= "i am fine";
c=a+b;  
Signature DSA = Signature.getInstance(c, "SUN"); 
DSA.initSign(pvKey);

1 个答案:

答案 0 :(得分:0)

"12iamfine"不是Signature.getInstance()的有效参数。您需要传递算法的名称,而不是您要签名的数据(我假设c是...)。

我总结了以下博客中用于生成签名的代码:https://compscipleslab.wordpress.com/2012/11/18/generating-verifying-digital-signatures/

//Create a KeyPairGenerator object for generating keys for the DSA signature algorithm.
KeyPairGenerator keyGen = KeyPairGenerator.getInstance("DSA", "SUN");

//Instantiate SecureRandom Object, which will act as a source of random numbers. 
//Here, we use SHA1PRNG 
SecureRandom random = SecureRandom.getInstance("SHA1PRNG", "SUN");

//Initialize the KeyPairGenerator with the key-length and the source of randomness
keyGen.initialize(1024, random);

//Generate the key-pair
KeyPair pair = keyGen.generateKeyPair();

//Collect the public & private key from the KeyPair into separate objects
PrivateKey privkey = pair.getPrivate();
PublicKey pubkey = pair.getPublic();

//Create a Signature object, you have to supply two arguments,first the algorithm 
//name & the provider. Here we use SHA1withDSA supplied by the SUN provider
Signature dsa = Signature.getInstance("SHA1withDSA", "SUN");

//Initialize it with the private key before using it for signing.
dsa.initSign(privkey);

//Supply the Signature Object the data to Be Signed
BufferedInputStream bufin = new BufferedInputStream(new FileInputStream(inputfile));
byte[] buffer = new byte[1024];
int len;

while ((len = bufin.read(buffer)) >=0) {
    dsa.update(buffer, 0, len);
}

bufin.close();

//Sign the data i.e. generate a signature for it
byte[] realSig = dsa.sign();