Android Open Source - base-android-utils R S A






From Project

Back to project page base-android-utils.

License

The source code is released under:

Apache License

If you think the Android project base-android-utils listed in this page is inappropriate, such as containing malicious code/tools or violating the copyright, please email info at java2s dot com, thanks.

Java Source Code

package me.pc.mobile.helper.v14.crypt;
/*ww w .j  av a  2s . co  m*/
/*
 --------------------------------------------**********--------------------------------------------

 ????1977?????????????MIT(Massachusetts Institute of Technology)?Ronal Rivest?Adi Shamir?Len Adleman????????????????????Rivest?Shamir?Adlernan?????RSA????????????????????????????????????????????!

 ??RSA??????????????????????????????????????????

 1.???????????p?q???p?q??155??????????512???????????n=pq?k=(p-1)(q-1)?

 2.??????????M?????M?????0?????n?

 3.????????e?????e?k?????e?????0?????k????????????(e, n)?

 4.??????d???ed??k????1??????e?n???????????d?????????????????(d, n)?

 ????? ?????????C??M?e????n??????

 ????? ?????????N??C?d????n??????

 ?????e??d?n??????????????M??N?

 --------------------------------------------**********--------------------------------------------
 */
import java.math.BigInteger;
import java.security.Key;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.SecureRandom;
import java.security.Signature;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.HashMap;
import java.util.Map;

import javax.crypto.Cipher;

import android.util.Log;

public class RSA {
  /** ??key???? */
  private static int KEYSIZE = 1024;

  /**
   * ???RSA???
   * 
   * @return ??????Map<String,
   *         String>?????publicKey????privateKey?????modulus??
   * @throws Exception
   */
  public static Map<String, String> generateKeyPair() throws Exception {
    /** RSA???????????????????? */
    SecureRandom sr = new SecureRandom();
    /** ?RSA??????KeyPairGenerator?? */
    KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
    /** ??????????????????????KeyPairGenerator?? */
    kpg.initialize(KEYSIZE, sr);
    /** ?????? */
    KeyPair kp = kpg.generateKeyPair();
    /** ???? */
    Key publicKey = kp.getPublic();
    byte[] publicKeyBytes = publicKey.getEncoded();
    String pub = new String(Base64.encodeBase64(publicKeyBytes),
        ConfigureEncryptAndDecrypt.CHAR_ENCODING);
    /** ????? */
    Key privateKey = kp.getPrivate();
    byte[] privateKeyBytes = privateKey.getEncoded();
    String pri = new String(Base64.encodeBase64(privateKeyBytes),
        ConfigureEncryptAndDecrypt.CHAR_ENCODING);

    Map<String, String> map = new HashMap<String, String>();
    map.put("publicKey", pub);
    map.put("privateKey", pri);
    RSAPublicKey rsp = (RSAPublicKey) kp.getPublic();
    BigInteger bint = rsp.getModulus();
    byte[] b = bint.toByteArray();
    byte[] deBase64Value = Base64.encodeBase64(b);
    String retValue = new String(deBase64Value);
    map.put("modulus", retValue);
    return map;
  }

  /**
   * RSA????
   * 
   * @param source
   *            ?????????????
   * @param publicKey
   *            ?????
   * @return Base64????????????
   * @throws Exception
   */
  public static String encryptToBase64(String source, String publicKey)
      throws Exception {
    return encryptToBase64(source, publicKey,
        ConfigureEncryptAndDecrypt.CHAR_ENCODING);
  }

  /**
   * RSA????
   * 
   * @param source
   *            ?????????????
   * @param publicKey
   *            ?????
   * @return Base64????????????
   * @throws Exception
   */
  public static String encryptToBase64(String source, String publicKey,
      String charset) throws Exception {
    PublicKey key = getPublicKey(publicKey, charset);
    return encryptToBase64(source, key, charset);
  }

  /**
   * RSA????
   * 
   * @param source
   *            ?????????????
   * @param key
   *            ??
   * @return Base64????????????
   * @throws Exception
   */
  public static String encryptToBase64(String source, PublicKey key)
      throws Exception {
    return encryptToBase64(source, key,
        ConfigureEncryptAndDecrypt.CHAR_ENCODING);
  }

