欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Android數(shù)據(jù)加密之Rsa加密的簡(jiǎn)單實(shí)現(xiàn)

 更新時(shí)間:2016年10月11日 09:47:40   投稿:jingxian  
下面小編就為大家?guī)硪黄狝ndroid數(shù)據(jù)加密之Rsa加密的簡(jiǎn)單實(shí)現(xiàn)。小編覺得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧

最近無意中和同事交流數(shù)據(jù)安全傳輸?shù)膯栴},想起自己曾經(jīng)使用過的Rsa非對(duì)稱加密算法,閑下來總結(jié)一下。

什么是Rsa加密?

RSA算法是最流行的公鑰密碼算法,使用長(zhǎng)度可以變化的密鑰。RSA是第一個(gè)既能用于數(shù)據(jù)加密也能用于數(shù)字簽名的算法。

RSA算法原理如下:

1.隨機(jī)選擇兩個(gè)大質(zhì)數(shù)p和q,p不等于q,計(jì)算N=pq;
2.選擇一個(gè)大于1小于N的自然數(shù)e,e必須與(p-1)(q-1)互素。
3.用公式計(jì)算出d:d×e = 1 (mod (p-1)(q-1)) 。
4.銷毀p和q。

最終得到的N和e就是“公鑰”,d就是“私鑰”,發(fā)送方使用N去加密數(shù)據(jù),接收方只有使用d才能解開數(shù)據(jù)內(nèi)容。

RSA的安全性依賴于大數(shù)分解,小于1024位的N已經(jīng)被證明是不安全的,而且由于RSA算法進(jìn)行的都是大數(shù)計(jì)算,使得RSA最快的情況也比DES慢上倍,這是RSA最大的缺陷,因此通常只能用于加密少量數(shù)據(jù)或者加密密鑰,但RSA仍然不失為一種高強(qiáng)度的算法。

該如何使用呢?

第一步:首先生成秘鑰對(duì)

/**
   * 隨機(jī)生成RSA密鑰對(duì)
   *
   * @param keyLength 密鑰長(zhǎng)度,范圍:512~2048
   *         一般1024
   * @return
   */
  public static KeyPair generateRSAKeyPair(int keyLength) {
    try {
      KeyPairGenerator kpg = KeyPairGenerator.getInstance(RSA);
      kpg.initialize(keyLength);
      return kpg.genKeyPair();
    } catch (NoSuchAlgorithmException e) {
      e.printStackTrace();
      return null;
    }
  }

具體加密實(shí)現(xiàn):

公鑰加密

/**
   * 用公鑰對(duì)字符串進(jìn)行加密
   *
   * @param data 原文
   */
  public static byte[] encryptByPublicKey(byte[] data, byte[] publicKey) throws Exception {
    // 得到公鑰
    X509EncodedKeySpec keySpec = new X509EncodedKeySpec(publicKey);
    KeyFactory kf = KeyFactory.getInstance(RSA);
    PublicKey keyPublic = kf.generatePublic(keySpec);
    // 加密數(shù)據(jù)
    Cipher cp = Cipher.getInstance(ECB_PKCS1_PADDING);
    cp.init(Cipher.ENCRYPT_MODE, keyPublic);
    return cp.doFinal(data);
  }

私鑰加密

/**
   * 私鑰加密
   *
   * @param data    待加密數(shù)據(jù)
   * @param privateKey 密鑰
   * @return byte[] 加密數(shù)據(jù)
   */
  public static byte[] encryptByPrivateKey(byte[] data, byte[] privateKey) throws Exception {
    // 得到私鑰
    PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(privateKey);
    KeyFactory kf = KeyFactory.getInstance(RSA);
    PrivateKey keyPrivate = kf.generatePrivate(keySpec);
    // 數(shù)據(jù)加密
    Cipher cipher = Cipher.getInstance(ECB_PKCS1_PADDING);
    cipher.init(Cipher.ENCRYPT_MODE, keyPrivate);
    return cipher.doFinal(data);
  }

公鑰解密

