1. 程式人生 > >Android RSA加密解密功能的實現

Android RSA加密解密功能的實現

本文主要是實現Android RSA加密解密功能,在網上參考了很多人提供的方法,自己改寫成一個關於Android RSA加密解密檔案的功能模組,方便今後參考使用。

1.在編寫程式碼前,需要準備好RSA的金鑰對。關於RSA金鑰對的生成網上有很多。可以去下載openssl-0.9.8k_WIN32,開啟cmd控制檯進入其bin目錄,執行以下操作:

(1)先來生成私鑰:

openssl genrsa -out rsa_private_key.pem 1024   

(2)根據私鑰生成公鑰:

openssl rsa -in rsa_private_key.pem -out rsa_public_key.pem -pubout  

(3)這時候的私鑰還不能直接被使用,需要進行PKCS#8編碼

openssl pkcs8 -topk8 -in rsa_private_key.pem -out pkcs8_rsa_private_key.pem -nocrypt  

注意:把生成的金鑰對pkcs8_rsa_private_key.pem,rsa_public_key.pem放到工程目錄的assets目錄下;

2.把獲取到的金鑰對放到工程目錄的assets目錄下之後,就可以開始編寫程式碼了。MainActivity

public class MainActivity extends Activity implements OnClickListener {
	private final String TAG="MainActivity";
	private Button encryptionBtn, decryptionBtn;// 加密,解密
	private EditText inputContent,outputEncryContent, outputDecryContent;// 需加密的內容,加密後的內容,解密後的內容

	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_rsamain);
		initView();
	}

	private void initView()
	{
		encryptionBtn = (Button) findViewById(R.id.encryption_btn);
		decryptionBtn = (Button) findViewById(R.id.decryption_btn);
		encryptionBtn.setOnClickListener(this);
		decryptionBtn.setOnClickListener(this);

		inputContent = (EditText) findViewById(R.id.input_content);
		outputEncryContent= (EditText) findViewById(R.id.output_encrycontent);
		outputDecryContent = (EditText) findViewById(R.id.output_decrycontent);
	}

	@Override
	public void onClick(View v)
	{
		switch (v.getId())
		{
		// 加密
		case R.id.encryption_btn:
			String source = inputContent.getText().toString().trim();
			Log.d(TAG, source);
			try
			{	Log.d(TAG, "進入");
				// 從檔案中得到公鑰
				InputStream inPublic = getAssets().open("rsa_public_key.pem");
				PublicKey publicKey = RSAUtils.loadPublicKey(inPublic);
				// 加密
				byte[] encryptByte = RSAUtils.encryptData(source.getBytes(), publicKey);
				
				// 為了方便觀察吧加密後的資料用base64加密轉一下,要不然看起來是亂碼,所以解密是也是要用Base64先轉換
				String afterencrypt = Base64Utils.encode(encryptByte);
				Log.d(TAG, afterencrypt );
				outputEncryContent.setText(afterencrypt);
			} catch (Exception e)
			{
				e.printStackTrace();
			}
			break;
		// 解密
		case R.id.decryption_btn:
			String encryptContent = outputEncryContent.getText().toString().trim();
			try
			{	
				// 從檔案中得到私鑰
				InputStream inPrivate = getResources().getAssets().open("pkcs8_rsa_private_key.pem");
				PrivateKey privateKey = RSAUtils.loadPrivateKey(inPrivate);
				// 因為RSA加密後的內容經Base64再加密轉換了一下,所以先Base64解密回來再給RSA解密
				byte[] decryptByte = RSAUtils.decryptData(Base64Utils.decode(encryptContent), privateKey);
				String decryptStr = new String(decryptByte);
				Log.d(TAG, decryptStr);
				 outputDecryContent.setText(decryptStr);
			} catch (Exception e)
			{
				e.printStackTrace();
			}
			break;
		default:
			break;
		}
	}

}

3.RSAUtils
@SuppressLint("TrulyRandom")
public final class RSAUtils {
	@SuppressWarnings("unused")
	private static String TAG="RSAUtils";
	private static String RSA = "RSA";