  /**
   * 
   * RSA????
   * 
   * @param source
   *            ?????????????
   * @param key
   *            ??
   * @param charset
   *            ?????????
   * @return
   * @throws Exception
   */
  public static String encryptToBase64(String source, PublicKey key,
      String charset) throws Exception {
    byte[] sourceByte = source.getBytes(charset);
    /** ??????? */
    byte[] b1 = encrypt(sourceByte, key);
    return new String(Base64.encodeBase64(b1), charset);
  }

  /**
   * RSA????
   * 
   * @param source
   *            ?????????
   * @param key
   *            ?????
   * @return ??????byte??
   * @throws Exception
   */
  public static byte[] encrypt(byte[] source, PublicKey key) throws Exception {
    /** ??Cipher???????????????RSA?? */
    Cipher cipher = Cipher
        .getInstance(ConfigureEncryptAndDecrypt.RSA_ALGORITHM);
    cipher.init(Cipher.ENCRYPT_MODE, key);
    /** ??????? */
    byte[] result = cipher.doFinal(source);
    return result;
  }

  /**
   * RSA????
   * 
   * @param cryptograph
   *            Base64??????
   * @param privateKey
   *            ??????
   * @return
   * @throws Exception
   */
  public static String decryptFromBase64(String cryptograph, String privateKey)
      throws Exception {
    return decryptFromBase64(cryptograph, privateKey,
        ConfigureEncryptAndDecrypt.CHAR_ENCODING);
  }

  /**
   * ????
   * 
   * @param cryptograph
   *            Base64??????
   * @param privateKey
   *            ??????
   * @param charset
   * @return
   * @throws Exception
   */
  public static String decryptFromBase64(String cryptograph,
      String privateKey, String charset) throws Exception {
    PrivateKey key = getPrivateKey(privateKey, charset);
    return decryptFromBase64(cryptograph, key, charset);
  }

  /**
   * RSA???? ????UTF-8???
   * 
   * @param cryptograph
   *            Base64??????
   * @param key
   * @return
   * @throws Exception
   */
  public static String decryptFromBase64(String cryptograph, PrivateKey key)
      throws Exception {
    return decryptFromBase64(cryptograph, key,
        ConfigureEncryptAndDecrypt.CHAR_ENCODING);
  }

  /**
   * RSA????
   * 
   * @param cryptograph
   *            ????????
   * @param key
   *            ???????
   * @param charset
   * @return
   * @throws Exception
   */
  public static String decryptFromBase64(String cryptograph, PrivateKey key,
      String charset) throws Exception {
    byte[] b1 = Base64.decodeBase64(cryptograph.getBytes(charset));
    byte[] b = decrypt(b1, key);
    return new String(b, charset);
  }

  /**
   * RSA????
   * 
   * @param cryptograph
   *            ????????
   * @param key
   *            ???????
   * @return
   * @throws Exception
   */
  public static byte[] decrypt(byte[] cryptograph, PrivateKey key)
      throws Exception {
    /** ??Cipher????????????????RSA?? */
    Cipher cipher = Cipher
        .getInstance(ConfigureEncryptAndDecrypt.RSA_ALGORITHM);
    cipher.init(Cipher.DECRYPT_MODE, key);
    /** ??????? */
    return cipher.doFinal(cryptograph);
  }

  /**
   * ????
   * 
   * @param key
   *            ?????????base64????
   * @throws Exception
   */
  public static PublicKey getPublicKey(String key, String charset)
      throws Exception {
    X509EncodedKeySpec keySpec = new X509EncodedKeySpec(
        Base64.decodeBase64(key.getBytes(charset)));
    KeyFactory keyFactory = KeyFactory.getInstance("RSA");
    PublicKey publicKey = keyFactory.generatePublic(keySpec);
    return publicKey;
  }

  /**
   * ?????
   * 
   * @param key
   *            ?????????base64????
   * @throws Exception
   */
  public static PrivateKey getPrivateKey(String key, String charset)
      throws Exception {
    PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(
        Base64.decodeBase64(key.getBytes(charset)));
    KeyFactory keyFactory = KeyFactory.getInstance("RSA");
    PrivateKey privateKey = keyFactory.generatePrivate(keySpec);
    return privateKey;
  }

