openssl 加密解密
生活随笔
收集整理的這篇文章主要介紹了
openssl 加密解密
小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
以上是項(xiàng)目結(jié)構(gòu)?
下面我就直接拷貝代碼 1,activity_main.xml <?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"xmlns:tools="http://schemas.android.com/tools"android:id="@+id/activity_main"android:layout_width="match_parent"android:layout_height="match_parent"android:paddingBottom="@dimen/activity_vertical_margin"android:paddingLeft="@dimen/activity_horizontal_margin"android:paddingRight="@dimen/activity_horizontal_margin"android:paddingTop="@dimen/activity_vertical_margin"tools:context="com.example.suiyantao.myapplication.MainActivity"><Buttonandroid:text="解密"android:layout_width="wrap_content"android:layout_height="wrap_content"android:id="@+id/button2"android:layout_alignBaseline="@+id/button"android:layout_alignBottom="@+id/button"android:layout_alignParentRight="true"android:layout_alignParentEnd="true"android:layout_marginRight="49dp"android:layout_marginEnd="49dp" /><EditTextandroid:layout_width="wrap_content"android:layout_height="wrap_content"android:inputType="textPersonName"android:ems="10"android:layout_above="@+id/button2"android:id="@+id/editText"android:layout_alignParentLeft="true"android:layout_alignParentStart="true"android:layout_alignParentRight="true"android:layout_alignParentEnd="true" /><Buttonandroid:text="加密"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_marginLeft="14dp"android:layout_marginStart="14dp"android:id="@+id/button"android:layout_marginTop="47dp"android:layout_alignParentTop="true"android:layout_alignParentLeft="true"android:layout_alignParentStart="true" /><EditTextandroid:layout_width="match_parent"android:layout_height="100dp"android:inputType="textMultiLine"android:ems="10"android:layout_marginTop="48dp"android:id="@+id/editText2"android:singleLine="false"android:layout_below="@+id/button2"android:layout_alignParentStart="true" /><EditTextandroid:layout_width="match_parent"android:layout_height="100dp"android:inputType="textMultiLine"android:ems="10"android:layout_marginTop="50dp"android:id="@+id/editText3"android:layout_below="@+id/editText2"android:layout_alignParentStart="true" /></RelativeLayout> MainActivity.java
package com.example.suiyantao.myapplication;import android.net.Uri; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.Toast;import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; import com.android.volley.AuthFailureError; import com.android.volley.Request; import com.android.volley.RequestQueue; import com.android.volley.Response; import com.android.volley.VolleyError; import com.android.volley.toolbox.StringRequest; import com.android.volley.toolbox.Volley; import com.google.android.gms.appindexing.Action; import com.google.android.gms.appindexing.AppIndex; import com.google.android.gms.appindexing.Thing; import com.google.android.gms.common.api.GoogleApiClient;import org.json.JSONException;import java.util.HashMap; import java.util.Map;public class MainActivity extends AppCompatActivity {Button btn1, btn2;Toast tst;EditText text1, text2, text3;/*** ATTENTION: This was auto-generated to implement the App Indexing API.* See https://g.co/AppIndexing/AndroidStudio for more information.*/private GoogleApiClient client;/*** ATTENTION: This was auto-generated to implement the App Indexing API.* See https://g.co/AppIndexing/AndroidStudio for more information.*/public Action getIndexApiAction() {Thing object = new Thing.Builder().setName("Main Page") // TODO: Define a title for the content shown.// TODO: Make sure this auto-generated URL is correct..setUrl(Uri.parse("http://[ENTER-YOUR-URL-HERE]")).build();return new Action.Builder(Action.TYPE_VIEW).setObject(object).setActionStatus(Action.STATUS_TYPE_COMPLETED).build();}@Overridepublic void onStart() {super.onStart();// ATTENTION: This was auto-generated to implement the App Indexing API.// See https://g.co/AppIndexing/AndroidStudio for more information.client.connect();AppIndex.AppIndexApi.start(client, getIndexApiAction());}@Overridepublic void onStop() {super.onStop();// ATTENTION: This was auto-generated to implement the App Indexing API.// See https://g.co/AppIndexing/AndroidStudio for more information.AppIndex.AppIndexApi.end(client, getIndexApiAction());client.disconnect();}class MyClickListener implements View.OnClickListener {OpenSSLInterface osi = new OpenSSLImpl(getAssets());@Overridepublic void onClick(View v) {switch (v.getId()) {case R.id.button:text1 = (EditText) findViewById(R.id.editText);try {text2 = (EditText) findViewById(R.id.editText2);tst = Toast.makeText(MainActivity.this, "加密成功", Toast.LENGTH_LONG);String afterencrypt = osi.encryption(text1.getText().toString());Log.i("msg_2016_09_26", text1.getText().toString());tst.show();text2.setText(afterencrypt);} catch (Exception e) {e.printStackTrace();}break;case R.id.button2:text2 = (EditText) findViewById(R.id.editText2);RequestQueue requestQueue = Volley.newRequestQueue(getApplicationContext());StringRequest request = new StringRequest(Request.Method.POST, "http://192.168.0.107:8080/app", new Response.Listener<String>() {@Overridepublic void onResponse(String response) {JSONObject res = JSON.parseObject(response);String success =res.getString("success");if ("true".equals(success)) {String msg =res.getString("msg");tst = Toast.makeText(MainActivity.this, "解密成功", Toast.LENGTH_LONG);text3 = (EditText) findViewById(R.id.editText3);text3.setText(msg);Log.i("msg_2016_09_26", msg);tst.show();}else{tst.setText("解密失敗");tst.show();}}}, new Response.ErrorListener() {@Overridepublic void onErrorResponse(VolleyError error) {Log.i("VolleyError Msg", error.getMessage());Toast.makeText(MainActivity.this, error.getMessage(), Toast.LENGTH_LONG).show();}}) {@Overrideprotected Map<String, String> getParams() throws AuthFailureError {Map<String, String> map = new HashMap<>();map.put("data", text2.getText().toString());return map;}};requestQueue.add(request);try { // tst = Toast.makeText(MainActivity.this,"解密成功",Toast.LENGTH_LONG); // text3 = (EditText) findViewById(R.id.editText3); // String decryptStr = osi1.deciphering(text2.getText().toString()); // text3.setText(decryptStr); // Log.i("msg_2016_09_26",decryptStr); // tst.show();} catch (Exception e) {e.printStackTrace();}break;default:// tst.show();break;}}}@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);btn1 = (Button) findViewById(R.id.button);btn2 = (Button) findViewById(R.id.button2);btn1.setOnClickListener(new MyClickListener());btn2.setOnClickListener(new MyClickListener());// ATTENTION: This was auto-generated to implement the App Indexing API.// See https://g.co/AppIndexing/AndroidStudio for more information.client = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build();} } 3,OpenSSLInterface.java package com.example.suiyantao.myapplication;import android.content.res.AssetManager;/*** Created by suiyantao on 16/10/18.*/public interface OpenSSLInterface {/***加密* @param mw* @return*/String encryption(String mw);String deciphering(String mw); }
4,OpenSSLImpl.java package com.example.suiyantao.myapplication;import android.content.res.AssetManager; import android.util.Log;import java.io.InputStream; import java.security.PrivateKey; import java.security.PublicKey;/*** Created by suiyantao on 16/10/18.*/public class OpenSSLImpl implements OpenSSLInterface {private AssetManager assetManager;public OpenSSLImpl(AssetManager assetManager) {this.assetManager = assetManager;}/*** 加密* @param mw 明文* @return*/@Overridepublic String encryption(String mw) {try {InputStream inPublic = assetManager.open("rsa_public_key.pem");PublicKey publicKey = RSAUtils.loadPublicKey(inPublic);byte[] encryptByte = RSAUtils.encryptData(mw.trim().getBytes(), publicKey);return Base64Utils.encode(encryptByte);} catch (Exception e) {e.printStackTrace();}return null;}/*** 解密* @param mw 密文* @return*/@Overridepublic String deciphering(String mw) {try {Log.i("sss",mw);InputStream inPrivate = assetManager.open("pkcs8_rsa_private_key.pem");PrivateKey privateKey = RSAUtils.loadPrivateKey(inPrivate);byte[] decryptByte = RSAUtils.decryptData(Base64Utils.decode(mw.trim()), privateKey);return new String(decryptByte);} catch (Exception e) {e.printStackTrace();}return null;}}
5,Base64Utils.java package com.example.suiyantao.myapplication;import java.io.UnsupportedEncodingException; /*** Created by suiyantao on 16/10/19.*/public class Base64Utils {private static char[] base64EncodeChars = new char[]{ 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T','U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm','n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5','6', '7', '8', '9', '+', '/' };private static byte[] base64DecodeChars = new byte[]{ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 62, -1, -1, -1, 63, 52, 53,54, 55, 56, 57, 58, 59, 60, 61, -1, -1, -1, -1, -1, -1, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, -1, -1, 26, 27, 28, 29,30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, -1, -1,-1, -1, -1 };/*** 加密** @param data* @return*/public static String encode(byte[] data){StringBuffer sb = new StringBuffer();int len = data.length;int i = 0;int b1, b2, b3;while (i < len){b1 = data[i++] & 0xff;if (i == len){sb.append(base64EncodeChars[b1 >>> 2]);sb.append(base64EncodeChars[(b1 & 0x3) << 4]);sb.append("==");break;}b2 = data[i++] & 0xff;if (i == len){sb.append(base64EncodeChars[b1 >>> 2]);sb.append(base64EncodeChars[((b1 & 0x03) << 4) | ((b2 & 0xf0) >>> 4)]);sb.append(base64EncodeChars[(b2 & 0x0f) << 2]);sb.append("=");break;}b3 = data[i++] & 0xff;sb.append(base64EncodeChars[b1 >>> 2]);sb.append(base64EncodeChars[((b1 & 0x03) << 4) | ((b2 & 0xf0) >>> 4)]);sb.append(base64EncodeChars[((b2 & 0x0f) << 2) | ((b3 & 0xc0) >>> 6)]);sb.append(base64EncodeChars[b3 & 0x3f]);}return sb.toString();}/*** 解密** @param str* @return*/public static byte[] decode(String str){try{return decodePrivate(str);} catch (UnsupportedEncodingException e){e.printStackTrace();}return new byte[]{};}private static byte[] decodePrivate(String str) throws UnsupportedEncodingException{StringBuffer sb = new StringBuffer();byte[] data = null;data = str.getBytes("US-ASCII");int len = data.length;int i = 0;int b1, b2, b3, b4;while (i < len){do{b1 = base64DecodeChars[data[i++]];} while (i < len && b1 == -1);if (b1 == -1)break;do{b2 = base64DecodeChars[data[i++]];} while (i < len && b2 == -1);if (b2 == -1)break;sb.append((char) ((b1 << 2) | ((b2 & 0x30) >>> 4)));do{b3 = data[i++];if (b3 == 61)return sb.toString().getBytes("iso8859-1");b3 = base64DecodeChars[b3];} while (i < len && b3 == -1);if (b3 == -1)break;sb.append((char) (((b2 & 0x0f) << 4) | ((b3 & 0x3c) >>> 2)));do{b4 = data[i++];if (b4 == 61)return sb.toString().getBytes("iso8859-1");b4 = base64DecodeChars[b4];} while (i < len && b4 == -1);if (b4 == -1)break;sb.append((char) (((b3 & 0x03) << 6) | b4));}return sb.toString().getBytes("iso8859-1");}}
6,RSAUtils.java package com.example.suiyantao.myapplication;import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.math.BigInteger; import java.security.KeyFactory; import java.security.KeyPair; import java.security.KeyPairGenerator; import java.security.NoSuchAlgorithmException; import java.security.PrivateKey; import java.security.PublicKey; import java.security.interfaces.RSAPrivateKey; import java.security.interfaces.RSAPublicKey; import java.security.spec.InvalidKeySpecException; import java.security.spec.PKCS8EncodedKeySpec; import java.security.spec.RSAPublicKeySpec; import java.security.spec.X509EncodedKeySpec;import javax.crypto.Cipher;public final class RSAUtils {private static String RSA = "RSA";/*** 隨機(jī)生成RSA密鑰對(duì)(默認(rèn)密鑰長(zhǎng)度為1024)** @return*/public static KeyPair generateRSAKeyPair(){return generateRSAKeyPair(1024);}/*** 隨機(jī)生成RSA密鑰對(duì)** @param keyLength* 密鑰長(zhǎng)度,范圍:512~2048<br>* 一般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;}}/*** 用公鑰加密 <br>* 每次加密的字節(jié)數(shù),不能超過(guò)密鑰的長(zhǎng)度值減去11** @param data* 需加密數(shù)據(jù)的byte數(shù)據(jù)* @param publicKey* 公鑰* @return 加密后的byte型數(shù)據(jù)*/public static byte[] encryptData(byte[] data, PublicKey publicKey){try{Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");// 編碼前設(shè)定編碼方式及密鑰cipher.init(Cipher.ENCRYPT_MODE, publicKey);// 傳入編碼數(shù)據(jù)并返回編碼結(jié)果return cipher.doFinal(data);} catch (Exception e){e.printStackTrace();return null;}}/*** 用私鑰解密** @param encryptedData* 經(jīng)過(guò)encryptedData()加密返回的byte數(shù)據(jù)* @param privateKey* 私鑰* @return*/public static byte[] decryptData(byte[] encryptedData, PrivateKey privateKey){try{Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");cipher.init(Cipher.DECRYPT_MODE, privateKey);return cipher.doFinal(encryptedData);} catch (Exception e){return null;}}/*** 通過(guò)公鑰byte[](publicKey.getEncoded())將公鑰還原,適用于RSA算法** @param keyBytes* @return* @throws NoSuchAlgorithmException* @throws InvalidKeySpecException*/public static PublicKey getPublicKey(byte[] keyBytes) throws NoSuchAlgorithmException,InvalidKeySpecException{X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyBytes);KeyFactory keyFactory = KeyFactory.getInstance(RSA);PublicKey publicKey = keyFactory.generatePublic(keySpec);return publicKey;}/*** 通過(guò)私鑰byte[]將公鑰還原,適用于RSA算法** @param keyBytes* @return* @throws NoSuchAlgorithmException* @throws InvalidKeySpecException*/public static PrivateKey getPrivateKey(byte[] keyBytes) throws NoSuchAlgorithmException,InvalidKeySpecException{PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(keyBytes);KeyFactory keyFactory = KeyFactory.getInstance(RSA);PrivateKey privateKey = keyFactory.generatePrivate(keySpec);return privateKey;}/*** 使用N、e值還原公鑰** @param modulus* @param publicExponent* @return* @throws NoSuchAlgorithmException* @throws InvalidKeySpecException*/public static PublicKey getPublicKey(String modulus, String publicExponent)throws NoSuchAlgorithmException, InvalidKeySpecException{BigInteger bigIntModulus = new BigInteger(modulus);BigInteger bigIntPrivateExponent = new BigInteger(publicExponent);RSAPublicKeySpec keySpec = new RSAPublicKeySpec(bigIntModulus, bigIntPrivateExponent);KeyFactory keyFactory = KeyFactory.getInstance(RSA);PublicKey publicKey = keyFactory.generatePublic(keySpec);return publicKey;}/*** 使用N、d值還原私鑰** @param modulus* @param privateExponent* @return* @throws NoSuchAlgorithmException* @throws InvalidKeySpecException*/public static PrivateKey getPrivateKey(String modulus, String privateExponent)throws NoSuchAlgorithmException, InvalidKeySpecException{BigInteger bigIntModulus = new BigInteger(modulus);BigInteger bigIntPrivateExponent = new BigInteger(privateExponent);RSAPublicKeySpec keySpec = new RSAPublicKeySpec(bigIntModulus, bigIntPrivateExponent);KeyFactory keyFactory = KeyFactory.getInstance(RSA);PrivateKey privateKey = keyFactory.generatePrivate(keySpec);return privateKey;}/*** 從字符串中加載公鑰** @param publicKeyStr* 公鑰數(shù)據(jù)字符串* @throws Exception* 加載公鑰時(shí)產(chǎn)生的異常*/public static PublicKey loadPublicKey(String publicKeyStr) throws Exception{try{byte[] buffer = Base64Utils.decode(publicKeyStr);KeyFactory keyFactory = KeyFactory.getInstance(RSA);X509EncodedKeySpec keySpec = new X509EncodedKeySpec(buffer);return (RSAPublicKey) keyFactory.generatePublic(keySpec);} catch (NoSuchAlgorithmException e){throw new Exception("無(wú)此算法");} catch (InvalidKeySpecException e){throw new Exception("公鑰非法");} catch (NullPointerException e){throw new Exception("公鑰數(shù)據(jù)為空");}}/*** 從字符串中加載私鑰<br>* 加載時(shí)使用的是PKCS8EncodedKeySpec(PKCS#8編碼的Key指令)。** @param privateKeyStr* @return* @throws Exception*/public static PrivateKey loadPrivateKey(String privateKeyStr) throws Exception{try{byte[] buffer = Base64Utils.decode(privateKeyStr);// X509EncodedKeySpec keySpec = new X509EncodedKeySpec(buffer);PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(buffer);KeyFactory keyFactory = KeyFactory.getInstance(RSA);return (RSAPrivateKey) keyFactory.generatePrivate(keySpec);} catch (NoSuchAlgorithmException e){throw new Exception("無(wú)此算法");} catch (InvalidKeySpecException e){throw new Exception("私鑰非法");} catch (NullPointerException e){throw new Exception("私鑰數(shù)據(jù)為空");}}/*** 從文件中輸入流中加載公鑰** @param in* 公鑰輸入流* @throws Exception* 加載公鑰時(shí)產(chǎn)生的異常*/public static PublicKey loadPublicKey(InputStream in) throws Exception{try{return loadPublicKey(readKey(in));} catch (IOException e){throw new Exception("公鑰數(shù)據(jù)流讀取錯(cuò)誤");} catch (NullPointerException e){throw new Exception("公鑰輸入流為空");}}/*** 從文件中加載私鑰** @param in* 私鑰文件名* @return 是否成功* @throws Exception*/public static PrivateKey loadPrivateKey(InputStream in) throws Exception{try{return loadPrivateKey(readKey(in));} catch (IOException e){throw new Exception("私鑰數(shù)據(jù)讀取錯(cuò)誤");} catch (NullPointerException e){throw new Exception("私鑰輸入流為空");}}/*** 讀取密鑰信息** @param in* @return* @throws IOException*/private static String readKey(InputStream in) throws IOException{BufferedReader br = new BufferedReader(new InputStreamReader(in));String readLine = null;StringBuilder sb = new StringBuilder();while ((readLine = br.readLine()) != null){if (readLine.charAt(0) == '-'){continue;} else{sb.append(readLine);sb.append('\r');}}return sb.toString();}/*** 打印公鑰信息** @param publicKey*/public static void printPublicKeyInfo(PublicKey publicKey){RSAPublicKey rsaPublicKey = (RSAPublicKey) publicKey;System.out.println("----------RSAPublicKey----------");System.out.println("Modulus.length=" + rsaPublicKey.getModulus().bitLength());System.out.println("Modulus=" + rsaPublicKey.getModulus().toString());System.out.println("PublicExponent.length=" + rsaPublicKey.getPublicExponent().bitLength());System.out.println("PublicExponent=" + rsaPublicKey.getPublicExponent().toString());}public static void printPrivateKeyInfo(PrivateKey privateKey){RSAPrivateKey rsaPrivateKey = (RSAPrivateKey) privateKey;System.out.println("----------RSAPrivateKey ----------");System.out.println("Modulus.length=" + rsaPrivateKey.getModulus().bitLength());System.out.println("Modulus=" + rsaPrivateKey.getModulus().toString());System.out.println("PrivateExponent.length=" + rsaPrivateKey.getPrivateExponent().bitLength());System.out.println("PrivatecExponent=" + rsaPrivateKey.getPrivateExponent().toString());}}
到此代碼我都上傳完畢啦,在MainActivity 我解密用的是后臺(tái),大家改成我注釋掉的代碼就可以看到效果
下面看下運(yùn)行效果吧
到此結(jié)束啦!
總結(jié)
以上是生活随笔為你收集整理的openssl 加密解密的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 树莓派 触摸屏_如何用树莓派搭建一个颗粒
- 下一篇: git推送本地分支到远程分支