	/**
	 * 隨機生成RSA金鑰對(預設金鑰長度為1024)
	 * 
	 * @return
	 */
	public static KeyPair generateRSAKeyPair()
	{
		return generateRSAKeyPair(1024);
	}

	/**
	 * 隨機生成RSA金鑰對
	 * 
	 * @param keyLength
	 *            金鑰長度,範圍:512~2048
	 *            一般1024
	 * @return
	 */
	@SuppressLint("TrulyRandom") 
	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;
		}
	}

	/**
	 * 用公鑰加密
	 * 每次加密的位元組數,不能超過金鑰的長度值減去11
	 * 
	 * @param data
	 *            需加密資料的byte資料
	 * @param pubKey
	 *            公鑰
	 * @return 加密後的byte型資料
	 */
	public static byte[] encryptData(byte[] data, PublicKey publicKey)
	{
		try
		{
			Cipher cipher = Cipher.getInstance(RSA);
			// 編碼前設定編碼方式及金鑰
			cipher.init(Cipher.ENCRYPT_MODE, publicKey);
			// 傳入編碼資料並返回編碼結果
			return cipher.doFinal(data);
		} catch (Exception e)
		{
			e.printStackTrace();
			return null;
		}
	}

	/**
	 * 用私鑰解密
	 * 
	 * @param encryptedData
	 *            經過encryptedData()加密返回的byte資料
	 * @param privateKey
	 *            私鑰
	 * @return
	 */
	public static byte[] decryptData(byte[] encryptedData, PrivateKey privateKey)
	{
		try
		{
			Cipher cipher = Cipher.getInstance(RSA);
			cipher.init(Cipher.DECRYPT_MODE, privateKey);
			return cipher.doFinal(encryptedData);
		} catch (Exception e)
		{
			return null;
		}
	}

	/**
	 * 通過公鑰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;
	}

	/**
	 * 通過私鑰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
	 *            公鑰資料字串
	 * @throws Exception
	 *             載入公鑰時產生的異常
	 */
	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("無此演算法");
		} catch (InvalidKeySpecException e)
		{
			throw new Exception("公鑰非法");
		} catch (NullPointerException e)
		{
			throw new Exception("公鑰資料為空");
		}
	}

	/**
	 * 從字串中載入私鑰<br>
	 * 載入時使用的是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("無此演算法");
		} catch (InvalidKeySpecException e)
		{
			throw new Exception("私鑰非法");
		} catch (NullPointerException e)
		{
			throw new Exception("私鑰資料為空");
		}
	}

	/**
	 * 從檔案中輸入流中載入公鑰
	 * 
	 * @param in
	 *            公鑰輸入流
	 * @throws Exception
	 *             載入公鑰時產生的異常
	 */
	public static PublicKey loadPublicKey(InputStream in) throws Exception
	{
		try
		{
			return loadPublicKey(readKey(in));
		} catch (IOException e)
		{
			throw new Exception("公鑰資料流讀取錯誤");
		} catch (NullPointerException e)
		{
			throw new Exception("公鑰輸入流為空");
		}
	}

	/**
	 * 從檔案中載入私鑰
	 * 
	 * @param keyFileName
	 *            私鑰檔名
	 * @return 是否成功
	 * @throws Exception
	 */
	public static PrivateKey loadPrivateKey(InputStream in) throws Exception
	{
		try
		{
			return loadPrivateKey(readKey(in));
		} catch (IOException e)
		{
			throw new Exception("私鑰資料讀取錯誤");
		} 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());

	}

}

4.Base64Utils
public final 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) {
        if (data == null || data.length < 1) return null;

        StringBuilder sb = new StringBuilder();
        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) {
        if (TextUtils.isEmpty(str)) return null;

        try {
            return decodePrivate(str);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return new byte[]{};
    }

    private static byte[] decodePrivate(String str) throws UnsupportedEncodingException {
        if (TextUtils.isEmpty(str)) return null;

        StringBuilder sb = new StringBuilder();
        byte[] 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");
    }
}