  /**
   * ??RSA????
   * 
   * @param content
   * @param privateKey
   * @return
   */
  public static String sign(String content, String privateKey) {
    String charset = ConfigureEncryptAndDecrypt.CHAR_ENCODING;
    try {
      PKCS8EncodedKeySpec priPKCS8 = new PKCS8EncodedKeySpec(
          Base64.decodeBase64(privateKey.getBytes(charset)));
      KeyFactory keyf = KeyFactory.getInstance("RSA");
      PrivateKey priKey = keyf.generatePrivate(priPKCS8);

      Signature signature = Signature.getInstance("SHA1WithRSA");
      signature.initSign(priKey);
      signature.update(content.getBytes(charset));

      byte[] signed = signature.sign();
      return new String(Base64.encodeBase64(signed));
    } catch (Exception e) {
      Log.e("RSA", "RSA Sign Error! content:[" + content
          + "] privateKey:[" + privateKey + "]", e);
    }
    return null;
  }

  /**
   * ???RSA????
   * 
   * @param content
   * @param sign
   * @param publicKey
   * @return
   */
  public static boolean checkSign(String content, String sign,
      String publicKey) {
    try {
      KeyFactory keyFactory = KeyFactory.getInstance("RSA");
      byte[] encodedKey = Base64.decode2(publicKey);
      PublicKey pubKey = keyFactory
          .generatePublic(new X509EncodedKeySpec(encodedKey));

      java.security.Signature signature = java.security.Signature
          .getInstance("SHA1WithRSA");
      signature.initVerify(pubKey);
      signature.update(content
          .getBytes(ConfigureEncryptAndDecrypt.CHAR_ENCODING));

      boolean bverify = signature.verify(Base64.decode2(sign));
      return bverify;
    } catch (Exception e) {
      Log.e("RSA", "RSA CheckSign Error! content:[" + content
          + "] sign:[" + sign + "] publicKey:[" + publicKey + "]", e);
    }

    return false;
  }

}




Java Source Code List

me.pc.mobile.helper.v14.BuildConfig.java
me.pc.mobile.helper.v14.base.BaseActivity.java
me.pc.mobile.helper.v14.base.BaseApp.java
me.pc.mobile.helper.v14.base.BaseFrag.java
me.pc.mobile.helper.v14.base.abs.BaseJsonParser.java
me.pc.mobile.helper.v14.crypt.AES7Padding.java
me.pc.mobile.helper.v14.crypt.AES.java
me.pc.mobile.helper.v14.crypt.Base64.java
me.pc.mobile.helper.v14.crypt.CheckUtils.java
me.pc.mobile.helper.v14.crypt.ConfigureEncryptAndDecrypt.java
me.pc.mobile.helper.v14.crypt.RSA.java
me.pc.mobile.helper.v14.files.ExternalStorage.java
me.pc.mobile.helper.v14.files.FileUtils.java
me.pc.mobile.helper.v14.files.Reader.java
me.pc.mobile.helper.v14.files.Writer.java
me.pc.mobile.helper.v14.http.AsyncHttpUtil.java
me.pc.mobile.helper.v14.net.Addresses.java
me.pc.mobile.helper.v14.net.NetworkUtil.java
me.pc.mobile.helper.v14.net.WifiWaker.java
me.pc.mobile.helper.v14.receiver.BatteryStateReceiver.java
me.pc.mobile.helper.v14.receiver.NetworkStateChangeReceiver.java
me.pc.mobile.helper.v14.ui.image.RoundedDrawable.java
me.pc.mobile.helper.v14.ui.image.RoundedImageView.java
me.pc.mobile.helper.v14.util.AppInstallUtil.java
me.pc.mobile.helper.v14.util.BitDrawableUtil.java
me.pc.mobile.helper.v14.util.DeviceIdentifier.java
me.pc.mobile.helper.v14.util.DisplayUtils.java
me.pc.mobile.helper.v14.util.IntentUtil.java
me.pc.mobile.helper.v14.util.IoUtils.java
me.pc.mobile.helper.v14.util.LogUtil.java
me.pc.mobile.helper.v14.util.PackageUtil.java
me.pc.mobile.helper.v14.util.PermissionAssertUtils.java
me.pc.mobile.helper.v14.util.RegexUtil.java
me.pc.mobile.helper.v14.util.SharedPrefUtil.java
me.pc.mobile.helper.v14.util.StorageUtils.java