我正在尝试使用 DSA 签名和验证文本。我已经编写了示例代码来签名。但它不起作用。你能帮忙吗?这只是一个测试,因为这个想法是对数据进行签名,记录在标签中,当我读取标签时,我想用数字签名验证数据。
import java.io.FileOutputStream;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.SecureRandom;
import java.security.Signature;
import android.os.Bundle;
import android.app.Activity;
import android.app.AlertDialog;
import android.text.Editable;
import android.view.Menu;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends Activity {
private EditText texto;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
texto = (EditText) findViewById(R.id.texto);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
public void test (View v){
if(v.getId() == R.id.button1)
firmar(texto.getText().toString());
}
public void firmar (String string){
try{
KeyPairGenerator keyGen = KeyPairGenerator.getInstance("DSA","SUN");
SecureRandom random = SecureRandom.getInstance("SHA1PRNG", "SUN");
keyGen.initialize(1024, random);
KeyPair pair = keyGen.generateKeyPair();
PrivateKey priv = pair.getPrivate();
PublicKey pub = pair.getPublic();
/* Create a Signature object and initialize it with the private key */
Signature dsa = Signature.getInstance("SHA1withDSA");
dsa.initSign(priv);
/* Update and sign the data */
//String string = texto.getText().toString();
byte [] bytes = string.getBytes();
dsa.update(bytes);
byte[] realSig = dsa.sign();
AlertDialog.Builder newAlert= new AlertDialog.Builder(this);
newAlert.setTitle("Firmado");
newAlert.show();
} catch (Exception e) {
AlertDialog.Builder newAlert= new AlertDialog.Builder(this);
newAlert.setTitle("No Firmado");
newAlert.show();
}
}
}