5.佈局檔案 activity_rsamain.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context="com.example.rsa.MainActivity" >
    
     <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="RSA加密解密功能測試"
            android:textSize="24dip" 
            android:textStyle="bold"
            android:layout_gravity="center"
            android:layout_marginTop="40dip"/>

    <EditText
        android:id="@+id/input_content"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="輸入需加密的內容" />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal" 
        android:gravity="center_horizontal">

        <Button
            android:id="@+id/encryption_btn"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="加密" />

        <Button
            android:id="@+id/decryption_btn"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="解密" />
    </LinearLayout>

    <EditText
        android:id="@+id/output_encrycontent"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="加密後的內容" />

    <EditText
        android:id="@+id/output_decrycontent"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="解密後的內容" />

</LinearLayout>

6.Manifest檔案配置

這裡不需要新增許可權


相關推薦

Android RSA加密解密功能實現

本文主要是實現Android RSA加密解密功能,在網上參考了很多人提供的方法,自己改寫成一個關於Android RSA加密解密檔案的功能模組,方便今後參考使用。 1.在編寫程式碼前,需要準備好RSA的金鑰對。關於RSA金鑰對的生成網上有很多。可以去下載openssl-0

go語言實現非對稱加密——RSA加密解密實現

版權宣告:本文為作者原創,如需轉載,請註明出處 https://blog.csdn.net/weixin_42940826 非對稱加密簡介 什麼是非對稱加密 非對稱加密,顧名思義,是相對於對稱加密的一種加密方法,對稱加密是指加密與解密使用的是同一把祕鑰,而非對稱加

使用Python進行AES加密解密功能實現

PyCrypto是一款非常實用的Python加密模組,最近寫了一個檔案加密指令碼需要用到AES加密,和大家分析一下心得。 下載與安裝:PyCrypto專案已經於2015年7月停止了,下面是官方的下載地址。 https://www.dlitz.net/software/pycrypto/ 如果是l

python AES-16位加密解密功能實現

從網上搜了很多這種python AES相關內容,但是大部分都是需要自己除錯修改半天才能使用,有的甚至埋下很多坑,費時費力,我這邊根據專案需求,也需要弄一套AES-16位加密和解密API 我用的python加密元件是Crypto,很好用,可以從網上下載最新的庫,我用的比較穩

windows中使用Python進行AES加密解密-加密解密功能實現

