首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >需要Javax.crypto Base64帮助

需要Javax.crypto Base64帮助
EN

Stack Overflow用户
提问于 2012-11-09 08:27:49
回答 1查看 346关注 0票数 0

我是一个新手安卓程序员,需要帮助加密和解密存储在SharedPreferences中的EditText字符串。这似乎应该是一个非常常见的过程,并且应该有许多教程介绍如何实现这一点,但我还没有找到非常好的信息或指导。我按照给出的说明操作,但是在检查HERE文件时,我的数据以明文显示。任何帮助都将不胜感激。

类接收EditText字符串并进行编码:

代码语言:javascript
复制
private SharedPreferences sp;


Intent i;
Button regBttn,rtnBttn;
EditText rName,rPwd;
String user, pass, chk;
String stat="a";
String key = "N@!an@jajpn!==";


/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState)
{


     super.onCreate(savedInstanceState);
     setContentView(R.layout.register);

    rName=(EditText)findViewById(R.id.reg_uname);
    rPwd=(EditText)findViewById(R.id.reg_pswd);
    regBttn=(Button)findViewById(R.id.reg_button);
    rtnBttn=(Button)findViewById(R.id.rtn_button); 
    regBttn.setOnClickListener(this);
    rtnBttn.setOnClickListener(this);

    sp=this.getSharedPreferences("AccessApp", MODE_WORLD_READABLE);
    chk=sp.getString("USERNAME_KEY", "");
    if(chk.length()!=0){
    sp=getSharedPreferences("AccessApp",MODE_WORLD_WRITEABLE); 

    i=new Intent(this,AccessApp.class);
    startActivity(i); 

    }     
   }

public void onClick(View arg0) {
    user=rName.getText().toString().trim();
    pass=rPwd.getText().toString().trim();

    if(arg0==regBttn){     
       if((user.length()!=0))
        {
         if((pass.length()!=0))
            {

        sp=getSharedPreferences("AccessApp",MODE_WORLD_WRITEABLE);
        Editor myEditor=sp.edit();

        try {

            byte[ ] superSecretKeyBytes = Base64.decode(user);
            byte[] key = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6 };
            for (int i = 0; i < superSecretKeyBytes.length && i < key.length; i++) {
                key[i] = superSecretKeyBytes[i];
                myEditor.putString("USERNAME_KEY", user);
            }
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }   
        try {

            byte[ ] superSecretKeyBytes = Base64.decode(pass);
            byte[] key = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6 };
            for (int i = 0; i < superSecretKeyBytes.length && i < key.length; i++) {
                key[i] = superSecretKeyBytes[i];
                myEditor.putString("PASSWORD_KEY", pass);
            }
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        myEditor.commit();
        Toast.makeText(this, "Registration is successfull",10000).show();
        i=new Intent(this,AccessApp.class);
        startActivity(i);
        }
        else
         {
          Toast.makeText(this, "Please Enter password", 10000).show();  
         }
         }
        else{
            Toast.makeText(this,"Please Enter Username",10000).show();
         }
        }

    else if(arg0==rtnBttn){
        AlertDialog.Builder builder=new AlertDialog.Builder(this);
         builder.setTitle("Exit");
         builder.setMessage("Do you want to exit");
         builder.setCancelable(false);
         builder.setPositiveButton("Yes",new DialogInterface.OnClickListener() {

  public void onClick(DialogInterface dialog, int which) {
  // TODO Auto-generated method stub
  finish();
  }
  });
    builder.setNegativeButton("No", new DialogInterface.OnClickListener() {

            public void onClick(DialogInterface arg0, int arg1) {
               arg0.cancel();
            }
        });
    AlertDialog alert=builder.create();
    alert.show();

    }
}
public String encrypt(String toencrypt, byte key[]) throws Exception {
    SecretKeySpec secret = new SecretKeySpec(key, "AES");
    Cipher cipher = Cipher.getInstance("AES");
    cipher.init(Cipher.ENCRYPT_MODE, secret);
    byte[] encryptedbytes = cipher.doFinal(toencrypt.getBytes());
    String encrypted = Base64.encodeBytes(encryptedbytes, 0);
    return encrypted;

}

}

用于解密和比较的类:

代码语言:javascript
复制
public class AccessApp extends Activity implements OnClickListener {
private SharedPreferences sp;
String user,pass;
Button lBttn,cBttn;
EditText uname,pword;
Intent i;

int flag=0;

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState)
{ 
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    lBttn=(Button)findViewById(R.id.login_button);
    cBttn=(Button)findViewById(R.id.cancel_button);
    uname=(EditText)findViewById(R.id.username);
    pword=(EditText)findViewById(R.id.password);

    lBttn.setOnClickListener(this);
    cBttn.setOnClickListener(this);
}
public void onClick(View arg0) {

    sp=this.getSharedPreferences("AccessApp", MODE_WORLD_READABLE);
    user = sp.getString("USERNAME_KEY", "");
    pass = sp.getString("PASSWORD_KEY", "");




   if(lBttn.equals(arg0)){

      if((uname.getText().toString().equals(user))&& 
        (pword.getText().toString().equals(pass)))

            {
          Toast.makeText(this, "You are Logged In", 20000).show();

               Intent intent;
               intent=new Intent(this,details.class);
               startActivity(intent);
              flag=1;
            }

        else 
           {
            Toast.makeText(this, "Wrong Username or Password",20000).show();
            flag=0;   
           }       
        } 
        else if(cBttn==arg0){
            AlertDialog.Builder builder=new AlertDialog.Builder(this);
          builder.setTitle("Exit");
         builder.setMessage("Do you want to exit");
    builder.setCancelable(false);
    builder.setPositiveButton("Yes",new DialogInterface.OnClickListener() {

 public void onClick(DialogInterface dialog, int which) {
 // TODO Auto-generated method stub
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_HOME);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);

 finish();
 }
 });
    builder.setNegativeButton("No", new DialogInterface.OnClickListener() {

            public void onClick(DialogInterface arg0, int arg1) {
               arg0.cancel();
            }
        });
    AlertDialog alert=builder.create();
    alert.show();

        }

    }
