android - 如何加密解密公钥

标签 android

下面是我的登录页面代码,我还在谷歌上找到了一个 RSA PUBLIC PRIVITE KEY 如何将此代码插入我的代码中?谁能帮我,我从这个网址找到了 RSA 代码 http://xtrace.blogspot.com/search/label/RSA

    public void onCreate(Bundle icicle)
{
    super.onCreate(icicle);
    setContentView(R.layout.agapplogin);

    TextView lblMobileNo = (TextView)findViewById(R.id.lblMobileNo);
    lblMobileNo.setTextColor(getResources().getColor(R.color.text_color_red));

    mobile = (EditText)findViewById(R.id.txtMobileNo);

    TextView lblPinNo = (TextView)findViewById(R.id.lblPinNo);
    lblPinNo.setTextColor(getResources().getColor(R.color.text_color_red));

    pin = (EditText)findViewById(R.id.txtPinNo);

    btnLogin = (Button)findViewById(R.id.btnLogin);
    btnClear = (Button)findViewById(R.id.btnClear);

    btnLogin.setOnClickListener(new OnClickListener() {
         public void onClick(View view) {                
             postLoginData();
         }
         });      

                ;}  

public void postLoginData() 

   {
             Intent i = new   
   Intent(this.getApplicationContext(),new.class);
             Bundle bundle = new Bundle();
             bundle.putString("mno", mobile.getText().toString());
             bundle.putString("pinno", pin.getText().toString());
             i.putExtras(bundle);
             startActivity(i);          }
}


            ///this is RSA code which i found





   import java.io.BufferedOutputStream;
   import java.io.FileOutputStream;
   import java.io.IOException;
   import java.io.ObjectOutputStream;
   import java.math.BigInteger;
   import java.security.Key;
   import java.security.KeyFactory;
   import java.security.KeyPair;
   import java.security.KeyPairGenerator;
   import java.security.NoSuchAlgorithmException;
   import java.security.spec.RSAPrivateKeySpec;
   import java.security.spec.RSAPublicKeySpec;

        /**
        * This class generates key pair and saves in file in current directory
       * 
       * @author amit
       * 
       */
        public class RSAKeyGenerator {

public void generateKeyPair(String publicKeyFileName,
        String privateKeyFileName) {
    KeyPairGenerator kpg = null;
    try {
        kpg = KeyPairGenerator.getInstance("RSA");
    } catch (NoSuchAlgorithmException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    kpg.initialize(2048);
    KeyPair kp = kpg.genKeyPair();
    Key publicKey = kp.getPublic();
    Key privateKey = kp.getPrivate();
    try {
        KeyFactory fact = KeyFactory.getInstance("RSA");
        RSAPublicKeySpec pub = fact.getKeySpec(publicKey,
                RSAPublicKeySpec.class);
        RSAPrivateKeySpec priv = fact.getKeySpec(privateKey,
                RSAPrivateKeySpec.class);

        saveToFile(publicKeyFileName, pub.getModulus(),
                pub.getPublicExponent());
        System.out.println("public key saved");
        saveToFile(privateKeyFileName, priv.getModulus(),
                priv.getPrivateExponent());
        System.out.println("private key saved");
    } catch (Exception e) {
        System.out.println("error ");
    }
}

private void saveToFile(String fileName, BigInteger mod, BigInteger exp)
        throws IOException {
    ObjectOutputStream oout = new ObjectOutputStream(
            new BufferedOutputStream(new FileOutputStream(fileName)));
    try {
        oout.writeObject(mod);
        oout.writeObject(exp);
    } catch (Exception e) {
        throw new IOException("Unexpected error", e);
    } finally {
        oout.close();
    }
}

/**
 * @param args
 */
public static void main(String[] args) {
    // TODO Auto-generated method stub
    RSAKeyGenerator t = new RSAKeyGenerator();
    t.generateKeyPair("public.key", "private.key");

}

        }








        import javax.crypto.Cipher;

         public class RSAEncDec {

private PublicKey readPublicKeyFromFile(String fileloc) throws IOException {
    InputStream in = new FileInputStream(new File(fileloc));

    ObjectInputStream oin = new ObjectInputStream(new BufferedInputStream(
            in));
    try {
        BigInteger m = (BigInteger) oin.readObject();
        BigInteger e = (BigInteger) oin.readObject();
        RSAPublicKeySpec keySpec = new RSAPublicKeySpec(m, e);
        KeyFactory fact = KeyFactory.getInstance("RSA");
        PublicKey pubKey = fact.generatePublic(keySpec);
        return pubKey;
    } catch (Exception e) {
        throw new RuntimeException("Spurious serialisation error", e);
    } finally {
        oin.close();
    }
}

private PrivateKey readPrivateKeyFromFile(String fileLoc)
        throws IOException {
    InputStream in = new FileInputStream(new File(fileLoc));

    ObjectInputStream oin = new ObjectInputStream(new BufferedInputStream(
            in));
    try {
        BigInteger m = (BigInteger) oin.readObject();
        BigInteger e = (BigInteger) oin.readObject();
        RSAPrivateKeySpec keySpec = new RSAPrivateKeySpec(m, e);
        KeyFactory fact = KeyFactory.getInstance("RSA");
        PrivateKey prvKey = fact.generatePrivate(keySpec);
        return prvKey;
    } catch (Exception e) {
        throw new RuntimeException("Spurious serialisation error", e);
    } finally {
        oin.close();
    }
}

public byte[] rsaEncrypt(byte[] data, String fileLoc) {
    try {
        PublicKey pubKey = readPublicKeyFromFile(fileLoc);
        Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.ENCRYPT_MODE, pubKey);
        byte[] cipherData = cipher.doFinal(data);
        return cipherData;
    } catch (Exception e) {
        System.out.println("some thing went wrong");
    }
    return null;
}

public byte[] rsaDecrypt(byte[] data, String fileLoc) {
    try {
        PrivateKey pubKey = readPrivateKeyFromFile(fileLoc);
        Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.DECRYPT_MODE, pubKey);
        byte[] cipherData = cipher.doFinal(data);
        return cipherData;
    } catch (Exception e) {
        System.out.println("some thing went wrong");
    }
    return null;
}