/**
   * 公鑰解密
   *
   * @param data   待解密數(shù)據(jù)
   * @param publicKey 密鑰
   * @return byte[] 解密數(shù)據(jù)
   */
  public static byte[] decryptByPublicKey(byte[] data, byte[] publicKey) throws Exception {
    // 得到公鑰
    X509EncodedKeySpec keySpec = new X509EncodedKeySpec(publicKey);
    KeyFactory kf = KeyFactory.getInstance(RSA);
    PublicKey keyPublic = kf.generatePublic(keySpec);
    // 數(shù)據(jù)解密
    Cipher cipher = Cipher.getInstance(ECB_PKCS1_PADDING);
    cipher.init(Cipher.DECRYPT_MODE, keyPublic);
    return cipher.doFinal(data);
  }

私鑰解密

/**
   * 使用私鑰進(jìn)行解密
   */
  public static byte[] decryptByPrivateKey(byte[] encrypted, byte[] privateKey) throws Exception {
    // 得到私鑰
    PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(privateKey);
    KeyFactory kf = KeyFactory.getInstance(RSA);
    PrivateKey keyPrivate = kf.generatePrivate(keySpec);

    // 解密數(shù)據(jù)
    Cipher cp = Cipher.getInstance(ECB_PKCS1_PADDING);
    cp.init(Cipher.DECRYPT_MODE, keyPrivate);
    byte[] arr = cp.doFinal(encrypted);
    return arr;
  }

幾個(gè)全局變量解說:

public static final String RSA = "RSA";// 非對(duì)稱加密密鑰算法
public static final String ECB_PKCS1_PADDING = "RSA/ECB/PKCS1Padding";//加密填充方式
public static final int DEFAULT_KEY_SIZE = 2048;//秘鑰默認(rèn)長(zhǎng)度
public static final byte[] DEFAULT_SPLIT = "#PART#".getBytes();// 當(dāng)要加密的內(nèi)容超過bufferSize,則采用partSplit進(jìn)行分塊加密
public static final int DEFAULT_BUFFERSIZE = (DEFAULT_KEY_SIZE / 8) - 11;// 當(dāng)前秘鑰支持加密的最大字節(jié)數(shù)

關(guān)于加密填充方式:之前以為上面這些操作就能實(shí)現(xiàn)rsa加解密,以為萬事大吉了,呵呵,這事還沒完,悲劇還是發(fā)生了,Android這邊加密過的數(shù)據(jù),服務(wù)器端死活解密不了,原來android系統(tǒng)的RSA實(shí)現(xiàn)是"RSA/None/NoPadding",而標(biāo)準(zhǔn)JDK實(shí)現(xiàn)是"RSA/None/PKCS1Padding" ,這造成了在android機(jī)上加密后無法在服務(wù)器上解密的原因,所以在實(shí)現(xiàn)的時(shí)候這個(gè)一定要注意。

實(shí)現(xiàn)分段加密:搞定了填充方式之后又自信的認(rèn)為萬事大吉了,可是意外還是發(fā)生了,RSA非對(duì)稱加密內(nèi)容長(zhǎng)度有限制,1024位key的最多只能加密127位數(shù)據(jù),否則就會(huì)報(bào)錯(cuò)(javax.crypto.IllegalBlockSizeException: Data must not be longer than 117 bytes) , RSA 是常用的非對(duì)稱加密算法。最近使用時(shí)卻出現(xiàn)了“不正確的長(zhǎng)度”的異常,研究發(fā)現(xiàn)是由于待加密的數(shù)據(jù)超長(zhǎng)所致。RSA 算法規(guī)定:待加密的字節(jié)數(shù)不能超過密鑰的長(zhǎng)度值除以 8 再減去 11(即:KeySize / 8 - 11),而加密后得到密文的字節(jié)數(shù),正好是密鑰的長(zhǎng)度值除以 8(即:KeySize / 8)。

公鑰分段加密

