【发布时间】:2015-08-14 16:14:54
【问题描述】:
我编写了以下代码来创建密钥对,将私钥存储在本地,然后从该文件中读取私钥。
当我尝试调用方法 savePrivateKey();和retrievePrivateKey();从 testData(View view) 我得到一个错误,说 (String[]) 不能应用于 ()。我希望能够在 testData(View view) 中调用上述两个函数;
public class EncryptionActivity extends ActionBarActivity {
private static final String TAG = EncryptionActivity.class.getSimpleName();
TextView textPublicKey;
TextView textPrivateKey;
Button buttonTest;
TextView privateKey;
Integer n;
String FILENAME = "privateKey";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_encryption);
// output keys to screen
textPrivateKey = (TextView)findViewById(R.id.textPrivateKey);
textPrivateKey.setMovementMethod(new ScrollingMovementMethod());
// textPublicKey = (TextView)findViewById(R.id.textPublicKey);
}
private void AsymmetricAlgorithmRSA() {
// Generate key pair for 1024-bit RSA encryption and decryption
Key publicKey = null;
Key privateKey = null;
try {
KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
kpg.initialize(1024);
KeyPair kp = kpg.genKeyPair();
publicKey = kp.getPublic();
privateKey = kp.getPrivate();
} catch (Exception e) {
Log.e(TAG, "RSA key pair error");
}
//textPublicKey.setText(String.valueOf(publicKey));
//textPrivateKey.setText(String.valueOf(privateKey));
}
public void savePrivateKey(String[] args) throws FileNotFoundException {
try {
// store private key locally
String string = String.valueOf(privateKey);
FileOutputStream fos = openFileOutput(FILENAME, Context.MODE_PRIVATE);
fos.write(string.getBytes());
fos.close();
}
catch (Exception e) {
Log.e(TAG, "Error saving file.");
}
}
public void retrievePrivateKey(String[] args) throws FileNotFoundException {
try {
FileInputStream fis = openFileInput(FILENAME);
StringBuffer fileContent = new StringBuffer("");
byte[] buffer = new byte[1024];
while ((n = fis.read(buffer)) != -1) ;
{
fileContent.append(new String(buffer, 0, n));
}
textPrivateKey.setText(String.valueOf(fileContent));
}
catch(IOException e) {
Log.e(TAG, "Error opening file.");
}
}
public void testData(View view){
AsymmetricAlgorithmRSA();
savePrivateKey();
retrievePrivateKey();
}
【问题讨论】:
-
那些方法并没有使用它们,所以只需删除每个方法签名中的
String[] args参数。 -
如果我这样做,我会得到 Unhandled exception: java.io.FileNotFoundException for both method calls inside testData();
-
这是一个不同的问题。
-
好的,但是假设上面的示例将使用 'String[] args' 你将如何将这些参数传递给方法调用?
-
在不知道
args将用于什么的情况下,我会说现在只传递一个虚拟值,例如savePrivateKey(null);。
标签: java android methods parameters