Android RSA解密 5C

目前项目有一个后台是使用RSA公钥加密,而后台给我的私钥是字符串, 请问如何把后台给的是要的字符串转换成PrivateKey

2个回答

得看看是什么样的字符串啊。PrivateKey本身也会转化成字符串。文件的会分cer和pem还有key的。另外还要看语言,没有这些信息没办法转换的。

我贴一个demo,供参考:

 import javax.crypto.Cipher;
import javax.crypto.CipherInputStream;
import javax.crypto.CipherOutputStream;
import javax.crypto.NoSuchPaddingException;
import java.io.*;
import java.security.*;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;

public class PrivateKeyTest {

    /**
     * 根据私钥字符串生成私钥对象
     */
    private static void test1() throws InvalidKeySpecException, NoSuchAlgorithmException {
        byte[] bytes = "xxxx".getBytes();
        PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(bytes);
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        PrivateKey privateKey = keyFactory.generatePrivate(pkcs8EncodedKeySpec);
    }

    /**
     * 1、随机生成一个秘钥对
     * 2、加密
     * 3、解密
     */
    private static void test2() throws NoSuchAlgorithmException, NoSuchPaddingException, IOException, InvalidKeyException {
        KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
        keyPairGenerator.initialize(1024);
        KeyPair keyPair = keyPairGenerator.generateKeyPair();

        String text = "abcdefghijklmn";

        // 加密
        Cipher encryptCipher = Cipher.getInstance("RSA");
        encryptCipher.init(Cipher.ENCRYPT_MODE, keyPair.getPrivate());
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        CipherOutputStream cipherOutputStream = new CipherOutputStream(byteArrayOutputStream, encryptCipher);
        DataOutputStream dataOutputStream = new DataOutputStream(cipherOutputStream);
        dataOutputStream.writeUTF(text);
        dataOutputStream.flush();
        dataOutputStream.close();
        byte[] cipherTextData = byteArrayOutputStream.toByteArray();

        // 解密
        Cipher decryptCipher = Cipher.getInstance("RSA");
        decryptCipher.init(Cipher.DECRYPT_MODE, keyPair.getPublic());
        ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(cipherTextData);
        CipherInputStream cipherInputStream = new CipherInputStream(byteArrayInputStream, decryptCipher);
        DataInputStream dataInputStream = new DataInputStream(cipherInputStream);
        String result = dataInputStream.readUTF();
        dataInputStream.close();
        System.out.println("result = " + result);
    }

    public static void main(String[] args) throws InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException, IOException {
        test2();
    }

}
Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
其他相关推荐
安卓RSA私钥解密 出现乱码