/**
   * 用公鑰對(duì)字符串進(jìn)行分段加密
   *
   */
  public static byte[] encryptByPublicKeyForSpilt(byte[] data, byte[] publicKey) throws Exception {
    int dataLen = data.length;
    if (dataLen <= DEFAULT_BUFFERSIZE) {
      return encryptByPublicKey(data, publicKey);
    }
    List<Byte> allBytes = new ArrayList<Byte>(2048);
    int bufIndex = 0;
    int subDataLoop = 0;
    byte[] buf = new byte[DEFAULT_BUFFERSIZE];
    for (int i = 0; i < dataLen; i++) {
      buf[bufIndex] = data[i];
      if (++bufIndex == DEFAULT_BUFFERSIZE || i == dataLen - 1) {
        subDataLoop++;
        if (subDataLoop != 1) {
          for (byte b : DEFAULT_SPLIT) {
            allBytes.add(b);
          }
        }
        byte[] encryptBytes = encryptByPublicKey(buf, publicKey);
        for (byte b : encryptBytes) {
          allBytes.add(b);
        }
        bufIndex = 0;
        if (i == dataLen - 1) {
          buf = null;
        } else {
          buf = new byte[Math.min(DEFAULT_BUFFERSIZE, dataLen - i - 1)];
        }
      }
    }
    byte[] bytes = new byte[allBytes.size()];
    {
      int i = 0;
      for (Byte b : allBytes) {
        bytes[i++] = b.byteValue();
      }
    }
    return bytes;
  }

私鑰分段加密

/**
   * 分段加密
   *
   * @param data    要加密的原始數(shù)據(jù)
   * @param privateKey 秘鑰
   */
  public static byte[] encryptByPrivateKeyForSpilt(byte[] data, byte[] privateKey) throws Exception {
    int dataLen = data.length;
    if (dataLen <= DEFAULT_BUFFERSIZE) {
      return encryptByPrivateKey(data, privateKey);
    }
    List<Byte> allBytes = new ArrayList<Byte>(2048);
    int bufIndex = 0;
    int subDataLoop = 0;
    byte[] buf = new byte[DEFAULT_BUFFERSIZE];
    for (int i = 0; i < dataLen; i++) {
      buf[bufIndex] = data[i];
      if (++bufIndex == DEFAULT_BUFFERSIZE || i == dataLen - 1) {
        subDataLoop++;
        if (subDataLoop != 1) {
          for (byte b : DEFAULT_SPLIT) {
            allBytes.add(b);
          }
        }
        byte[] encryptBytes = encryptByPrivateKey(buf, privateKey);
        for (byte b : encryptBytes) {
          allBytes.add(b);
        }
        bufIndex = 0;
        if (i == dataLen - 1) {
          buf = null;
        } else {
          buf = new byte[Math.min(DEFAULT_BUFFERSIZE, dataLen - i - 1)];
        }
      }
    }
    byte[] bytes = new byte[allBytes.size()];
    {
      int i = 0;
      for (Byte b : allBytes) {
        bytes[i++] = b.byteValue();
      }
    }
    return bytes;
  }

公鑰分段解密