@Override
public boolean onKeyDown(int keyCode, KeyEvent event)  {
 if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {

     Intent intent = new Intent(Intent.ACTION_MAIN);
        intent.addCategory(Intent.CATEGORY_HOME);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(intent);
     finish();
 }
 return super.onKeyDown(keyCode, event);
}

public static String decrypt(String encryptedText, byte[ ] key) throws Exception {
    SecretKeySpec skeySpec = new SecretKeySpec(key, "AES");
    Cipher cipher = Cipher.getInstance("AES");
    cipher.init(Cipher.DECRYPT_MODE, skeySpec);
    byte[] toDecrypt = Base64.decode(encryptedText);
    byte[] encrypted = cipher.doFinal(toDecrypt);
    return new String(encrypted);
}
}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2012-11-09 08:50:57

您似乎要将未加密的用户名和密码保存到编辑器:

代码语言:javascript
复制
        byte[ ] superSecretKeyBytes = Base64.decode(pass);  
        byte[] key = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6 };
        for (int i = 0; i < superSecretKeyBytes.length && i < key.length; i++) {
            key[i] = superSecretKeyBytes[i];
            myEditor.putString("PASSWORD_KEY", pass);
        }

老实说,我不明白你为什么要这么做。您实际上所做的似乎真的没有必要,因为您正在将其解码为一个字节数组,创建一个固定数量的字节数组,遍历已解码的数组,并将创建的固定数量数组的数据替换为已解码的数据,然后将未更改的字符串密码添加到编辑器中(顺便说一句,您已经做了太多次了)。我很确定这不是你想要做的。

我相信你要做的实际上是加密它,但你从来没有用过它,所以让我们试试这个:

首先,你的密钥应该是一个静态变量,如果它改变了,它将不再能够适当地加密/解密。

代码语言:javascript
复制
byte[] key = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6 };

现在,要根据已有的信息加密密码,请根据密钥(在本例中为key)和要加密的字符串(在本例中为:pass)调用encrypt方法:

代码语言:javascript
复制
String encryptedPassword = encrypt(pass, key);

现在,encryptedPassword包含了基于您输入的密钥的Base64加密形式的密码。现在剩下要做的就是使用编辑器保存加密形式的密码,而不是像以前那样保存未加密形式的密码。

代码语言:javascript
复制
myEditor.putString("PASSWORD_KEY", encryptedPassword);

所以现在当您调用myEditor.commit()时,您将存储加密的表单。

下面是来自第一个源文件的编辑后的onClick方法,用于用户名和密码加密。我没有看你的解密部分,但你应该能够根据我给你的东西弄明白:

代码语言:javascript
复制
public void onClick(View arg0) {
    user=rName.getText().toString().trim();
    pass=rPwd.getText().toString().trim();

    if(arg0==regBttn){     
       if((user.length()!=0))
        {
          if((pass.length()!=0))
        {

        sp=getSharedPreferences("AccessApp",MODE_WORLD_WRITEABLE);
        Editor myEditor=sp.edit();

        byte[] key = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6 };

        try {
             String encryptedUser = encrypt(user, key);  
             myEditor.putString("USERNAME_KEY", encryptedUser); 
        }
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }   
    try {
             String encryptedPass = encrypt(pass, key);  
             myEditor.putString("PASSWORD_KEY", encryptedPass); 

    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    myEditor.commit();
    Toast.makeText(this, "Registration is successfull",10000).show();
    i=new Intent(this,AccessApp.class);
    startActivity(i);
    }
    else
     {
      Toast.makeText(this, "Please Enter password", 10000).show();  
     }
     }
    else{
        Toast.makeText(this,"Please Enter Username",10000).show();
     }
    }

else if(arg0==rtnBttn){
    AlertDialog.Builder builder=new AlertDialog.Builder(this);
     builder.setTitle("Exit");
     builder.setMessage("Do you want to exit");
     builder.setCancelable(false);
     builder.setPositiveButton("Yes",new DialogInterface.OnClickListener() {

  public void onClick(DialogInterface dialog, int which) {
  // TODO Auto-generated method stub
  finish();
  }
  });
    builder.setNegativeButton("No", new DialogInterface.OnClickListener() {

            public void onClick(DialogInterface arg0, int arg1) {
                arg0.cancel();
            }
        });
    AlertDialog alert=builder.create();
    alert.show();

    }
}

希望能帮上忙~

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/13300310

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档