最近遇到了1个奇葩的项目需求,需要在安卓客户端做RSA私钥解密的工作,写了代码以后发现一直输出乱码 ```public class RSAUtils { /** * load private key from a stream * * @param * @return * @throws Exception */ private static final int MAX_DECRYPT_BLOCK = 256; private static RSAPrivateKey loadPrivateKey(InputStream in) throws Exception { RSAPrivateKey priKey; try { 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'); } } byte[] priKeyData = Base64.decode(new String(sb), Base64.DEFAULT); PKCS8EncodedKeySpec keySpec= new PKCS8EncodedKeySpec(priKeyData); KeyFactory keyFactory= KeyFactory.getInstance("RSA"); priKey= (RSAPrivateKey) keyFactory.generatePrivate(keySpec); } catch (IOException e) { throw new Exception("error reading the key"); } catch (NullPointerException e) { throw new Exception("inputstream is null"); } return priKey; } /** * decrypt with a private key * * @param privateKey * @param cipherData * @return * @throws Exception */ private static byte[] decrypt(RSAPrivateKey privateKey, byte[] cipherData) throws Exception { if (privateKey == null) { throw new Exception("key is null"); } Cipher cipher = null; try { cipher = Cipher.getInstance("RSA"); cipher.init(Cipher.DECRYPT_MODE, privateKey); int inputLen = cipherData.length; ByteArrayOutputStream out = new ByteArrayOutputStream(); int offSet = 0; byte[] cache; int i = 0; while (inputLen - offSet > 0) { if (inputLen - offSet > MAX_DECRYPT_BLOCK) { cache = cipher.doFinal(cipherData, offSet, MAX_DECRYPT_BLOCK); } else { cache = cipher.doFinal(cipherData, offSet, inputLen - offSet); } out.write(cache, 0, cache.length); i++; offSet = i * MAX_DECRYPT_BLOCK; } byte[] decryptedData = out.toByteArray(); out.close(); return decryptedData; } catch (NoSuchAlgorithmException e) { throw new Exception("no such algorithm"); } catch (NoSuchPaddingException e) { e.printStackTrace(); return null; } catch (InvalidKeyException e) { throw new Exception("InvalidKeyException"); } catch (IllegalBlockSizeException e) { throw new Exception("IllegalBlockSizeException"); } catch (BadPaddingException e) { throw new Exception("BadPaddingException"); } } public static String RSADecrypt(Context context, String KeyFileNameInAssetFolder, byte[] content) { String result = "error"; try { InputStream inputStream = context.getResources().getAssets().open(KeyFileNameInAssetFolder); RSAPrivateKey privateKey = loadPrivateKey(inputStream); byte[] b = decrypt(privateKey, content); result = new String(b); } catch (Exception e) { e.printStackTrace(); } return result; } ``` 调用的时候 我调了 ``` String result = RSAUtils.RSADecrypt(getApplicationContext(),"pkcs8.pem",Base64.decode(s,Base64.DEFAULT)); ``` 然后输出的一直是 ��*�ۘˋ��Ӡ���b$�<Ni����E�Dν��Y��u��Z߱���C�$i�3��yDŽS�bI.E�lI�Cq\}e|=xc�t���%�̳��(�>�`�����=ݞ*��6̞Q;��D��ffd��W�J: �������C�tG���r�=�5�n����#a�x��٠���^��l�Y�ث�2��#�j�\��.^�N�y�`�6_X੒J��,�8�ԑDw�tpV�|<Zܕ~�$u���������#���U�)�3�0ͧ%�K��>\5[�H�D�4 ��I� 类似这种东西 不这i到哪里错了

Android中的RSA生成正确的密钥但错误的解密

<div class="post-text" itemprop="text"> <p>I am trying to encrypt username and password data in MySQL database using PHP and Android. I am keeping the data as a <strong>BLOB</strong> type in MySQL DB along with the <strong>public key in the Database</strong>. NOTE : Retrieval and Submission of done is done in <strong>JSON format using HTTP</strong>.</p> <p><strong>But</strong> : I am getting the <strong>wrong data</strong>(<strong>easily visible in log below</strong> that (sid,a) is used for (username,password) and (YzJsawo=,YzJsawo=) is obtained) after decryption despite using Base64encoding to retrieve the data.(I have already tried it with CHAR and VARCHAR but no success). </p> <p><strong>Please help</strong> I have my project submission tomorrow. Worried. If at all u think that u won't be able to read the code that i have written please provide me with an alternative for above problem or a link where similar problem is discussed(Although i couldn't find one).</p> <p>Here is what I am trying to do.</p> <p><strong>Encryption Part</strong></p> <p></p><div class="snippet" data-lang="js" data-hide="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>protected String doInBackground(String... args) { runOnUiThread(new Runnable() { public void run() { userStr = inputUsername.getText().toString(); passStr = inputPassword.getText().toString(); confirmpass = inputConfirmPass.getText().toString(); if(userStr.equals("") || passStr.equals("") || confirmpass.equals("")) { Toast.makeText(getApplicationContext(),"Enter all the fields" ,Toast.LENGTH_SHORT).show(); } else { if(passStr.equals(confirmpass)) { //Encoding the string using RSA Algorithm // Original text valid=1; // Generate key pair for 1024-bit RSA encryption and decryption Key publicKey = null; Key privateKey = null; String publicKeyStr; try { KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA"); kpg.initialize(1024); KeyPair kp = kpg.genKeyPair(); publicKey = kp.getPublic(); privateKey = kp.getPrivate(); } catch (Exception e) { Log.e("", "RSA key pair error"); } byte[] encodedUser = null,encodedPassword = null; //Changing public key to str to transfer it between activities publicKeyStr = Base64.encodeToString(publicKey.getEncoded(), Base64.DEFAULT); try { //Encoding Username // Encode the original data with RSA private key Cipher c = Cipher.getInstance("RSA/ECB/PKCS1Padding"); c.init(Cipher.ENCRYPT_MODE, privateKey); encodedUser = c.doFinal(Base64.encode(userStr.getBytes("utf-8"),Base64.DEFAULT)); //Encoding Password encodedPassword = c.doFinal(Base64.encode(passStr.getBytes("utf-8"),Base64.DEFAULT)); } catch (Exception e) { Log.e("Error Type:", "RSA encryption error"); } String UsernameStrEncod,PasswordStrEncod; UsernameStrEncod = Base64.encodeToString(encodedUser, Base64.DEFAULT); PasswordStrEncod = Base64.encodeToString(encodedPassword, Base64.DEFAULT); List&lt;NameValuePair&gt; params = new ArrayList&lt;NameValuePair&gt;(); params.add(new BasicNameValuePair("username", UsernameStrEncod)); params.add(new BasicNameValuePair("password", PasswordStrEncod)); params.add(new BasicNameValuePair("publickey", publicKeyStr)); // getting JSON Object // Note that create product url accepts POST method JSONObject json = jsonParser.makeHttpRequest(url_register_user,"POST", params); // check log cat fro response Log.d("Create Response", json.toString()); // check for success tag try { int success = json.getInt(TAG_SUCCESS); if (success == 1) { // successfully created product Intent i = new Intent(getApplicationContext(), LoginActivity.class); //i.putExtra("encodedUser", encodedUser); //i.putExtra("publicKey", publicKeyStr); startActivity(i); // closing this screen finish(); } else { // failed to create product } } catch (JSONException e) { e.printStackTrace(); } } else Toast.makeText(getApplicationContext(),"Both the passwords do not match" ,Toast.LENGTH_SHORT).show(); } } }); return null; }</code></pre> </div> </div> <p><strong>Decryption Part</strong></p> <p></p><div class="snippet" data-lang="js" data-hide="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>protected String doInBackground(String... params) { // updating UI from Background Thread runOnUiThread(new Runnable() { public void run() { // Check for success tag int success; int found=0; try { //EditText variable initialization inputUsername = (EditText) findViewById(R.id.UsernameID); inputPassword = (EditText) findViewById(R.id.PasswordID); //Converting EditText to string user = inputUsername.getText().toString(); password = inputPassword.getText().toString(); if(user.equals("") || (password.equals(""))) Toast.makeText(getApplicationContext(),"Enter Both the fields" ,Toast.LENGTH_SHORT).show(); // Building Parameters else { List&lt;NameValuePair&gt; params = new ArrayList&lt;NameValuePair&gt;(); params.add(new BasicNameValuePair("username", user)); params.add(new BasicNameValuePair("password", password)); Log.d(user,password); // getting product details by making HTTP request // Note that product details url will use GET request JSONObject json = jsonParser.makeHttpRequest(url_login_details, "GET", params); // check your log for json response Log.d("Login Details", json.toString()); // json success tag success = json.getInt(TAG_SUCCESS); if (success == 1) { // successfully received product details JSONArray userArray = json.getJSONArray(TAG_USER); // JSON Array for(int j=0; (j&lt;userArray.length()) &amp;&amp; (found==0); ++j) { // get first product object from JSON Array JSONObject userObj = userArray.getJSONObject(j); String u = userObj.getString(TAG_USERNAME); String p = userObj.getString(TAG_PASSWORD); String publicKey = userObj.getString(TAG_PUBLICKEY); Log.d("usernameBlob:", u); Log.d("passwordBlob:", p); Log.d("publickeyBlob:", publicKey); //Decoding the data obtained from DB byte[] UsernameByteDecod = null, PasswordByteDecod = null; String UsernameStrDecod = null,PasswordStrDecod = null; try { //Converting the string public key into key type byte[] keyBytes = Base64.decode(publicKey.getBytes("utf-8"),Base64.DEFAULT); X509EncodedKeySpec spec = new X509EncodedKeySpec(keyBytes); KeyFactory keyFactory = KeyFactory.getInstance("RSA"); PublicKey publickey = keyFactory.generatePublic(spec); Cipher c = Cipher.getInstance("RSA/ECB/PKCS1Padding"); c.init(Cipher.DECRYPT_MODE, publickey); //Decoding the data UsernameByteDecod = c.doFinal(Base64.decode(u.getBytes("UTF-8"),Base64.DEFAULT)); PasswordByteDecod = c.doFinal(Base64.decode(u.getBytes("UTF-8"),Base64.DEFAULT)); UsernameStrDecod = Base64.encodeToString(UsernameByteDecod, Base64.DEFAULT); PasswordStrDecod = Base64.encodeToString(PasswordByteDecod, Base64.DEFAULT); Log.d("Username:",UsernameStrDecod); Log.d("Password:",PasswordStrDecod); } catch (Exception e) { Log.e("RSA Error:", "RSA decryption error"); e.printStackTrace(); } if((user.equals(UsernameStrDecod)) &amp;&amp; (password.equals(PasswordStrDecod))) { found=1; } else if(user.equals(u)) { Toast.makeText(getApplicationContext(),"Password is Incorrect" ,Toast.LENGTH_SHORT).show(); break; } else { } // display product data in EditText } } else { Toast.makeText(getApplicationContext(),"You are not registered, Register Here" ,Toast.LENGTH_SHORT).show(); Intent i = new Intent(getApplicationContext(), RegisterActivity.class); startActivity(i); } if(found==1) { Toast.makeText(getApplicationContext(),"Welcome "+ user ,Toast.LENGTH_SHORT).show(); Intent i = new Intent(getApplicationContext(), MainActivity.class); startActivity(i); //finish(); } else if(found==0) { Toast.makeText(getApplicationContext(),"You are not registered, Register Here" ,Toast.LENGTH_SHORT).show(); Intent i = new Intent(getApplicationContext(), RegisterActivity.class); startActivity(i); //finish(); } } } catch (JSONException e) { e.printStackTrace(); } } }); return null; }</code></pre> </div> </div> <p><strong>PHP Script for Inserting data after Encryption</strong></p> <p></p><div class="snippet" data-lang="js" data-hide="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>&lt;?php /* * Following code will create a new product row * All product details are read from HTTP Post Request */ // array for JSON response $response = array(); // check for required fields if (isset($_POST['username']) &amp;&amp; isset($_POST['password']) &amp;&amp; isset($_POST['publickey'])) { $username = $_POST['username']; $password = $_POST['password']; $publickey = $_POST['publickey']; // include db connect class require_once __DIR__ . '/users_db_connect.php'; // connecting to db $db = new DB_CONNECT(); // mysql inserting a new row $result = mysql_query("INSERT INTO user(username, password, publickey) VALUES('$username', '$password', '$publickey')"); // check if row inserted or not if ($result) { // successfully inserted into database $response["success"] = 1; $response["message"] = "Successfull Registration."; // echoing JSON response echo json_encode($response); } else { // failed to insert row $response["success"] = 0; $response["message"] = "Oops! An error occurred."; // echoing JSON response echo json_encode($response); } } else { // required field is missing $response["success"] = 0; $response["message"] = "Required field(s) is missing"; // echoing JSON response echo json_encode($response); } ?&gt;</code></pre> </div> </div> <p><strong>PHP Script for retrieving data and Decrypting it afterwards</strong></p> <p></p><div class="snippet" data-lang="js" data-hide="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>&lt;?php /* * Following code will list all the products * */ // array for JSON response $response = array(); // include db connect class require_once __DIR__ . '/users_db_connect.php'; // connecting to db $db = new DB_CONNECT(); // get all products from products table $result = mysql_query("SELECT * FROM user") or die(mysql_error()); // check for empty result if (mysql_num_rows($result) &gt; 0) { // looping through all results // products node $response["user"] = array(); while ($row = mysql_fetch_array($result)) { // temp user array $product = array(); $product["username"] = $row["username"]; $product["password"] = $row["password"]; $product["publickey"] = $row["publickey"]; // push single product into final response array array_push($response["user"], $product); } // success $response["success"] = 1; // echoing JSON response echo json_encode($response); } else { // no products found $response["success"] = 0; $response["message"] = "No user found"; // echo no users JSON echo json_encode($response); } ?&gt;</code></pre> </div> </div> <p><strong>Logcat</strong></p> <p></p><div class="snippet" data-lang="js" data-hide="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>05-03 23:58:53.584: D/sid(26226): a 05-03 23:58:53.640: D/Login Details(26226): {"user":[{"username":"oBYxmonY0wmJhVbCZ69S\/OJYiVt7socheDmRfJM1vUyw1ACBA9ZraePdFJsvbYSjce\/UhxemRE+x RyF4d2GYLxfw+s0sw6Xo0P7T5bJ2gDqw7Grn+aAolhS4xzPnZm\/tytTVHVgyqdx\/UbWn8txu8h5D Vj8WmLa0IstgcmvHRtQ= ","password":"j\/iLoIjK5a1vJulTE4Hv7ofMQF48krK3xiDiBwGOJBsK7eGGnRskwjV+xUyT+jT3IeWQHbLncdWD eG9HrQKiM2kE+t5SQ6CkCXVTcfWg8\/axmQC+UQt\/Q3s81UC64AMVBB0J0\/cZrdGeAQ8bGGVDkwC2 f9WTl8RoAiMmpl6Q7gs= ","publickey":"MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCxZzks60BsVN6D\/2wJhXrURkzuDvljjEcN3hW6 4JbjxK4UJb5T0uVtzULvyfceHcySlhqo2AcP0s+EybPuaZ+dwI1Mhd7VYg1Xeyz5EvLStAOreY3G 3yweb4sryGvcty88Q4XkC\/KrcURGAT8QBzNVSc9cHJa+qPf1\/t+Eb9Yb3wIDAQAB "},{"username":"YjvJ6eNMNtU649ZgordslPURCNOt8ZgfkAm5WzNzlxxYZiYldAIg3PeOHjiOUsIunZuLlQ7\/uJG2 9GBCTRDbQJeqOJ\/YaFePEjuydEHyN7CAay4ocUklVQkTdgSLkTEtU+RFifqGs3fM67fyQD3w8xq6 yHb3vZMdJ3AS8cFS0fM= ","password":"fr+vrqHzYBgvuHAnaRpNb+V9I0hn9crCuHNabF0v\/8PAY3a11fnE9v924sUTcgh4BDJVSzp\/sSxQ L1i7noh45buKPrZEz6BfGgiGqpwbjXTLKIyuNFjIyA3qbBFs9rxhYS00AsKmKO+zoB5AZ+I4amQQ wa3QKC\/wtHjPtV7BfwY= ","publickey":"MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDG9gggL32xWWArvV2FClklGPGUZPpsHUavy+l7 GME2RwuI+nlARq9dM4TGyAY2A6APTj\/lD6\/uVfmvFvuo1MC2OSGBNNYNngoJ+J1Bg9kjwJUEktEF sO2L0iCTu0EQM+1SXlWe20k2sp4UmKdP0Rx3L8NqhbJLLoPLfA5qhCwNDQIDAQAB "}],"success":1} 05-03 23:58:53.640: D/usernameBlob:(26226): oBYxmonY0wmJhVbCZ69S/OJYiVt7socheDmRfJM1vUyw1ACBA9ZraePdFJsvbYSjce/UhxemRE+x 05-03 23:58:53.640: D/usernameBlob:(26226): RyF4d2GYLxfw+s0sw6Xo0P7T5bJ2gDqw7Grn+aAolhS4xzPnZm/tytTVHVgyqdx/UbWn8txu8h5D 05-03 23:58:53.640: D/usernameBlob:(26226): Vj8WmLa0IstgcmvHRtQ= 05-03 23:58:53.640: D/passwordBlob:(26226): j/iLoIjK5a1vJulTE4Hv7ofMQF48krK3xiDiBwGOJBsK7eGGnRskwjV+xUyT+jT3IeWQHbLncdWD 05-03 23:58:53.640: D/passwordBlob:(26226): eG9HrQKiM2kE+t5SQ6CkCXVTcfWg8/axmQC+UQt/Q3s81UC64AMVBB0J0/cZrdGeAQ8bGGVDkwC2 05-03 23:58:53.640: D/passwordBlob:(26226): f9WTl8RoAiMmpl6Q7gs= 05-03 23:58:53.640: D/publickeyBlob:(26226): MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCxZzks60BsVN6D/2wJhXrURkzuDvljjEcN3hW6 05-03 23:58:53.640: D/publickeyBlob:(26226): 4JbjxK4UJb5T0uVtzULvyfceHcySlhqo2AcP0s+EybPuaZ+dwI1Mhd7VYg1Xeyz5EvLStAOreY3G 05-03 23:58:53.640: D/publickeyBlob:(26226): 3yweb4sryGvcty88Q4XkC/KrcURGAT8QBzNVSc9cHJa+qPf1/t+Eb9Yb3wIDAQAB 05-03 23:58:53.641: D/Username:(26226): YzJsawo= 05-03 23:58:53.641: D/Password:(26226): YzJsawo= 05-03 23:58:53.641: D/usernameBlob:(26226): YjvJ6eNMNtU649ZgordslPURCNOt8ZgfkAm5WzNzlxxYZiYldAIg3PeOHjiOUsIunZuLlQ7/uJG2 05-03 23:58:53.641: D/usernameBlob:(26226): 9GBCTRDbQJeqOJ/YaFePEjuydEHyN7CAay4ocUklVQkTdgSLkTEtU+RFifqGs3fM67fyQD3w8xq6 05-03 23:58:53.641: D/usernameBlob:(26226): yHb3vZMdJ3AS8cFS0fM= 05-03 23:58:53.641: D/passwordBlob:(26226): fr+vrqHzYBgvuHAnaRpNb+V9I0hn9crCuHNabF0v/8PAY3a11fnE9v924sUTcgh4BDJVSzp/sSxQ 05-03 23:58:53.641: D/passwordBlob:(26226): L1i7noh45buKPrZEz6BfGgiGqpwbjXTLKIyuNFjIyA3qbBFs9rxhYS00AsKmKO+zoB5AZ+I4amQQ 05-03 23:58:53.641: D/passwordBlob:(26226): wa3QKC/wtHjPtV7BfwY= 05-03 23:58:53.641: D/publickeyBlob:(26226): MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDG9gggL32xWWArvV2FClklGPGUZPpsHUavy+l7 05-03 23:58:53.641: D/publickeyBlob:(26226): GME2RwuI+nlARq9dM4TGyAY2A6APTj/lD6/uVfmvFvuo1MC2OSGBNNYNngoJ+J1Bg9kjwJUEktEF 05-03 23:58:53.641: D/publickeyBlob:(26226): sO2L0iCTu0EQM+1SXlWe20k2sp4UmKdP0Rx3L8NqhbJLLoPLfA5qhCwNDQIDAQAB 05-03 23:58:53.647: D/Username:(26226): YzJsawo= 05-03 23:58:53.647: D/Password:(26226): YzJsawo=</code></pre> </div> </div> </div>