/**
   * 公鑰分段解密
   *
   * @param encrypted 待解密數(shù)據(jù)
   * @param publicKey 密鑰
   */
  public static byte[] decryptByPublicKeyForSpilt(byte[] encrypted, byte[] publicKey) throws Exception {
    int splitLen = DEFAULT_SPLIT.length;
    if (splitLen <= 0) {
      return decryptByPublicKey(encrypted, publicKey);
    }
    int dataLen = encrypted.length;
    List<Byte> allBytes = new ArrayList<Byte>(1024);
    int latestStartIndex = 0;
    for (int i = 0; i < dataLen; i++) {
      byte bt = encrypted[i];
      boolean isMatchSplit = false;
      if (i == dataLen - 1) {
        // 到data的最后了
        byte[] part = new byte[dataLen - latestStartIndex];
        System.arraycopy(encrypted, latestStartIndex, part, 0, part.length);
        byte[] decryptPart = decryptByPublicKey(part, publicKey);
        for (byte b : decryptPart) {
          allBytes.add(b);
        }
        latestStartIndex = i + splitLen;
        i = latestStartIndex - 1;
      } else if (bt == DEFAULT_SPLIT[0]) {
        // 這個(gè)是以split[0]開頭
        if (splitLen > 1) {
          if (i + splitLen < dataLen) {
            // 沒有超出data的范圍
            for (int j = 1; j < splitLen; j++) {
              if (DEFAULT_SPLIT[j] != encrypted[i + j]) {
                break;
              }
              if (j == splitLen - 1) {
                // 驗(yàn)證到split的最后一位,都沒有break,則表明已經(jīng)確認(rèn)是split段
                isMatchSplit = true;
              }
            }
          }
        } else {
          // split只有一位,則已經(jīng)匹配了
          isMatchSplit = true;
        }
      }
      if (isMatchSplit) {
        byte[] part = new byte[i - latestStartIndex];
        System.arraycopy(encrypted, latestStartIndex, part, 0, part.length);
        byte[] decryptPart = decryptByPublicKey(part, publicKey);
        for (byte b : decryptPart) {
          allBytes.add(b);
        }
        latestStartIndex = i + splitLen;
        i = latestStartIndex - 1;
      }
    }
    byte[] bytes = new byte[allBytes.size()];
    {
      int i = 0;
      for (Byte b : allBytes) {
        bytes[i++] = b.byteValue();
      }
    }
    return bytes;
  }

私鑰分段解密

/**
   * 使用私鑰分段解密
   *
   */
  public static byte[] decryptByPrivateKeyForSpilt(byte[] encrypted, byte[] privateKey) throws Exception {
    int splitLen = DEFAULT_SPLIT.length;
    if (splitLen <= 0) {
      return decryptByPrivateKey(encrypted, privateKey);
    }
    int dataLen = encrypted.length;
    List<Byte> allBytes = new ArrayList<Byte>(1024);
    int latestStartIndex = 0;
    for (int i = 0; i < dataLen; i++) {
      byte bt = encrypted[i];
      boolean isMatchSplit = false;
      if (i == dataLen - 1) {
        // 到data的最后了
        byte[] part = new byte[dataLen - latestStartIndex];
        System.arraycopy(encrypted, latestStartIndex, part, 0, part.length);
        byte[] decryptPart = decryptByPrivateKey(part, privateKey);
        for (byte b : decryptPart) {
          allBytes.add(b);
        }
        latestStartIndex = i + splitLen;
        i = latestStartIndex - 1;
      } else if (bt == DEFAULT_SPLIT[0]) {
        // 這個(gè)是以split[0]開頭
        if (splitLen > 1) {
          if (i + splitLen < dataLen) {
            // 沒有超出data的范圍
            for (int j = 1; j < splitLen; j++) {
              if (DEFAULT_SPLIT[j] != encrypted[i + j]) {
                break;
              }
              if (j == splitLen - 1) {
                // 驗(yàn)證到split的最后一位,都沒有break,則表明已經(jīng)確認(rèn)是split段
                isMatchSplit = true;
              }
            }
          }
        } else {
          // split只有一位,則已經(jīng)匹配了
          isMatchSplit = true;
        }
      }
      if (isMatchSplit) {
        byte[] part = new byte[i - latestStartIndex];
        System.arraycopy(encrypted, latestStartIndex, part, 0, part.length);
        byte[] decryptPart = decryptByPrivateKey(part, privateKey);
        for (byte b : decryptPart) {
          allBytes.add(b);
        }
        latestStartIndex = i + splitLen;
        i = latestStartIndex - 1;
      }
    }
    byte[] bytes = new byte[allBytes.size()];
    {
      int i = 0;
      for (Byte b : allBytes) {
        bytes[i++] = b.byteValue();
      }
    }
    return bytes;
  }

這樣總算把遇見的問題解決了,項(xiàng)目中使用的方案是客戶端公鑰加密,服務(wù)器私鑰解密,服務(wù)器開發(fā)人員說是出于效率考慮,所以還是自己寫了個(gè)程序測(cè)試一下真正的效率

第一步:準(zhǔn)備100條對(duì)象數(shù)據(jù)

