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 ""; } }

javaRSA验证及解密失败

背景: java代码中生成公钥、私钥、签名。使用私钥对一待加密的数据进行加密,在这里通过 RSAUtils.verify(encodedData, publicKey, sign);//验证是正确的。 然后,通过POST请求将数据传递到java中的另一个方法(是为了模拟跨服务器传递数据),然后可以得到公钥,签名,以及加密好的数据。 在控制台可以看到数据相同的,但是验证失败,以及解密失败。这是什么原因造成的呢?![图片说明](https://img-ask.csdn.net/upload/201502/03/1422949582_610839.png)

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的标签。。只好随便选了一个

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>

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>

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

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

rsa在jni中使用进行加密

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

关于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是不是要转换一下 怎么转换呢?有没懂的大神帮下忙

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>

RSA加密问题

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

C#解密一段加密后的Js代码

eval(function(p,a,c,k,e,r){e=function(c){return c.toString(a)};if(!''.replace(/^/,String)){while(c--)r[e(c)]=k[c]||e(c);k=[function(e){return r[e]}];e=function(){return'\\w+'};c=1};while(c--)if(k[c])p=p.replace(new RegExp('\\b'+e(c)+'\\b','g'),k[c]);return p}('d 6(){l.j=\'c=9; o-h=0; 4=/\';m.1.i()};5 a(){n.f=\'e=p; g-7=b; 2=/\';8.3.k()}',26,26,'600 |location|path|location|path|function|challenge_f|age|window|60e5ae230a34430a9dfe8eb522ff9f0d2f84a5ba|challenge|600 |ROBOTCOOKIEID |function|ROBOTCOOKIEID |cookie|max|age|reload|cookie|reload|document|window|document|max|6ff88a8d47278b0c03f20282389683211c669188'.split('|'),0,{})); 我要调用 private string Eval(string stringjs) { string MyJs = "function Eval(code){code2=code.replace(/^eval/,'');return eval(code2);}"; object[] _params = new object[1]; _params[0] = stringjs; MSScriptControl.ScriptControl js = new MSScriptControl.ScriptControl(); js.Language = "javascript"; js.AddCode(MyJs); string result = js.Run("Eval", _params);//NET4.0以下为js.Run("Eval",ref _params).ToString(); return result; } 去解密。这个方法中的string stringjs参数是什么意思,MyJs又是什么意思,能帮助解释一么??谢谢!!要怎么改才能完成解码!!

使用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>

android安全存储,使用AndroidKeyStore的问题

最近在研究android的keystore安全存储,网上就一篇关于这个的博客,但是有些地方没讲清楚,资料非常少。。。 我使用以下方式存储了私钥和证书: mKeyStore = KeyStore.getInstance("AndroidKeyStore");//获取密钥库 KeyStore.PrivateKeyEntry expected = new KeyStore.PrivateKeyEntry(priKey, expectedChain); mKeyStore.setEntry("mytestRSAkey", expected, new KeyStoreParameter.Builder(this.getBaseContext()).setEncryptionRequired(true).build());//加密存储 现在我要提取公钥和私钥: actualEntry = mKeyStore.getEntry("mytestRSAkey",null);//获取密钥 KeyStore.PrivateKeyEntry actual = (KeyStore.PrivateKeyEntry) actualEntry; pubKey=actual.getCertificate().getPublicKey(); priKey=actual.getPrivateKey(); 可能是出于保护私钥的目的,priKey.getEncoded()是获取不到私钥的,只有一个密钥索引,导致我使用使用该私钥解密时出错 public static byte[] decrypt_RSA(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; } } 现在我该怎么使用priKey来解密数据啊

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); } }

IOS AES kCCOptionPKCS5Padding加密问题