以下Android AES解密 怎么在iOS里实现

以下是Android 里面的AES解密方法,有谁能在iOS里面实现的,非常感谢 public static String decrypt(String content, String key) { //反序列化AES密钥 SecretKeySpec keySpec = new SecretKeySpec(Base64.decodeBase64(key.getBytes()), "AES"); //128bit全零的IV向量 byte[] iv = new byte[16]; for (int i = 0; i < iv.length; i++) { iv[i] = 0; } IvParameterSpec ivParameterSpec = new IvParameterSpec(iv); try { Cipher deCipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); deCipher.init(Cipher.DECRYPT_MODE, keySpec, ivParameterSpec); byte[] encryptedBytes = Base64.decodeBase64(content.getBytes()); byte[] bytes = deCipher.doFinal(encryptedBytes); return new String(bytes); } catch (Exception e) { return ""; } }

rsa加密解密功能实现方法

使用java写个RSA加解密的方法来实现用户登录时密码加密功能

RSA加密时有填充,如何在已知明文范围,填充方法和密文时,找到明文?

问题的具体描述如下: RSA加密 (c = (PIN)^e mod N)。假设PIN是一个小于2^16正整数,在直接加密前,先把PIN转化为二进制,然后在最右边加上2048个1。比如,十六进制整数abcd变成二进制整数x=1010101111001101 1...1(2048个1),然后再将x代入求出密文。已知N,e,c和填充方法,就是说全部都知道,就是不知道密钥d和明文m,现在需要寻找一种有效的攻击方法来找出明文。本人对这方面是刚入门的级别,想了两天只想出穷举法作为最有效的攻击因为PIN是一个小于2^16正整数。但是题目的要求是要具体算出明文的数值,在给定了N,e和c具体数值的前提下。若有大神能给我解答,必将感激不尽!找不到RSA的标签。。只好随便选了一个

android客户端和js服务端RSA加密解密

android客户端利用js服务端的公钥加密数据再发给js服务端解密,可是js客户端总返回给我解密失败,找不到问题在哪,求大神指教!!!

RSA OAEP,Golang解密,Java加密

<div class="post-text" itemprop="text"> <p>The Android client encrypt message, the java code </p> <pre><code>Cipher cipher = Cipher.getInstance("RSA/ECB/OAEPWITHSHA-256ANDMGF1PADDING"); byte[] publicBytes = Base64.decode(Configs.PUBLIC_KEY.getBytes("UTF-8"),Base64.DEFAULT); X509EncodedKeySpec keySpec = new X509EncodedKeySpec(publicBytes); KeyFactory keyFactory = KeyFactory.getInstance("RSA"); PublicKey pubKey = keyFactory.generatePublic(keySpec); cipher.init(Cipher.ENCRYPT_MODE, pubKey); String plaintext = "test"; byte[] encryptedBytes = cipher.doFinal(plaintext.getBytes("UTF-8")); String chipertext = Base64.encodeToString(encryptedBytes,Base64.DEFAULT); Log.d(TAG,"encrypted (chipertext) = " + chipertext); </code></pre> <p>The Golang server decrypt message, the golang code </p> <pre><code>func RsaDecrypt(encryptedString string) (string, error) { base64DecodeBytes, err := base64.StdEncoding.DecodeString(encryptedString) if err != nil { return "", err } privateKeyBlock, _ := pem.Decode([]byte(privateKey)) var pri *rsa.PrivateKey pri, parseErr := x509.ParsePKCS1PrivateKey(privateKeyBlock.Bytes) if parseErr != nil { return "", parseErr } decryptedData, decryptErr := rsa.DecryptOAEP(sha1.New(), rand.Reader, pri, base64DecodeBytes, nil) if decryptErr != nil { return "", decryptErr } return string(decryptedData), nil } </code></pre> <p>and the error in golang : <code>crypto/rsa: decryption error</code> </p> <p>I can't change the code on the server, so how to change the code in Java?</p> <p>Need your help</p> <p>Thx.</p> </div>

JAVA和IOS对接RSA加密问题

公司开发IOS APP,跟JAVA后台对接。在加密方面,使用的是RSA。在JAVA端生成的公钥和私钥,通过BASE64转成字符串。然后在IOS端,如果直接拿着这个转化的字符串密钥(通过BASE64解密后)去做RSA加密的话,这边JAVA端解密会失败。所以,请问下,在密钥方面应该怎么处理呢?JAVA端生成的密钥怎样处理给到IOS端才会成功?谢谢!

RSA加解密问题求教,已知公钥的模和指数

遇到个问题,请教下大家 后台下发下来公钥的模和指数,前端怎样通过公钥的模和指数合成一个公钥来加密一组32位的随机数

PHP RSA加密字符串的Android设备解密失败,解密结果不正确

<div class="post-text" itemprop="text"> <p>The code that encrypts a string PHP-serverside. I use the PKCS8 and not PKCS1 so that I can unencrypt on Android side.</p> <p>The code for the Encryption follows: I use the phpseclib.</p> <pre><code>include('libs/PHPSecLib/Crypt/RSA.php'); </code></pre> <p>...code to lookup public and private keys stored in database omitted...</p> <pre><code>$rsa = new Crypt_RSA(); $rsa-&gt;loadKey($row['pref_pub_key']); // public key stored in MySQL BLOB. $plaintext = 'Testing 123'; $rsa-&gt;setEncryptionMode(CRYPT_RSA_ENCRYPTION_PKCS8); //USE PKCS8 $ciphertext = $rsa-&gt;encrypt($plaintext); echo $ciphertext; $rsa-&gt;loadKey($row['pref_priv_key']); // private key stored in MySQL BLOB echo $rsa-&gt;decrypt($ciphertext); $query = "UPDATE preferences SET pref_license = ?; //execute query to store the encrypted text in pref_license BLOB field. try { $stmt = $db-&gt;prepare($query); $stmt-&gt;bindParam(1,$ciphertext); $stmt-&gt;bindParam(2,$ref); $db-&gt;errorInfo(); $result = $stmt-&gt;execute(); } catch (PDOException $ex) { $response["success"] = 0; $response["message"] = "Database Error. Couldn't update Pref post with License!" . $ex-&gt;getMessage(); echo $response["message"]; die(json_encode($response)); } </code></pre> <p>I basically encrypt the string, and store it in a BLOB field, for later reference.</p> <p>I generate the Private Public KEYPAIR and store in BLOB in the following manner, and send the privatekey to the Android device:</p> <pre><code>include('libs/PHPSecLib/Crypt/RSA.php'); $rsa = new Crypt_RSA(); $rsa-&gt;setPrivateKeyFormat(CRYPT_RSA_PRIVATE_FORMAT_PKCS8); $rsa-&gt;setPublicKeyFormat(CRYPT_RSA_PUBLIC_FORMAT_PKCS8); extract($rsa-&gt;createKey()); //echo $privatekey . '&lt;br/&gt;&lt;br/&gt;' . $publickey; //I can see that it worked! if (!empty($_POST)) { //initial update query to store the keys in BLOBS on SERVER MYSQL $query = "UPDATE preferences SET pref_priv_key = ?, pref_pub_key = ? WHERE pref_device_serial = ?"; //execute query try { $stmt = $db-&gt;prepare($query); $stmt-&gt;bindParam(1,$privatekey); $stmt-&gt;bindParam(2,$publickey); $stmt-&gt;bindParam(3,$_POST['p_device_serial']); $db-&gt;errorInfo(); $result = $stmt-&gt;execute(); } catch (PDOException $ex) { $response["success"] = 0; $response["message"] = "Database Error. Couldn't update Pref post!" . $ex-&gt;getMessage(); die(json_encode($response)); } } //then I send the $privatekey to the Android device and save it there. //to then later decrypt the serverside encrypted string. $response["success"] = 1; $response["pk"] = $privatekey; $response["message"] = "Key Pair successfully generated."; echo json_encode($response); </code></pre> <p>On the Android device, I use ans AsyncTask to request the Encrypted String and then read the PrivateKey from the local sqlite blob field, and try and decrypt the string:</p> <pre><code> class GetLicense extends AsyncTask&lt;String, String, String&gt; { @Override protected void onPreExecute() { super.onPreExecute(); pDialog = new ProgressDialog(LicenseActivity.this); pDialog.setMessage("Retrieving License Data..."); pDialog.setIndeterminate(false); pDialog.setCancelable(true); pDialog.show(); } @Override protected String doInBackground(String... args) { int success; String elicense; try { getPref = LicenseActivity.this.openOrCreateDatabase("aaa.db", Context.MODE_PRIVATE, null); Cursor c = getPref.rawQuery("SELECT * FROM preferences", null); Log.d("request!", "starting"); if (c != null) { if (c.moveToFirst()) { do { String Preferences_Id = c.getString(c.getColumnIndex(SupaAttendDb.KEY_ROWID)); String Preferences_UUID = c.getString(c.getColumnIndex(SupaAttendDb.KEY_Preferences_PREFUUID)); String Preferences_Device_Serial = c.getString(c.getColumnIndex(SupaAttendDb.KEY_Preferences_PREFDEVICESERIAL)); sPK = c.getString(c.getColumnIndex(SupaAttendDb.KEY_Preferences_PREFPK)); // Building Parameters List&lt;NameValuePair&gt; params = new ArrayList&lt;NameValuePair&gt;(); params.add(new BasicNameValuePair("p_uuid", Preferences_UUID)); try { //Get Encrypted License from server JSONObject json = jsonParser.makeHttpRequest( GET_LICENSE_URL, "POST", params); // full json response // json success element success = json.getInt(TAG_SUCCESS); if (success == 1) { sData = json.getString(TAG_LICENSE); </code></pre> <p>..then I save the the license to Android SQLite. code not required ... In the onPostExecute, I format the PrivateKey and then try to decrypt the sData, but get the incorrect data back, and not 'Testing 123'.</p> <pre><code> protected void onPostExecute(String file_url) { pDialog.dismiss(); String privKeyPEM = sPK.replace("-----BEGIN PRIVATE KEY----- ", ""); privKeyPEM = privKeyPEM.replace("-----END PRIVATE KEY-----", ""); byte[] b = Base64.decode(privKeyPEM,Base64.DEFAULT); KeyFactory keyFactory = null; try { keyFactory = KeyFactory.getInstance("RSA"); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } EncodedKeySpec privateKeySpec = new PKCS8EncodedKeySpec(b); //This decodes properly without any exceptions. PrivateKey privateKey2 = null; try { privateKey2 = keyFactory.generatePrivate(privateKeySpec); } catch (InvalidKeySpecException e) { e.printStackTrace(); } byte[] decryptedData = null; Cipher cipher = null; try { cipher = Cipher.getInstance("RSA"); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (NoSuchPaddingException e) { e.printStackTrace(); } try { cipher.init(Cipher.DECRYPT_MODE,privateKey2); } catch (InvalidKeyException e) { e.printStackTrace(); } byte[] sD = Base64.decode(sData, Base64.DEFAULT);// Here I try to get the encrypted string retrieved from server into a byte[]. try { decryptedData = cipher.doFinal(sD); // no errors, but I get the incorrect unencrypted string. } catch (IllegalBlockSizeException e) { e.printStackTrace(); } catch (BadPaddingException e) { e.printStackTrace(); } if (decryptedData != null){ String decrypted = new String(decryptedData); //decryptedData = Base64.encode(decryptedData,Base64.DEFAULT); Toast.makeText(LicenseActivity.this, decrypted, Toast.LENGTH_LONG).show(); } } } </code></pre> <p>I realise I'm just doing something stupid in this last bit of code where I try and decode the Encrypted string, and then decrypt it. Hope you can point me in the correct direction, and sorry for being long winded.</p> <p>Oh and yes, before you ask, I retrieve the license from the server with the following PHP:</p> <pre><code>require("config.inc.php"); if (!empty($_POST)) { //initial query $query = "SELECT pref_uuid, pref_license, pref_device_serial FROM preferences WHERE pref_uuid = :p_uuid"; $query_params = array(':p_uuid' =&gt; $_POST['p_uuid']); //execute query try { $stmt = $db-&gt;prepare($query); $db-&gt;errorInfo(); $result = $stmt-&gt;execute($query_params); } catch (PDOException $ex) { $response["success"] = 0; $response["message"] = "Database Error. Couldn't retrieve License details!" . $ex-&gt;getMessage(); die(json_encode($response)); } if(!$result) { $response["success"] = 0; $response["message"] = "Database Error. Couldn't return Licenses!" . $ex-&gt;getMessage(); die(json_encode($response)); } $row = $stmt-&gt;fetch(PDO::FETCH_ASSOC); $response["license"] = base64_encode($row['pref_license']); // I encode it here before I send the encrypted string off to android device. $response["message"] = "License Record successfully retrieved"; $response["success"] = 1; echo json_encode($response); } </code></pre> </div>

用RSA加密方式加密后的密文太长

最近在搞License,用RSA对其加密后感觉加密后的字符串太长 如果想让其长度固定8位 或16位 怎么做?请各位前辈指导指导,谢谢啦

rsa在jni中使用进行加密

有谁知道适合在jni中调用的rsa算法源码么,需要我手动设置自己想要设置的秘钥, 或者谁有集成好的静态库,帮帮忙,给我一份谢啦

为什么解密返回会出现部分乱码!!!!!!

这个是一个查询接口的返回信息。为什么其他部分的内容都可以显示,可是名字却是无法解析,是一堆的问号!!!,然后界面上显示的也是乱码的![图片说明](https://img-ask.csdn.net/upload/201704/18/1492481659_245355.png)![图片说明](https://img-ask.csdn.net/upload/201704/18/1492481839_586100.png)

关于java自带RSA密钥包生成的私钥公钥加密不了,求大神帮忙看一下

我用JAVA生成了一个公钥如下: System.out.println(publicKey.getPublicKey()); 输出:modulus:154308594144468705348294760484396264219304223307125368116140288659005422830 11489867478404495635728307309845313276126541903154766024976823588585215138754477992 96802915396931308077347778973425837411602815233405546695183536389616670156153124753 50767041053961957188628650343640790505255765999004862716823611888529 public exponent: 65537 用这个modulus的值加密不了,我看网上的公钥都是这样子的<RSAKeyValue><Modulus>5q4F3crOuN4OG68Dko7EZl5wYn+FokohvMm6m/NFmMJIGBhYnJ9/8JKQMxndka8GafQ9BU/LASFtvbrfNsyA6TfP2wMalewfWF0GBT5AviGouGqt9I9BMrvBfTttU5OMqD2rF+fQ23WMTi+UYzY/9kZB7Rys7A1oIFWnsnB0Jnc=</Modulus><Exponent>AQAB</Exponent></RSAKeyValue> 请问这个modulus是不是要转换一下 怎么转换呢?有没懂的大神帮下忙

java RSA 加密 密钥怎么是这样???请求大神

如题:我使用java 进行rsa加密和解密,以前的密钥是这样的 ``` -----BEGIN RSA PRIVATE KEY----- MIICYAIBAAKBgQCFBCOuc0ADomD/ZIyUHFlzwbmbZQm+/NFC3vXJZpiuyCyU79GS +9igHN18NBJY2zPacdN0BR/Zw8zb5QEXncbx5bUMxrdut5cn540Z5EKCGXamEGNa YQqJOFdwLZ+MdpRhF9+LuBEJLShDHkqWOYxL9B9ChFusL6ffilJHovt1vQIDAQAB AoGBAIR/IA/Ia25zU81yWfm613vP79OTbIbbDJNgxlHMqbAIYygkTozr4tdyiUkM EW6DQv6IPYonBJgFSs2LKeaO2r78qYX7HS+d/FIHOItiYmn+/TVg4K31gvHDTR3h wHZYYj82DzLHzE6XUYi1Rskp/j7hLH9G6j9lvkC0LfCONYH9AkUAilhNcAXuo34/ 5mkJpARzYVh0z1yoIYLopgGnu+bZ9DKnJOFw7vgkW/ht9F1iDXtNyGNFNSvUR+4u +3ZLzUx/nCkWDWMCPQD2I7AnzI3xUrNtXmdmPVBu1rdnksvzlnB1Fq61UtZCl8lF l0wf8v/Mwoo+8cwIU76SZ7qotyOk8zMw6l8CRAwkY+eJHcDLu+AFKAt1OIs6sEXi 4/7M9o5bZtVfFZIRQApEnxzaOpa33y6rY4e7YsBLti9MgX0usoDviQejxy91i7Hx AjxbD7z+HGlvHH+RONncM1bsirdztBWMWt3kE64zGyB1pp4qBt18/HOyl056Fw67 DfB1Tbb68DZZsjgAItUCRGf3HjhNJ7Ds1vkxr/4TSpPrwtzdyRDL9rfMpPsMtxIx VIlm/QMhuocPa1n/X4sj7zr7lIO9hJQatH+o8H+k/RdU9C1U -----END RSA PRIVATE KEY----- -----BEGIN RSA PUBLIC KEY----- MIGJAoGBAIUEI65zQAOiYP9kjJQcWXPBuZtlCb780ULe9clmmK7ILJTv0ZL72KAc 3Xw0EljbM9px03QFH9nDzNvlARedxvHltQzGt263lyfnjRnkQoIZdqYQY1phCok4 V3Atn4x2lGEX34u4EQktKEMeSpY5jEv0H0KEW6wvp9+KUkei+3W9AgMBAAE= -----END RSA PUBLIC KEY----- ``` 可是java生成的密钥是这样的 ``` Public: Sun RSA public key, 1024 bits modulus: 115167042676305858738847186533249405669862094235824050170829472846838184071198269677735802427559009406378408679122716231466842633032672638784932362501517832025002317128732500267361048428339476135327496604377557607368863315349176457827649815598420261325717980373017826912041724701533957365472698961283209962067 public exponent: 65537 Private: sun.security.rsa.RSAPrivateCrtKeyImpl@7fb47 ``` 密钥如果不正常,我就不能在其他平台使用密钥进行解密,请求大神!!!

RSA加密问题

RSA用512为公钥加密,一次只能加密32个byte,返回64个byte,,数据翻倍了。 512的私钥解密,一次需要64byte,, 第一个是数据翻倍了,第二个是我有320个byte需要加密10次,,

Golang中的java RSA / ECB / OAEPWithSHA 256AndMGF1Padding等效项

<div class="post-text" itemprop="text"> <p>I'm trying to migrate some java encryption code into golang and came across this </p> <pre><code>Cipher cipher = Cipher.getInstance(RSA_ECB_OAEPWithSHA256AndMGF1Padding); cipher.init(Cipher.WRAP_MODE, cert); return cipher.wrap(key); </code></pre> <p>I'm trying to find any implementation of this in go. Any help would be appreciated. Thanks.</p> </div>

使用Phpseclib在Java中加密并在PHP中解密

<div class="post-text" itemprop="text"> <p><strong>Edit 2:</strong> Problem has been solved. I didn't understand how the loadkey function in php was supposed to work and I mistakenly assumed it would read a key file (it does not). The solution was to read the contents of the file into a variable and then load the variable with loadkey. </p> <p><strong>Edit:</strong> The problem seems to be with the key. I realized that loadkey is returning false, indicating that it was unable to read the key. Could there be a difference in the formats accepted by phpseclib and the keys created in java?</p> <hr> <p>I am trying to encrypt a AES key in Java (android) and decrypt it in PHP to use symmetric encryption for data transfer. Currently, I am able to encrypt and decrypt a short file or string using RSA in Java, but have not been able to decrypt it in PHP.</p> <p>I am using phpseclib to decrypt in PHP, and i dont get any error, but my output string is null. </p> <p>This is the code I am using: </p> <p><strong>Java:</strong> </p> <pre><code>File archivo_llave_publica = new File(direccion); byte[] bytes_llave = leer(archivo_llave_publica); KeyFactory keyFactory = KeyFactory.getInstance("RSA"); EncodedKeySpec publicKeySpec = new X509EncodedKeySpec(bytes_llave); PublicKey pubKey = keyFactory.generatePublic(publicKeySpec); Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding"); cipher.init(Cipher.ENCRYPT_MODE, pubKey); byte[] cipherData = cipher.doFinal(src); return cipherData; </code></pre> <p><strong>PHP:</strong></p> <pre><code>&lt;?php include('./Crypt/RSA.php'); $rsa = new Crypt_RSA(); $rsa-&gt;setEncryptionMode(CRYPT_RSA_ENCRYPTION_PKCS1); $rsa-&gt;loadKey('./key/Pri.txt'); // public key $temprsa = $rsa-&gt;decrypt($key); if ($temprsa==null){echo "null decrypt";} </code></pre> <hr> <p>Code used to generate keys:</p> <pre><code>public void generaArchivoLlaves(String pub_file, String pri_file){ File LlavePrivada = new File(raiz.getAbsolutePath()+"/Bushfire/"+pri_file); File LlavePublica = new File(raiz.getAbsolutePath()+"/Bushfire/"+pub_file); try { KeyPair kp = generaLlaves(); byte[] privateKeyBytes = kp.getPrivate().getEncoded(); byte[] publicKeyBytes = kp.getPublic().getEncoded(); Toast.makeText(this, "Privada: "+kp.getPrivate().getFormat(), Toast.LENGTH_LONG).show(); Toast.makeText(this, "Pública: "+kp.getPublic().getFormat(), Toast.LENGTH_LONG).show(); escribir(LlavePrivada, privateKeyBytes); escribir(LlavePublica, publicKeyBytes); } catch (NoSuchAlgorithmException e) {Toast.makeText(this, "Error al generar llave", Toast.LENGTH_LONG).show();} } public KeyPair generaLlaves() throws NoSuchAlgorithmException{ KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA"); kpg.initialize(2048); KeyPair kp = kpg.genKeyPair(); //Toast.makeText(this, "Se generó correctamente", Toast.LENGTH_LONG).show(); return kp; </code></pre> <p>}</p> <p><strong>NOTE</strong>: Function escribir just writes the data byte by byte to a file. </p> <p>What could be causing the problem?</p> </div>

c++ openssl库解密问题

服务器给出的是加密后的信息、公模、指数,现在需要解密。 加密后的信息:6F07A0FF53393F619558DBD2E3EE16BC74F009D4661DB49D25A02E900EDAE56A02C142B07408E06C11E66025A42F9875ACF5FA6E5753FA5E3BF322E7284DBF1ADDB1E8F04C6FB3FBF32EA87838A6907E2A0A329B7AA1F3FC238B3B62B73C7C1AF954ED72C840CCBC49EB2538E8EA7A55C8A30A0764E2D95F59DF91D5BA6E7212 模: 93699723240557642714298223752328168207006127117803470313269635629012817131034121107145129394983372480532303750498616664968561285851237790153779524806068201674946146616076995235171678387337669517216870663016805090450941855464370990772124971064613523571889080169553919406043381049541688440844350694063503328143 指数: 52751041223791366488956578170589134293081741094930754240786067048660404059792711481594010927526534797774079972815309832166257796401533019599826805426624527321616158832674775347472860942794678504268163882233141437031764733191695179159757852053450055046188533293005499003752385892369582823636950131897518571777 解密后应为:正常的数字 服务器端代码如下: public class RSAUtils { /** * 生成公钥和私钥 * @throws NoSuchAlgorithmException * */ public static HashMap<String, Object> getKeys() throws NoSuchAlgorithmException{ HashMap<String, Object> map = new HashMap<String, Object>(); KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance("RSA"); keyPairGen.initialize(1024); KeyPair keyPair = keyPairGen.generateKeyPair(); RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic(); RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate(); map.put("public", publicKey); map.put("private", privateKey); return map; } /** * 使用模和指数生成RSA公钥 * 注意:【此代码用了默认补位方式,为RSA/None/PKCS1Padding,不同JDK默认的补位方式可能不同,如Android默认是RSA * /None/NoPadding】 * * @param modulus * 模 * @param exponent * 指数 * @return */ public static RSAPublicKey getPublicKey(String modulus, String exponent) { try { BigInteger b1 = new BigInteger(modulus); BigInteger b2 = new BigInteger(exponent); KeyFactory keyFactory = KeyFactory.getInstance("RSA"); RSAPublicKeySpec keySpec = new RSAPublicKeySpec(b1, b2); return (RSAPublicKey) keyFactory.generatePublic(keySpec); } catch (Exception e) { e.printStackTrace(); return null; } } /** * 使用模和指数生成RSA私钥 * 注意:【此代码用了默认补位方式,为RSA/None/PKCS1Padding,不同JDK默认的补位方式可能不同,如Android默认是RSA * /None/NoPadding】 * * @param modulus * 模 * @param exponent * 指数 * @return */ public static RSAPrivateKey getPrivateKey(String modulus, String exponent) { try { BigInteger b1 = new BigInteger(modulus); BigInteger b2 = new BigInteger(exponent); KeyFactory keyFactory = KeyFactory.getInstance("RSA"); RSAPrivateKeySpec keySpec = new RSAPrivateKeySpec(b1, b2); return (RSAPrivateKey) keyFactory.generatePrivate(keySpec); } catch (Exception e) { e.printStackTrace(); return null; } } /** * 公钥加密 * * @param data * @param publicKey * @return * @throws Exception */ public static String encryptByPublicKey(String data, RSAPublicKey publicKey) throws Exception { Cipher cipher = Cipher.getInstance("RSA"); cipher.init(Cipher.ENCRYPT_MODE, publicKey); // 模长 int key_len = publicKey.getModulus().bitLength() / 8; // 加密数据长度 <= 模长-11 String[] datas = splitString(data, key_len - 11); String mi = ""; //如果明文长度大于模长-11则要分组加密 for (String s : datas) { mi += bcd2Str(cipher.doFinal(s.getBytes("UTF-8"))); } return mi; } /** * 私钥解密 * * @param data * @param privateKey * @return * @throws Exception */ public static String decryptByPrivateKey(String data, RSAPrivateKey privateKey) throws Exception { Cipher cipher = Cipher.getInstance("RSA"); cipher.init(Cipher.DECRYPT_MODE, privateKey); //模长 int key_len = privateKey.getModulus().bitLength() / 8; byte[] bytes = data.getBytes("UTF-8"); byte[] bcd = ASCII_To_BCD(bytes, bytes.length); System.err.println(bcd.length); //如果密文长度大于模长则要分组解密 String ming = ""; byte[][] arrays = splitArray(bcd, key_len); for(byte[] arr : arrays){ ming += new String(cipher.doFinal(arr)); } return ming; } /** * ASCII码转BCD码 * */ public static byte[] ASCII_To_BCD(byte[] ascii, int asc_len) { byte[] bcd = new byte[asc_len / 2]; int j = 0; for (int i = 0; i < (asc_len + 1) / 2; i++) { bcd[i] = asc_to_bcd(ascii[j++]); bcd[i] = (byte) (((j >= asc_len) ? 0x00 : asc_to_bcd(ascii[j++])) + (bcd[i] << 4)); } return bcd; } public static byte asc_to_bcd(byte asc) { byte bcd; if ((asc >= '0') && (asc <= '9')) bcd = (byte) (asc - '0'); else if ((asc >= 'A') && (asc <= 'F')) bcd = (byte) (asc - 'A' + 10); else if ((asc >= 'a') && (asc <= 'f')) bcd = (byte) (asc - 'a' + 10); else bcd = (byte) (asc - 48); return bcd; } /** * BCD转字符串 */ public static String bcd2Str(byte[] bytes) { char temp[] = new char[bytes.length * 2], val; for (int i = 0; i < bytes.length; i++) { val = (char) (((bytes[i] & 0xf0) >> 4) & 0x0f); temp[i * 2] = (char) (val > 9 ? val + 'A' - 10 : val + '0'); val = (char) (bytes[i] & 0x0f); temp[i * 2 + 1] = (char) (val > 9 ? val + 'A' - 10 : val + '0'); } return new String(temp); } /** * 拆分字符串 */ public static String[] splitString(String string, int len) { int x = string.length() / len; int y = string.length() % len; int z = 0; if (y != 0) { z = 1; } String[] strings = new String[x + z]; String str = ""; for (int i=0; i<x+z; i++) { if (i==x+z-1 && y!=0) { str = string.substring(i*len, i*len+y); }else{ str = string.substring(i*len, i*len+len); } strings[i] = str; } return strings; } /** *拆分数组 */ public static byte[][] splitArray(byte[] data,int len){ int x = data.length / len; int y = data.length % len; int z = 0; if(y!=0){ z = 1; } byte[][] arrays = new byte[x+z][]; byte[] arr; for(int i=0; i<x+z; i++){ arr = new byte[len]; if(i==x+z-1 && y!=0){ System.arraycopy(data, i*len, arr, 0, y); }else{ System.arraycopy(data, i*len, arr, 0, len); } arrays[i] = arr; } return arrays; } public static void main(String[] args) throws Exception { //加密 String sysRsaPublicExponent = "65537"; //sys 公钥指数 String sysRsaModulus = "120638465331515039018602766102898243545817108824248108758756045538044335002008114706331728819795590465631377302362547268746636029891250" + "449814559223888056676854984963129330873452309930246829596744979895825527218697094609496436664015271970577401170500785252151278453045409127914743768611747170785074707487690419"; //sys 模 RSAPublicKey publickey = RSAUtils.getPublicKey(sysRsaModulus, sysRsaPublicExponent); String msg = RSAUtils.encryptByPublicKey("公钥加密",publickey); System.out.println("加密后:"+msg); //解密 String sysRsaPrivateExponent = "69691507048707743370070353001445404895625917269420837047873779453901742880754798400624368724803714772247798108968155997295384898479984467247191849129527212787744749050" + "17092964178282019340128383046059793475544308917861326270601739489293981014213604544197641773445405470949453568565300025014058699812509971313"; //sys 私钥指数 RSAPrivateKey privateKey = RSAUtils.getPrivateKey(sysRsaModulus, sysRsaPrivateExponent); msg = RSAUtils.decryptByPrivateKey(msg,privateKey); System.out.println("解密后:"+msg); } }

大学四年自学走来,这些私藏的实用工具/学习网站我贡献出来了

大学四年,看课本是不可能一直看课本的了,对于学习,特别是自学,善于搜索网上的一些资源来辅助,还是非常有必要的,下面我就把这几年私藏的各种资源,网站贡献出来给你们。主要有:电子书搜索、实用工具、在线视频学习网站、非视频学习网站、软件下载、面试/求职必备网站。 注意:文中提到的所有资源,文末我都给你整理好了,你们只管拿去,如果觉得不错,转发、分享就是最大的支持了。 一、电子书搜索 对于大部分程序员...

在中国程序员是青春饭吗?

今年,我也32了 ,为了不给大家误导,咨询了猎头、圈内好友,以及年过35岁的几位老程序员……舍了老脸去揭人家伤疤……希望能给大家以帮助,记得帮我点赞哦。 目录: 你以为的人生 一次又一次的伤害 猎头界的真相 如何应对互联网行业的「中年危机」 一、你以为的人生 刚入行时,拿着傲人的工资,想着好好干,以为我们的人生是这样的: 等真到了那一天,你会发现,你的人生很可能是这样的: ...

springboot+jwt实现token登陆权限认证

一 前言 此篇文章的内容也是学习不久,终于到周末有时间码一篇文章分享知识追寻者的粉丝们,学完本篇文章,读者将对token类的登陆认证流程有个全面的了解,可以动态搭建自己的登陆认证过程;对小项目而已是个轻量级的认证机制,符合开发需求;更多精彩原创内容关注公主号知识追寻者,读者的肯定,就是对作者的创作的最大支持; 二 jwt实现登陆认证流程 用户使用账号和面发出post请求 服务器接受到请求后使用私...

技术大佬:我去,你写的 switch 语句也太老土了吧

昨天早上通过远程的方式 review 了两名新来同事的代码,大部分代码都写得很漂亮,严谨的同时注释也很到位,这令我非常满意。但当我看到他们当中有一个人写的 switch 语句时,还是忍不住破口大骂:“我擦,小王,你丫写的 switch 语句也太老土了吧!” 来看看小王写的代码吧,看完不要骂我装逼啊。 private static String createPlayer(PlayerTypes p...

女程序员,为什么比男程序员少???

昨天看到一档综艺节目,讨论了两个话题:(1)中国学生的数学成绩,平均下来看,会比国外好?为什么?(2)男生的数学成绩,平均下来看,会比女生好?为什么?同时,我又联想到了一个技术圈经常讨...

总结了 150 余个神奇网站,你不来瞅瞅吗?

原博客再更新,可能就没了,之后将持续更新本篇博客。

副业收入是我做程序媛的3倍,工作外的B面人生是怎样的?

提到“程序员”,多数人脑海里首先想到的大约是:为人木讷、薪水超高、工作枯燥…… 然而,当离开工作岗位,撕去层层标签,脱下“程序员”这身外套,有的人生动又有趣,马上展现出了完全不同的A/B面人生! 不论是简单的爱好,还是正经的副业,他们都干得同样出色。偶尔,还能和程序员的特质结合,产生奇妙的“化学反应”。 @Charlotte:平日素颜示人,周末美妆博主 大家都以为程序媛也个个不修边幅,但我们也许...

MySQL数据库面试题(2020最新版)

文章目录数据库基础知识为什么要使用数据库什么是SQL?什么是MySQL?数据库三大范式是什么mysql有关权限的表都有哪几个MySQL的binlog有有几种录入格式?分别有什么区别?数据类型mysql有哪些数据类型引擎MySQL存储引擎MyISAM与InnoDB区别MyISAM索引与InnoDB索引的区别?InnoDB引擎的4大特性存储引擎选择索引什么是索引?索引有哪些优缺点?索引使用场景(重点)...

如果你是老板,你会不会踢了这样的员工?

有个好朋友ZS,是技术总监,昨天问我:“有一个老下属,跟了我很多年,做事勤勤恳恳,主动性也很好。但随着公司的发展,他的进步速度,跟不上团队的步伐了,有点...

我入职阿里后,才知道原来简历这么写

私下里,有不少读者问我:“二哥,如何才能写出一份专业的技术简历呢?我总感觉自己写的简历太烂了,所以投了无数份,都石沉大海了。”说实话,我自己好多年没有写过简历了,但我认识的一个同行,他在阿里,给我说了一些他当年写简历的方法论,我感觉太牛逼了,实在是忍不住,就分享了出来,希望能够帮助到你。 01、简历的本质 作为简历的撰写者,你必须要搞清楚一点,简历的本质是什么,它就是为了来销售你的价值主张的。往深...

程序员写出这样的代码,能不挨骂吗?

当你换槽填坑时,面对一个新的环境。能够快速熟练,上手实现业务需求是关键。但是,哪些因素会影响你快速上手呢?是原有代码写的不够好?还是注释写的不够好?昨夜...

外包程序员的幸福生活

今天给你们讲述一个外包程序员的幸福生活。男主是Z哥,不是在外包公司上班的那种,是一名自由职业者,接外包项目自己干。接下来讲的都是真人真事。 先给大家介绍一下男主,Z哥,老程序员,是我十多年前的老同事,技术大牛,当过CTO,也创过业。因为我俩都爱好喝酒、踢球,再加上住的距离不算远,所以一直也断断续续的联系着,我对Z哥的状况也有大概了解。 Z哥几年前创业失败,后来他开始干起了外包,利用自己的技术能...

优雅的替换if-else语句

场景 日常开发,if-else语句写的不少吧??当逻辑分支非常多的时候,if-else套了一层又一层,虽然业务功能倒是实现了,但是看起来是真的很不优雅,尤其是对于我这种有强迫症的程序"猿",看到这么多if-else,脑袋瓜子就嗡嗡的,总想着解锁新姿势:干掉过多的if-else!!!本文将介绍三板斧手段: 优先判断条件,条件不满足的,逻辑及时中断返回; 采用策略模式+工厂模式; 结合注解,锦...

离职半年了,老东家又发 offer,回不回?

有小伙伴问松哥这个问题,他在上海某公司,在离职了几个月后,前公司的领导联系到他,希望他能够返聘回去,他很纠结要不要回去? 俗话说好马不吃回头草,但是这个小伙伴既然感到纠结了,我觉得至少说明了两个问题:1.曾经的公司还不错;2.现在的日子也不是很如意。否则应该就不会纠结了。 老实说,松哥之前也有过类似的经历,今天就来和小伙伴们聊聊回头草到底吃不吃。 首先一个基本观点,就是离职了也没必要和老东家弄的苦...

2020阿里全球数学大赛:3万名高手、4道题、2天2夜未交卷

阿里巴巴全球数学竞赛( Alibaba Global Mathematics Competition)由马云发起,由中国科学技术协会、阿里巴巴基金会、阿里巴巴达摩院共同举办。大赛不设报名门槛,全世界爱好数学的人都可参与,不论是否出身数学专业、是否投身数学研究。 2020年阿里巴巴达摩院邀请北京大学、剑桥大学、浙江大学等高校的顶尖数学教师组建了出题组。中科院院士、美国艺术与科学院院士、北京国际数学...

为什么你不想学习?只想玩?人是如何一步一步废掉的

不知道是不是只有我这样子,还是你们也有过类似的经历。 上学的时候总有很多光辉历史,学年名列前茅,或者单科目大佬,但是虽然慢慢地长大了,你开始懈怠了,开始废掉了。。。 什么?你说不知道具体的情况是怎么样的? 我来告诉你: 你常常潜意识里或者心理觉得,自己真正的生活或者奋斗还没有开始。总是幻想着自己还拥有大把时间,还有无限的可能,自己还能逆风翻盘,只不是自己还没开始罢了,自己以后肯定会变得特别厉害...

男生更看重女生的身材脸蛋,还是思想?

往往,我们看不进去大段大段的逻辑。深刻的哲理,往往短而精悍,一阵见血。问:产品经理挺漂亮的,有点心动,但不知道合不合得来。男生更看重女生的身材脸蛋,还是...

为什么程序员做外包会被瞧不起?

二哥,有个事想询问下您的意见,您觉得应届生值得去外包吗?公司虽然挺大的,中xx,但待遇感觉挺低,马上要报到,挺纠结的。

当HR压你价,说你只值7K,你该怎么回答?

当HR压你价,说你只值7K时,你可以流畅地回答,记住,是流畅,不能犹豫。 礼貌地说:“7K是吗?了解了。嗯~其实我对贵司的面试官印象很好。只不过,现在我的手头上已经有一份11K的offer。来面试,主要也是自己对贵司挺有兴趣的,所以过来看看……”(未完) 这段话主要是陪HR互诈的同时,从公司兴趣,公司职员印象上,都给予对方正面的肯定,既能提升HR的好感度,又能让谈判气氛融洽,为后面的发挥留足空间。...

面试:第十六章:Java中级开发

HashMap底层实现原理,红黑树,B+树,B树的结构原理 Spring的AOP和IOC是什么?它们常见的使用场景有哪些?Spring事务,事务的属性,传播行为,数据库隔离级别 Spring和SpringMVC,MyBatis以及SpringBoot的注解分别有哪些?SpringMVC的工作原理,SpringBoot框架的优点,MyBatis框架的优点 SpringCould组件有哪些,他们...

早上躺尸,晚上干活:硅谷科技公司这么流行迟到?

硅谷科技公司上班时间OPEN早已不是什么新鲜事,早九晚五是常态,但有很多企业由于不打卡,员工们10点、11点才“姗姗来迟”的情况也屡见不鲜。 这种灵活的考勤制度为人羡慕,甚至近年来,国内某些互联网企业也纷纷效仿。不过,硅谷普遍弹性的上班制度是怎么由来的呢?这种“流行性迟到”真的有那么轻松、悠哉吗? 《动态规划专题班》 课程试听内容: 动态规划的解题要领 动态规划三大类 求最值/计数/可行性 常...

面试阿里p7,被按在地上摩擦,鬼知道我经历了什么?

面试阿里p7被问到的问题(当时我只知道第一个):@Conditional是做什么的?@Conditional多个条件是什么逻辑关系?条件判断在什么时候执...

终于懂了TCP和UDP协议区别

终于懂了TCP和UDP协议区别

Python爬虫,高清美图我全都要(彼岸桌面壁纸)

爬取彼岸桌面网站较为简单,用到了requests、lxml、Beautiful Soup4

无代码时代来临,程序员如何保住饭碗?

编程语言层出不穷,从最初的机器语言到如今2500种以上的高级语言,程序员们大呼“学到头秃”。程序员一边面临编程语言不断推陈出新,一边面临由于许多代码已存在,程序员编写新应用程序时存在重复“搬砖”的现象。 无代码/低代码编程应运而生。无代码/低代码是一种创建应用的方法,它可以让开发者使用最少的编码知识来快速开发应用程序。开发者通过图形界面中,可视化建模来组装和配置应用程序。这样一来,开发者直...

面试了一个 31 岁程序员,让我有所触动,30岁以上的程序员该何去何从?

最近面试了一个31岁8年经验的程序猿,让我有点感慨,大龄程序猿该何去何从。

大三实习生,字节跳动面经分享,已拿Offer

说实话,自己的算法,我一个不会,太难了吧

程序员垃圾简历长什么样?

已经连续五年参加大厂校招、社招的技术面试工作,简历看的不下于万份 这篇文章会用实例告诉你,什么是差的程序员简历! 疫情快要结束了,各个公司也都开始春招了,作为即将红遍大江南北的新晋UP主,那当然要为小伙伴们做点事(手动狗头)。 就在公众号里公开征简历,义务帮大家看,并一一点评。《启舰:春招在即,义务帮大家看看简历吧》 一石激起千层浪,三天收到两百多封简历。 花光了两个星期的所有空闲时...

Java岗开发3年,公司临时抽查算法,离职后这几题我记一辈子

前几天我们公司做了一件蠢事,非常非常愚蠢的事情。我原以为从学校出来之后,除了找工作有测试外,不会有任何与考试有关的事儿。 但是,天有不测风云,公司技术总监、人事总监两位大佬突然降临到我们事业线,叫上我老大,给我们组织了一场别开生面的“考试”。 那是一个风和日丽的下午,我翘着二郎腿,左手端着一杯卡布奇诺,右手抓着我的罗技鼠标,滚动着轮轴,穿梭在头条热点之间。 “淡黄的长裙~蓬松的头发...

大胆预测下未来5年的Web开发

在2019年的ReactiveConf 上,《Elm in Action》的作者Richard Feldman对未来5年Web开发的发展做了预测,很有意思,分享给大家。如果你有机会从头...

立即提问
相关内容推荐