android中怎麼對一個code進行加密

來源:互聯網
上載者:User

最近項目有一個需求就是某一個模組的功能必須輸入序號才能使用.輸入序號後加密後打包成為檔案存放在sdcard中,下次使用的時候驗證sdcard下面是否有這樣一個檔案.

java中是如何加密解密:

有這樣2個類:

KeyGenerator:此類提供(對稱)金鑰產生器的功能。

Cipher:此類為加密和解密提供密碼功能。

在加密和解密過程中Cipher會使用到KeyGenerator產生的key進行加密(產生密文)和解密(解析密文)

public class Main {public static void main(String[] args) throws NoSuchAlgorithmException, UnsupportedEncodingException {//-------------------加密過程---------------------------------//產生一個key,需要關聯一種“DES”演算法KeyGenerator keyGenerator = KeyGenerator.getInstance("DES");SecretKey deskey = keyGenerator.generateKey();//需要加密的infoString info = "12345678";//輸出加密前的密文內容System.out.println(""+info);//產生一個RandomSecureRandom sr = new SecureRandom(); byte[] cipherByteEncrypt = null;  try {Cipher c1 = Cipher.getInstance("DES");c1.init(Cipher.ENCRYPT_MODE, deskey, sr);//產生密文cipherByteEncrypt = c1.doFinal(info.getBytes());  } catch (Exception e) {e.printStackTrace();  }//輸出加密後的密文內容System.out.println(""+new String(cipherByteEncrypt,"ISO-8859-1"));//-------------------解密過程-----------------------------------//產生一個Random sr = new SecureRandom();   byte[] cipherByteDecrypt = null;   try { Cipher c1 = Cipher.getInstance("DES"); c1.init(Cipher.DECRYPT_MODE, deskey, sr);//解析密文     cipherByteDecrypt = c1.doFinal(cipherByteEncrypt);   } catch (Exception e) { e.printStackTrace();   } System.out.println(""+new String(cipherByteDecrypt,"ISO-8859-1"));}}

輸出:

12345678
3M±@*:?;???+j??? ---------------->這是密文
12345678

 

補充一個問題:

為什麼在代碼中會有使用ISO-8859-1來編碼.

看如下代碼:

bytebytes[] = new byte[] { 50, 0, -1, 28, -24 };

String string = new String(bytes);

byte[] ret = string.getBytes();

查看ret的資料發現是50, 0, -17, -65, -67, 28, -17, -65, -67,探索資料並不是原來的資料。

而使用如下代碼就可以得到原來的資料:

bytebytes[] = new byte[] { 50, 0, -1, 28, -24 };

StringisoString = new String(bytes, "ISO-8859-1");

byte[] isoret = isoString.getBytes("ISO-8859-1");

這是為什麼呢?原因是第一種方法預設是用UTF-8編碼來產生String的,用System.getProperty("sun.jnu.encoding")可以得到Android預設編碼是UTF-8。UTF-8是可變長度的編碼,原來的位元組數組就被改變了。而ISO8859-1通常叫做Latin-1,Latin-1包括了書寫所有西方歐洲語言不可缺少的附加字元,其中 0~127的字元與ASCII碼相同,它是單位元組的編碼方式,這樣第二種方式產生的String裡的位元組數組就跟原來的位元組數組一樣。在new String使用其他編碼如GBK,GB2312的話一樣也會導致位元組數組發生變化,因此要想擷取String裡單位元組數組,就應該使用iso8859-1編碼。

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.