package wei.aes;
import wei.aes.R;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
public class MainActivity extends Activity {
EditText et1,et2;
Button btn1,btn2;
String encrypt,decrypt;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
findviews();
}
private void findviews(){
et1=(EditText)findViewById(R.id.et1);
et2=(EditText)findViewById(R.id.et2);
btn1=(Button)findViewById(R.id.btn1);
btn2=(Button)findViewById(R.id.btn2);
btn1.setOnClickListener(listener);
btn2.setOnClickListener(listener);
}
OnClickListener listener=new OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
if(v.getId()==R.id.btn1){
try{
String encrypted=et1.getText().toString();
encrypt= AES_function.encrypt(encrypted);
}catch(Exception e){
}
et2.setText(encrypt);
}
else if(v.getId()==R.id.btn2){
try{
String decrypted=et2.getText().toString();
decrypt=AES_function.decrypt(decrypted);
}catch(Exception e){
}
et1.setText(decrypt);
}
}
};
@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;
}
}
------------------------------------------------------------------------------------------------------------
AES_function.java
package wei.aes;
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import android.util.Base64;
public class AES_function {
private static String key = "1AF4567SD123TR67";
public static String encrypt(String input)
{
byte[] crypted = null;
try
{
SecretKeySpec skey = new SecretKeySpec(key.getBytes(), "AES");
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, skey);
crypted = cipher.doFinal(input.getBytes());
}
catch(Exception e)
{
System.out.println(e.toString());
}
return new String(Base64.encode(crypted,Base64.DEFAULT));
}
public static String decrypt(String input)
{
byte[] output = null;
try
{
SecretKeySpec skey = new SecretKeySpec(key.getBytes(), "AES");
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE, skey);
output = cipher.doFinal(Base64.decode(input, Base64.DEFAULT));
}
catch (Exception e)
{
System.out.println(e.toString());
}
return new String(output);
}
}
沒有留言:
張貼留言