PyCrypto是一款非常實用的Python加密模組,最近寫了一個檔案加密指令碼需要用到AES加密(http://blog.csdn.net/u013578500/article/details/77916990),和大家分析一下心得。 下載與安裝:PyCrypto專案

RSA加密解密C++實現

實現過程: 1 隨意選擇兩個大的質數p和q,p不等於q,計算N=p*q。 2 根據尤拉函式,求得r = (p-1)(q-1) 3 選擇一個小於 r 的整數 e,求得 e 關於模 r 的模反元素,命名為d。(模反元素存在,當且僅當e與r互質) 將 p 和

Node.js 基於 ursa 模組的 RSA 加密解密(已與IOS,Android實現加密通訊)

前幾天除錯一個RSA加密,遇到一些問題,在網上找了好久好久,與Node.js相關的資源少得非常可憐,最後還是靠自己一步一步解決了,今天把程式碼和一些心得拿出來分享一下: cnode連結地址:https://cnodejs.org/topic/54d2de4cf

Javascript實現前端AES加密解密功能

西安人 才網 西安人才網掌握的HTML中的js前端AES加密最近因為項目需求做了一次MITM,俄然即便發現運用HTTPS,也不能確保數據傳輸過程中的安全性。 經過中間人進犯,能夠直接獲取到Http協議的一切內容。 所以開端嘗試做一些簡略的加密,在一定程度上確保安全性。本次選用AES加密數據,所以客戶端

RSA加密解密及數字簽名Java實現

cto 包括 sign object misc 數據 factory 了解 對稱密鑰 RSA公鑰加密算法是1977年由羅納德·李維斯特(Ron Rivest)、阿迪·薩莫爾(Adi Shamir)和倫納德·阿德曼(Leonard Adleman)一起提出的。當時他們三人都在

php實現的三個常用加密解密功能函數示例

htm 常用 zab rand unlock ret == UNC test 目錄 算法一: 算法二: 算法三(改進第一個加密之後的算法) 本文實例講述了php實現的三個常用加密解密功能函數。分享給大家供大家參考,具體如下: 算法一: //加密函數 function

RSA加密解密實現(JAVA)

1.關於RSA演算法的原理解析參考:http://www.ruanyifeng.com/blog/2013/06/rsa_algorithm_part_one.html 2.RSA金鑰長度、明文長度和密文長度參考:https://blog.csdn.net/liuhuabai100/article/deta

條理清晰的入門:使用Java實現RSA加密解密

條理清晰的入門:使用Java實現RSA加密解密 什麼是RSA 使用Java 需要匯入的標頭檔案 生成公鑰、私鑰 進行加密解密 金鑰的儲存 密文的儲存、讀取 什麼是RSA 翻一下以前的密碼

JAVA實現RSA加密解密

RSA 工具類。提供加密,解密,生成金鑰對等方法。  RSA加密原理概述   : RSA的安全性依賴於大數的分解,公鑰和私鑰都是兩個大素數(大於100的十進位制位)的函式。 據猜測,從一個金鑰和密文推斷出明文的難度等同於分解兩個大素數的積    金鑰的產生:     1.選

RSA加密解密(無資料大小限制,php、go、java互通實現

RSA加解密中必須考慮到的金鑰長度、明文長度和密文長度問題。明文長度需要小於金鑰長度,而密文長度則等於金鑰長度。因此當加密內容長度大於金鑰長度時,有效的RSA加解密就需要對內容進行分段。這是因為,RSA演算法本身要求加密內容也就是明文長度m必須0<m<金鑰長度n。

C++實現RSA加密解密

RSA演算法的描述 1、選取長度相等的兩個大素數p和q,計算其乘積: n = pq 然後隨機選取加密金鑰e,使e和(p–1)(q–1)互素。 最後用歐幾里德擴充套件演算法計算解密金鑰d,以滿足 ed = 1(

C#實現RSA加密解密原始碼

{ privatestaticstring publicKey = "<RSAKeyValue><Modulus>6CdsXgYOyya/yQH"+ "TO96dB3gEurM2UQDDVGrZoe6RcAVTxAqDDf5L"+ "wPycZwtNOx3Cfy44/D5M

python實現aes加密解密RSA簽名和驗籤,RSA加密解密,並呼叫介面

用python實現呼叫介面的示例程式碼,過程涉及到很多的加密演算法,值得分享一下。首先公鑰和私鑰如何生成,並且能相容java平臺,嘗試了很多方法。最終決定用openssl命令前提,需要安裝openssl,Crypto庫生成公鑰私鑰對過程:生成私鑰: openssl ge

Java 實現 RSA加密解密及數字簽名

RSA公鑰加密演算法是1977年由羅納德·李維斯特(Ron Rivest)、阿迪·薩莫爾(Adi Shamir)和倫納德·阿德曼(Leonard Adleman)一起提出的。當時他們三人都在麻省理工學院工作。RSA就是他們三人姓氏開頭字母拼在一起組成的。 RSA是目

RSA加密解密實現

概述 RSA被稱為非對稱性加密演算法,意思就是加密和解密用的不是同一份金鑰。RSA演算法的金鑰分為公鑰和私鑰,兩者內容不同,用途也不同。公鑰用於加密,一般交給客戶端使用;私鑰用於解密,一般由伺服器管理。反過來,對稱性加密演算法,指的就是用同一份金鑰進行加密解密了,比如DES

C# 與JAVA 的RSA 加密解密交互,互通,C#使用BouncyCastle來實現私鑰加密,公鑰解密的方法

cipher process [] var class mar tor als get 因為C#的RSA加密解密只有公鑰加密,私鑰解密,沒有私鑰加密,公鑰解密。在網上查了很久也沒有很好的實現。BouncyCastle的文檔少之又少。很多人可能會說,C#也是可以的,通過Big