List<Person> personList=new ArrayList<>();
    int testMaxCount=100;//測(cè)試的最大數(shù)據(jù)條數(shù)
    //添加測(cè)試數(shù)據(jù)
    for(int i=0;i<testMaxCount;i++){
      Person person =new Person();
      person.setAge(i);
      person.setName(String.valueOf(i));
      personList.add(person);
    }
    //FastJson生成json數(shù)據(jù)

    String jsonData=JsonUtils.objectToJsonForFastJson(personList);

    Log.e("MainActivity","加密前json數(shù)據(jù) ---->"+jsonData);
    Log.e("MainActivity","加密前json數(shù)據(jù)長(zhǎng)度 ---->"+jsonData.length());

第二步生成秘鑰對(duì)

KeyPair keyPair=RSAUtils.generateRSAKeyPair(RSAUtils.DEFAULT_KEY_SIZE);
// 公鑰
RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
// 私鑰
RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();

接下來分別使用公鑰加密 私鑰解密   私鑰加密 公鑰解密

//公鑰加密
    long start=System.currentTimeMillis();
    byte[] encryptBytes=  RSAUtils.encryptByPublicKeyForSpilt(jsonData.getBytes(),publicKey.getEncoded());
    long end=System.currentTimeMillis();
    Log.e("MainActivity","公鑰加密耗時(shí) cost time---->"+(end-start));
    String encryStr=Base64Encoder.encode(encryptBytes);
    Log.e("MainActivity","加密后json數(shù)據(jù) --1-->"+encryStr);
    Log.e("MainActivity","加密后json數(shù)據(jù)長(zhǎng)度 --1-->"+encryStr.length());
    //私鑰解密
    start=System.currentTimeMillis();
    byte[] decryptBytes= RSAUtils.decryptByPrivateKeyForSpilt(Base64Decoder.decodeToBytes(encryStr),privateKey.getEncoded());
    String decryStr=new String(decryptBytes);
    end=System.currentTimeMillis();
    Log.e("MainActivity","私鑰解密耗時(shí) cost time---->"+(end-start));
    Log.e("MainActivity","解密后json數(shù)據(jù) --1-->"+decryStr);

    //私鑰加密
    start=System.currentTimeMillis();
    encryptBytes=  RSAUtils.encryptByPrivateKeyForSpilt(jsonData.getBytes(),privateKey.getEncoded());
    end=System.currentTimeMillis();
    Log.e("MainActivity","私鑰加密密耗時(shí) cost time---->"+(end-start));
    encryStr=Base64Encoder.encode(encryptBytes);
    Log.e("MainActivity","加密后json數(shù)據(jù) --2-->"+encryStr);
    Log.e("MainActivity","加密后json數(shù)據(jù)長(zhǎng)度 --2-->"+encryStr.length());
    //公鑰解密
    start=System.currentTimeMillis();
    decryptBytes= RSAUtils.decryptByPublicKeyForSpilt(Base64Decoder.decodeToBytes(encryStr),publicKey.getEncoded());
    decryStr=new String(decryptBytes);
    end=System.currentTimeMillis();
    Log.e("MainActivity","公鑰解密耗時(shí) cost time---->"+(end-start));
    Log.e("MainActivity","解密后json數(shù)據(jù) --2-->"+decryStr);

運(yùn)行結(jié)果:

對(duì)比發(fā)現(xiàn):私鑰的加解密都很耗時(shí),所以可以根據(jù)不同的需求采用不能方案來進(jìn)行加解密。個(gè)人覺得服務(wù)器要求解密效率高,客戶端私鑰加密,服務(wù)器公鑰解密比較好一點(diǎn)

加密后數(shù)據(jù)大小的變化:數(shù)據(jù)量差不多是加密前的1.5倍

以上就是小編為大家?guī)淼腁ndroid數(shù)據(jù)加密之Rsa加密的簡(jiǎn)單實(shí)現(xiàn)全部?jī)?nèi)容了,希望大家多多支持腳本之家~