/*
 * string
 * 
 * @param data (normal string)
 * 
 * @return
 */
public String encrypt(String data, String fileLoc) {
    byte[] enc = rsaEncrypt(data.getBytes(), fileLoc);
    return Base64.encode(enc);
}

/**
 * return the normal string
 * 
 * @param data
 *            (base64 encoded string)
 * @return
 * @throws Base64DecodingException
 */
public String decrypt(String data, String fileLoc)
        throws Base64DecodingException {
    byte[] enc = Base64.decode(data);
    byte[] decryptedData = rsaDecrypt(enc, fileLoc);
    return new String(decryptedData);
}

/**
 * 
 * @param args
 */
public static void main(String[] args) {
    // TODO Auto-generated method stub
    RSAEncDec obj = new RSAEncDec();
    String enc = obj.encrypt("hello world", "./public.key");
    System.out.println(enc);
    String dat = null;
    try {
        dat = obj.decrypt(enc, "./private.key");
    } catch (Base64DecodingException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    System.out.println(dat);

        }

       }

最佳答案

你到底想做什么?

在发送到服务器之前,是否要使用 RSA 加密 mobileNo 和 pin?

如果是这种情况,您可能希望在您的服务器上生成一个 key 对,并且让您的 android 可以访问公钥。

上面的代码在 Android 中同时生成私钥和公钥,我不认为你想在这里做什么。

查看本文以了解如何在您的服务器中生成 key 并在 Android 中使用它们 http://www.helloandroid.com/tutorials/rsa-string-encryption-security

关于android - 如何加密解密公钥,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12668838/

相关文章:

android - 我如何在 Android Studio 中添加依赖项

android - 如何在 Android 中将线性布局中的内容设置到屏幕的底部。?

android - 以编程方式检索 Android API 版本

android - 有没有办法检查状态栏的可见性?

android - 无法解码流 : FileNotFoundException

android - 读取包含 åäö 的 Assets 中的文本文件

android - 从 SQLite 数据库 Android SDK 中获取随机行

Android Debug模式性能

android - Android 上的 "nuclear-pub"设备是什么?

android - 邮寄到 Android : 'Unsupported action' error