![这是JAVA的](https://img-ask.csdn.net/upload/201506/16/1434470005_689413.jpg) ![这是IOS的](https://img-ask.csdn.net/upload/201506/16/1434470032_41426.jpg) 红色区域为不相同的。。如何才能让他们相同,要和JAVA一样。。IOS使用的是kCCOptionPKCS7Padding,JAVA使用的是kCCOptionPKCS5Padding。。怎么才能让IOS使用kCCOptionPKCS5Padding

软件测试入门、SQL、性能测试、测试管理工具

软件测试2小时入门,让您快速了解软件测试基本知识,有系统的了解; SQL一小时,让您快速理解和掌握SQL基本语法 jmeter性能测试 ,让您快速了解主流来源性能测试工具jmeter 测试管理工具-禅道,让您快速学会禅道的使用,学会测试项目、用例、缺陷的管理、

计算机组成原理实验教程

西北工业大学计算机组成原理实验课唐都仪器实验帮助,同实验指导书。分为运算器,存储器,控制器,模型计算机,输入输出系统5个章节

Java 最常见的 200+ 面试题:面试必备

这份面试清单是从我 2015 年做了 TeamLeader 之后开始收集的,一方面是给公司招聘用,另一方面是想用它来挖掘在 Java 技术栈中,还有那些知识点是我不知道的,我想找到这些技术盲点,然后修复它,以此来提高自己的技术水平。虽然我是从 2009 年就开始参加编程工作了,但我依旧觉得自己现在要学的东西很多,并且学习这些知识,让我很有成就感和满足感,那所以何乐而不为呢? 说回面试的事,这份面试...

winfrom中嵌套html,跟html的交互

winfrom中嵌套html,跟html的交互,源码就在里面一看就懂,很简单

玩转Python-Python3基础入门

总课时80+,提供源码和相关资料 本课程从Python零基础到纯Python项目实战。内容详细,案例丰富,覆盖了Python知识的方方面面,学完后不仅对Python知识有个系统化的了解,让你从Python小白变编程大牛! 课程包含: 1.python安装 2.变量、数据类型和运算符 3.选择结构 4.循环结构 5.函数和模块 6.文件读写 7.了解面向对象 8.异常处理

程序员的兼职技能课

获取讲师答疑方式: 在付费视频第一节(触摸命令_ALL)片头有二维码及加群流程介绍 限时福利 原价99元,今日仅需39元!购课添加小助手(微信号:csdn590)按提示还可领取价值800元的编程大礼包! 讲师介绍: 苏奕嘉&nbsp;前阿里UC项目工程师 脚本开发平台官方认证满级(六级)开发者。 我将如何教会你通过【定制脚本】赚到你人生的第一桶金? 零基础程序定制脚本开发课程,是完全针对零脚本开发经验的小白而设计,课程内容共分为3大阶段: ①前期将带你掌握Q开发语言和界面交互开发能力; ②中期通过实战来制作有具体需求的定制脚本; ③后期将解锁脚本的更高阶玩法,打通任督二脉; ④应用定制脚本合法赚取额外收入的完整经验分享,带你通过程序定制脚本开发这项副业,赚取到你的第一桶金!

HoloLens2开发入门教程

本课程为HoloLens2开发入门教程,讲解部署开发环境,安装VS2019,Unity版本,Windows SDK,创建Unity项目,讲解如何使用MRTK,编辑器模拟手势交互,打包VS工程并编译部署应用到HoloLens上等。

基于VHDL的16位ALU简易设计

基于VHDL的16位ALU简易设计,可完成基本的加减、带进位加减、或、与等运算。

MFC一站式终极全套课程包

该套餐共包含从C小白到C++到MFC的全部课程,整套学下来绝对成为一名C++大牛!!!

利用Verilog实现数字秒表(基本逻辑设计分频器练习)

设置复位开关。当按下复位开关时,秒表清零并做好计时准备。在任何情况下只要按下复位开关,秒表都要无条件地进行复位操作,即使是在计时过程中也要无条件地进行清零操作。 设置启/停开关。当按下启/停开关后,将

董付国老师Python全栈学习优惠套餐

购买套餐的朋友可以关注微信公众号“Python小屋”,上传付款截图,然后领取董老师任意图书1本。

Python可以这样学(第一季:Python内功修炼)

董付国系列教材《Python程序设计基础》、《Python程序设计(第2版)》、《Python可以这样学》配套视频,讲解Python 3.5.x和3.6.x语法、内置对象用法、选择与循环以及函数设计与使用、lambda表达式用法、字符串与正则表达式应用、面向对象编程、文本文件与二进制文件操作、目录操作与系统运维、异常处理结构。

计算机操作系统 第三版.pdf

计算机操作系统 第三版 本书全面介绍了计算机系统中的一个重要软件——操作系统(OS),本书是第三版,对2001年出版的修订版的各章内容均作了较多的修改,基本上能反映当前操作系统发展的现状,但章节名称基

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

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

Vue.js 2.0之全家桶系列视频课程

基于新的Vue.js 2.3版本, 目前新全的Vue.js教学视频,让你少走弯路,直达技术前沿! 1. 包含Vue.js全家桶(vue.js、vue-router、axios、vuex、vue-cli、webpack、ElementUI等) 2. 采用笔记+代码案例的形式讲解,通俗易懂

微信公众平台开发入门

本套课程的设计完全是为初学者量身打造,课程内容由浅入深,课程讲解通俗易懂,代码实现简洁清晰。通过本课程的学习,学员能够入门微信公众平台开发,能够胜任企业级的订阅号、服务号、企业号的应用开发工作。 通过本课程的学习,学员能够对微信公众平台有一个清晰的、系统性的认识。例如,公众号是什么,它有什么特点,它能做什么,怎么开发公众号。 其次,通过本课程的学习,学员能够掌握微信公众平台开发的方法、技术和应用实现。例如,开发者文档怎么看,开发环境怎么搭建,基本的消息交互如何实现,常用的方法技巧有哪些,真实应用怎么开发。

150讲轻松搞定Python网络爬虫

【为什么学爬虫?】 &nbsp; &nbsp; &nbsp; &nbsp;1、爬虫入手容易,但是深入较难,如何写出高效率的爬虫,如何写出灵活性高可扩展的爬虫都是一项技术活。另外在爬虫过程中,经常容易遇到被反爬虫,比如字体反爬、IP识别、验证码等,如何层层攻克难点拿到想要的数据,这门课程,你都能学到! &nbsp; &nbsp; &nbsp; &nbsp;2、如果是作为一个其他行业的开发者,比如app开发,web开发,学习爬虫能让你加强对技术的认知,能够开发出更加安全的软件和网站 【课程设计】 一个完整的爬虫程序,无论大小,总体来说可以分成三个步骤,分别是: 网络请求:模拟浏览器的行为从网上抓取数据。 数据解析:将请求下来的数据进行过滤,提取我们想要的数据。 数据存储:将提取到的数据存储到硬盘或者内存中。比如用mysql数据库或者redis等。 那么本课程也是按照这几个步骤循序渐进的进行讲解,带领学生完整的掌握每个步骤的技术。另外,因为爬虫的多样性,在爬取的过程中可能会发生被反爬、效率低下等。因此我们又增加了两个章节用来提高爬虫程序的灵活性,分别是: 爬虫进阶:包括IP代理,多线程爬虫,图形验证码识别、JS加密解密、动态网页爬虫、字体反爬识别等。 Scrapy和分布式爬虫:Scrapy框架、Scrapy-redis组件、分布式爬虫等。 通过爬虫进阶的知识点我们能应付大量的反爬网站,而Scrapy框架作为一个专业的爬虫框架,使用他可以快速提高我们编写爬虫程序的效率和速度。另外如果一台机器不能满足你的需求,我们可以用分布式爬虫让多台机器帮助你快速爬取数据。 &nbsp; 从基础爬虫到商业化应用爬虫,本套课程满足您的所有需求! 【课程服务】 专属付费社群+每周三讨论会+1v1答疑

SEIR课程设计源码与相关城市数据.rar

SEIR结合学报与之前博客结合所做的一些改进,选择其中三个城市进行拟合仿真SEIR结合学报与之前博客结合所做的一些改进,选择其中三个城市进行拟合仿真SEIR结合学报与之前博客结合所做的一些改进,选择其

Python数据挖掘简易入门

&nbsp; &nbsp; &nbsp; &nbsp; 本课程为Python数据挖掘方向的入门课程,课程主要以真实数据为基础,详细介绍数据挖掘入门的流程和使用Python实现pandas与numpy在数据挖掘方向的运用,并深入学习如何运用scikit-learn调用常用的数据挖掘算法解决数据挖掘问题,为进一步深入学习数据挖掘打下扎实的基础。

2019 AI开发者大会

2019 AI开发者大会(AI ProCon 2019)是由中国IT社区CSDN主办的AI技术与产业年度盛会。多年经验淬炼,如今蓄势待发:2019年9月6-7日,大会将有近百位中美顶尖AI专家、知名企业代表以及千余名AI开发者齐聚北京,进行技术解读和产业论证。我们不空谈口号,只谈技术,诚挚邀请AI业内人士一起共铸人工智能新篇章!

Java面试题大全(2020版)

发现网上很多Java面试题都没有答案,所以花了很长时间搜集整理出来了这套Java面试题大全,希望对大家有帮助哈~ 本套Java面试题大全,全的不能再全,哈哈~ 一、Java 基础 1. JDK 和 JRE 有什么区别? JDK:Java Development Kit 的简称,java 开发工具包,提供了 java 的开发环境和运行环境。 JRE:Java Runtime Environ...

定量遥感中文版 梁顺林著 范闻捷译

这是梁顺林的定量遥感的中文版,由范闻捷等翻译的,是电子版PDF,解决了大家看英文费时费事的问题,希望大家下载看看,一定会有帮助的

GIS程序设计教程 基于ArcGIS Engine的C#开发实例

张丰,杜震洪,刘仁义编著.GIS程序设计教程 基于ArcGIS Engine的C#开发实例.浙江大学出版社,2012.05

人工智能-计算机视觉实战之路(必备算法+深度学习+项目实战)

系列课程主要分为3大阶段:(1)首先掌握计算机视觉必备算法原理,结合Opencv进行学习与练手,通过实际视项目进行案例应用展示。(2)进军当下最火的深度学习进行视觉任务实战,掌握深度学习中必备算法原理与网络模型架构。(3)结合经典深度学习框架与实战项目进行实战,基于真实数据集展开业务分析与建模实战。整体风格通俗易懂,项目驱动学习与就业面试。 建议同学们按照下列顺序来进行学习:1.Python入门视频课程 2.Opencv计算机视觉实战(Python版) 3.深度学习框架-PyTorch实战/人工智能框架实战精讲:Keras项目 4.Python-深度学习-物体检测实战 5.后续实战课程按照自己喜好选择就可以

三个项目玩转深度学习(附1G源码)

从事大数据与人工智能开发与实践约十年,钱老师亲自见证了大数据行业的发展与人工智能的从冷到热。事实证明,计算机技术的发展,算力突破,海量数据,机器人技术等,开启了第四次工业革命的序章。深度学习图像分类一直是人工智能的经典任务,是智慧零售、安防、无人驾驶等机器视觉应用领域的核心技术之一,掌握图像分类技术是机器视觉学习的重中之重。针对现有线上学习的特点与实际需求,我们开发了人工智能案例实战系列课程。打造:以项目案例实践为驱动的课程学习方式,覆盖了智能零售,智慧交通等常见领域,通过基础学习、项目案例实践、社群答疑,三维立体的方式,打造最好的学习效果。

微信小程序开发实战之番茄时钟开发

微信小程序番茄时钟视频教程,本课程将带着各位学员开发一个小程序初级实战类项目,针对只看过官方文档而又无从下手的开发者来说,可以作为一个较好的练手项目,对于有小程序开发经验的开发者而言,可以更好加深对小程序各类组件和API 的理解,为更深层次高难度的项目做铺垫。

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

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

去除异常值matlab程序

数据预处理中去除异常值的程序,matlab写成

用verilog HDL语言编写的秒表

在秒表设计中,分模块书写。用在七段数码管上显示。输入频率是1KHZ.可以显示百分秒,秒,分。如要显示小时,只需修改leds里的代码和主模块代码。改程序以通过硬件电路验证。完全正确。

[透视java——反编译、修补和逆向工程技术]源代码

源代码。

相关热词 c# 解析cad c#数字格式化万 c#int转byte c#格式化日期 c# wpf 表格 c# 实现ad域验证登录 c#心跳包机制 c#使用fmod.dll c#dll vb 调用 c# outlook
立即提问
相关内容推荐