我是Android的新手,我正试图制作一个简单的"关于cypher / decypher应用程序的教程。我有以下代码
public class MainActivity extends AppCompatActivity {
KeyPairGenerator kpg;
KeyPair kp;
PublicKey publicKey;
PrivateKey privateKey;
byte[] encryptedBytes, decryptedBytes;
Cipher cipher, cipher1;
String encrypted, decrypted;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
try {
generateKey();
TextView txtPuk = (TextView) findViewById(R.id.tViewPUK);
txtPuk.setText(kp.getPublic().toString());
}catch(Exception e){
e.printStackTrace();
Toast.makeText(getBaseContext(), e.toString(),Toast.LENGTH_LONG).show();
}
setContentView(R.layout.activity_main);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public void generateKey() throws NoSuchAlgorithmException, NoSuchPaddingException,
IllegalBlockSizeException,BadPaddingException,InvalidKeyException{
try{
kpg = KeyPairGenerator.getInstance("RSA");
kpg.initialize(1024); //NULLPOINTER HERE
kp = kpg.genKeyPair();
}catch(Exception e){
e.printStackTrace();
Toast.makeText(getBaseContext(), e.toString(),Toast.LENGTH_LONG).show();
}
}
public byte[] RSAEncrypt(final String plain) throws NoSuchAlgorithmException, NoSuchPaddingException,
IllegalBlockSizeException, BadPaddingException, InvalidKeyException {
;
publicKey = kp.getPublic();
privateKey = kp.getPrivate();
cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.ENCRYPT_MODE, publicKey);
encryptedBytes = cipher.doFinal(plain.getBytes());
return encryptedBytes;
}
public String RSADecrypt(final byte[] encryptedBytes) throws NoSuchAlgorithmException, NoSuchPaddingException,
InvalidKeyException, IllegalBlockSizeException, BadPaddingException {
cipher1 = Cipher.getInstance("RSA");
cipher1.init(Cipher.DECRYPT_MODE, privateKey);
decryptedBytes = cipher1.doFinal(encryptedBytes);
decrypted = new String(decryptedBytes);
return decrypted;
}
}
但正如标题所说,我在kpg.initialize(1024)
得到了一个NullPointer。
由于理论似乎是正确的,我觉得这可能是一个盲目的伎俩,我没有遵循,所以可能是这种情况发生的原因
编辑:编辑代码以删除还原代码,如sugested
答案 0 :(得分:3)
问题是在findViewById(R.id.tViewPUK)
之前调用setContentView(R.layout.activity_main);
。