相關(guān)文章

  • Android開發(fā)中的MVC設(shè)計(jì)模式淺析

    Android開發(fā)中的MVC設(shè)計(jì)模式淺析

    這篇文章主要介紹了Android開發(fā)中的MVC設(shè)計(jì)模式淺析,本文講解了對(duì)Android開發(fā)中的MVC設(shè)計(jì)模式的理解,需要的朋友可以參考下
    2015-06-06
  • android語音即時(shí)通訊之錄音、播放功能實(shí)現(xiàn)代碼

    android語音即時(shí)通訊之錄音、播放功能實(shí)現(xiàn)代碼

    這篇文章主要為大家詳細(xì)介紹了android語音即時(shí)通訊之錄音、播放功能的實(shí)現(xiàn)代碼,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2017-07-07
  • Android實(shí)現(xiàn)截屏功能

    Android實(shí)現(xiàn)截屏功能

    這篇文章主要為大家詳細(xì)介紹了Android實(shí)現(xiàn)截屏功能,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2021-07-07
  • Android實(shí)現(xiàn)定時(shí)任務(wù)及鬧鐘

    Android實(shí)現(xiàn)定時(shí)任務(wù)及鬧鐘

    這篇文章主要為大家詳細(xì)介紹了Android實(shí)現(xiàn)定時(shí)任務(wù)及鬧鐘,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2020-06-06
  • Kotlin + Flow 實(shí)現(xiàn)Android 應(yīng)用初始化任務(wù)啟動(dòng)庫

    Kotlin + Flow 實(shí)現(xiàn)Android 應(yīng)用初始化任務(wù)啟動(dòng)庫

    這篇文章主要介紹了Kotlin + Flow 實(shí)現(xiàn)Android 應(yīng)用初始化任務(wù)啟動(dòng)庫的方法,幫助大家更好的理解和學(xué)習(xí)使用Android,感興趣的朋友可以了解下
    2021-03-03
  • Android中巧妙的實(shí)現(xiàn)緩存詳解

    Android中巧妙的實(shí)現(xiàn)緩存詳解

    采用緩存,可以進(jìn)一步大大緩解數(shù)據(jù)交互的壓力,有的時(shí)候?yàn)榱丝焖俨樵儠?huì)被多次調(diào)用的數(shù)據(jù),或者構(gòu)建比較廢時(shí)的實(shí)例,我們一般使用緩存的方法。無論大型或小型應(yīng)用,靈活的緩存可以說不僅大大減輕了服務(wù)器的壓力,而且因?yàn)楦焖俚挠脩趔w驗(yàn)而方便了用戶。下面來一起看看吧。
    2016-11-11
  • 結(jié)合Windows窗口深入分析Android窗口的實(shí)現(xiàn)

    結(jié)合Windows窗口深入分析Android窗口的實(shí)現(xiàn)

    在Android中,窗口是一個(gè)基本的圖形用戶界面元素,它提供了一個(gè)屏幕區(qū)域來放置應(yīng)用程序的用戶界面元素。窗口可以是全屏的,也可以是一個(gè)小的對(duì)話框。每個(gè)窗口都有一個(gè)特定的主題和樣式,可以根據(jù)應(yīng)用程序的需求進(jìn)行自定義
    2023-04-04
  • Android仿微信底部菜單欄效果

    Android仿微信底部菜單欄效果

    這篇文章主要為大家詳細(xì)介紹了Android仿微信底部菜單欄效果,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2017-11-11
  • Android實(shí)現(xiàn)網(wǎng)頁圖片瀏覽功能

    Android實(shí)現(xiàn)網(wǎng)頁圖片瀏覽功能

    這篇文章主要為大家詳細(xì)介紹了Android實(shí)現(xiàn)網(wǎng)頁圖片瀏覽功能,輸入圖片的url然后點(diǎn)擊按鈕加載出來圖片,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2017-05-05
  • 5種Android數(shù)據(jù)存儲(chǔ)方式匯總

    5種Android數(shù)據(jù)存儲(chǔ)方式匯總

    這篇文章主要為大家整理了5種Android數(shù)據(jù)存儲(chǔ)方式,列出了各存儲(chǔ)方式的優(yōu)缺點(diǎn),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2016-12-12

最新評(píng)論