中文字幕av专区_日韩电影在线播放_精品国产精品久久一区免费式_av在线免费观看网站

溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

在Java項目中怎么實現一個非對稱加密算法

發布時間:2020-11-21 14:37:28 來源:億速云 閱讀:146 作者:Leah 欄目:開發技術

今天就跟大家聊聊有關在Java項目中怎么實現一個非對稱加密算法,可能很多人都不太了解,為了讓大家更加了解,小編給大家總結了以下內容,希望大家根據這篇文章可以有所收獲。

非對稱加密算法與對稱加密算法的主要差別在于非對稱加密算法用于加密和解密的密鑰不相同,非對稱加密算法密鑰分為公鑰和私鑰,公鑰加密只能用私鑰解密,反之私鑰加密只能用公鑰解密。相比對稱加密算法,非對稱加密算法加/解密效率低,但安全性高,這兩種算法一般結合使用。常見非對稱加密算法有RSA、ECC、Elgamal等。

使用RSA實現加密解密

公鑰加密,私鑰解密。

package com.ss.utils;

import javax.crypto.Cipher;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;

public class RsaUtil {
  public static final String KEY_TYPE_PRIVATE_KEY = "privateKey";
  public static final String KEY_TYPE_PUBLIC_KEY = "publicKey";

  /**
   * 生成公鑰和私鑰
   *
   * @return
   * @throws NoSuchAlgorithmException
   */
  public static Map<String, String> generateKey() throws NoSuchAlgorithmException {
    Map<String, String> resultMap = new HashMap<>();
    KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
    KeyPair keyPair = keyPairGenerator.generateKeyPair();
    Base64.Encoder encoder = Base64.getEncoder();
    resultMap.put(KEY_TYPE_PRIVATE_KEY, encoder.encodeToString(keyPair.getPrivate().getEncoded()));
    resultMap.put(KEY_TYPE_PUBLIC_KEY, encoder.encodeToString(keyPair.getPublic().getEncoded()));
    return resultMap;
  }

  /**
   * RSA加密
   * @param key
   * @param content
   * @param keyType
   * @return
   * @throws Exception
   */
  public static String rsaEncrypt(String key, String content, String keyType) throws Exception {
    return rsa(key, content.getBytes(), keyType, Cipher.ENCRYPT_MODE);
  }

  /**
   * RSA解密
   * @param key
   * @param content
   * @param keyType
   * @return
   * @throws Exception
   */
  public static String rsaDecrypt(String key, String content, String keyType) throws Exception {
    return rsa(key, Base64.getDecoder().decode(content), keyType, Cipher.DECRYPT_MODE);
  }

  private static String rsa(String key, byte[] content, String keyType, int mode) throws Exception {
    Cipher cipher = Cipher.getInstance("RSA");
    KeyFactory keyFactory = KeyFactory.getInstance("RSA");
    if (KEY_TYPE_PRIVATE_KEY.equals(keyType)) {
      cipher.init(mode, keyFactory.generatePrivate(new PKCS8EncodedKeySpec(Base64.getDecoder().decode(key))));
    } else {
      cipher.init(mode, keyFactory.generatePublic(new X509EncodedKeySpec(Base64.getDecoder().decode(key))));
    }
    byte[] bytes = cipher.doFinal(content);
    return mode == Cipher.DECRYPT_MODE &#63; new String(bytes) : Base64.getEncoder().encodeToString(bytes);
  }

  public static void main(String[] args) throws Exception {
    String content = "大王叫我來巡山吶";

    //生成密鑰對
    Map<String, String> keyMap = generateKey();
    System.out.println("私鑰:" + keyMap.get(KEY_TYPE_PRIVATE_KEY));
    System.out.println("公鑰:" + keyMap.get(KEY_TYPE_PUBLIC_KEY));

    //私鑰加密,公鑰解密
    String privateKeyData = rsaEncrypt(keyMap.get(KEY_TYPE_PRIVATE_KEY), content, KEY_TYPE_PRIVATE_KEY);
    System.out.println("私鑰加密:" + privateKeyData);
    System.out.println("公鑰解密:" + rsaDecrypt(keyMap.get(KEY_TYPE_PUBLIC_KEY), privateKeyData, KEY_TYPE_PUBLIC_KEY));

    //公鑰加密,私鑰解密
    String publicKeyData = rsaEncrypt(keyMap.get(KEY_TYPE_PUBLIC_KEY), content, KEY_TYPE_PUBLIC_KEY);
    System.out.println("公鑰加密:" + publicKeyData);
    System.out.println("私鑰解密:" + rsaDecrypt(keyMap.get(KEY_TYPE_PRIVATE_KEY), publicKeyData, KEY_TYPE_PRIVATE_KEY));
  }
}

輸出

私鑰:MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQDQPZnj0+/uh6jG0/rqVsXKLve7wTw2LVEwdBhm+SPrLoHYb4+6idNeF4bWgTqNRs2hfewq5cyiwXujT+eqp0g1ebSLWSUWzBsktynQMggxb8IwtnFYzmZX7BSAUudrfTre74RtKS0krYY5PCXCGR/EGbbXMVv1m2S59BrkWEI8c/iORhRAJ5/pqRW/51cIimPx9iTYx/QZC4VsCRi8ZrBaXcJhEi4Y/YzOFhfITID4ATis0Z3yw3FVybKzJo3Nexupcec5qaLBlwuDkY6E4NgQq51bjBCUB78RgXFLdaVtfBu9Vr7pRdqrh7sD//kpiicjiLJvmcLG9egXrkHRlm2TAgMBAAECggEAes75hM0mwOujBA9b+Pu3pedRHp91XRYYvZSaF5ByyG4jEXuprf8+ck05riOEXnEVMFpM/3eK2al1uviSzafeA/uEqHGoV+uDToHe3PPEtTMNuSC/c/o1jUCjTpKV/GRcZcGnvaD9CJZ1hCeetPuQKlxn4j0v2IcOPkRh46zVU0SZJKu5Ltt6iyGbpk6qqlpLnX93Ez5weWLnuolgjF34JBDQpc/zZjHwC8/avE81cJ3dUQR55l9QiwZUoMQ2eDWO1UcPAEqRssNAwEHbQJFSJmqtvg1yuSSvPIGB5ATPlTu7EoOLFMOQm3qoAxX7/FR9uU50wHivyZrRyKV4CdiLcQKBgQDuj6bh2WUQRIBU5ZOtljbs73RdYYbS1uUHubizQ3rqrNo3+TmaVu+7H3DPPI0L21YVpjXuPMUVkix+KA7HiDqULxx0yZMsdqXmggOT2QFEjGdueMFAJw09jAHnCIwuxmn3f94XAvV6N+Hfhjy31RGPQhjFGn6QQ16a3NI46CD6VwKBgQDfdorB9Wm0H6QJ8AYAQuHAiFJnXeOzN0q2407F5kx8XkAKwKaI7ybGZbiYES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X4rsGNHEYuyN6/sbbD56r3ij5tUpShXFlcHrzVH4IfD4ySbvNNeMs2FrZLF3zvQmwRKDPH6SJ0DEczi5N97Vfh5b2tfyLT8iX3t9LPWgEj5mB7MXiYPc56mza+ZAqDduxWWsm6Emm81uKn97wZnasg8zXlDbhRttVTWhszbDhrFqsgd2sb8ZZUZIuiGTaIg7U6Slc5x9uS3UVACXXVyMCmxiVutQtg3Z4kt80ruh7xO0hl4cWk6P2Tg0ncaIQn/5vKsO2UXr/EsCb2rchWN3ZBHTVyQ83v/EHDtQw==
公鑰解密:大王叫我來巡山吶
公鑰加密:aartOyClfEIz1JT5nghpTbXxLZEOovm+vwvg+u3Tw8t5LOF+C7Gg/uxUP8Hm5jEkN6JfBHaMWTKg0RQ2xf3CCuXcLIpYVCOUwADwd05E8guEfZBT8FIp8jghCz2j+lAIiTfGZvsK9qUdZEmwTAEjV6uP4avF6njriglGJ4KhcYXEO66tOJWe2nQ1hyYXEHS43h9F0dtlWDjF6Xr6wdmUALnhprHDwKPdT/1T8p7+M5Fz7fUC7TJulBHWCSZvhgl405PvN+iTv7VysBJKRPks1JnmMe6BxFyhxXZfNRHmUyQvTMSfWt/A5gOy8ao/SOwWv0QMSh6NbocSd/tpjn27kw==
私鑰解密:大王叫我來巡山吶

使用RSA實現數字簽名

私鑰簽名,公鑰驗證。

package com.ss.utils;

import java.security.*;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;

public class SignatureUtil {
  public static final String KEY_TYPE_PRIVATE_KEY = "privateKey";
  public static final String KEY_TYPE_PUBLIC_KEY = "publicKey";

  /**
   * 生成公鑰和私鑰
   *
   * @return
   * @throws NoSuchAlgorithmException
   */
  public static Map<String, String> generateKey() throws NoSuchAlgorithmException {
    Map<String, String> resultMap = new HashMap<>();
    KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
    KeyPair keyPair = keyPairGenerator.generateKeyPair();
    Base64.Encoder encoder = Base64.getEncoder();
    resultMap.put(KEY_TYPE_PRIVATE_KEY, encoder.encodeToString(keyPair.getPrivate().getEncoded()));
    resultMap.put(KEY_TYPE_PUBLIC_KEY, encoder.encodeToString(keyPair.getPublic().getEncoded()));
    return resultMap;
  }

  /**
   * 私鑰簽名
   * @param privateKeyStr
   * @param content
   * @return
   * @throws Exception
   */
  public static String generateSignature(String privateKeyStr, String content) throws Exception {
    KeyFactory keyFactory = KeyFactory.getInstance("RSA");
    Signature signature = Signature.getInstance("SHA1withRSA");
    PrivateKey privateKey = keyFactory.generatePrivate(new PKCS8EncodedKeySpec(Base64.getDecoder().decode(privateKeyStr)));
    signature.initSign(privateKey);
    signature.update(content.getBytes());
    return Base64.getEncoder().encodeToString(signature.sign());
  }

  /**
   * 公鑰驗證
   * @param publicKeyStr
   * @param content
   * @param sign
   * @return
   * @throws Exception
   */
  public static boolean verifySignature(String publicKeyStr, String content, String sign) throws Exception {
    KeyFactory keyFactory = KeyFactory.getInstance("RSA");
    Signature signature = Signature.getInstance("SHA1withRSA");
    PublicKey publicKey = keyFactory.generatePublic(new X509EncodedKeySpec(Base64.getDecoder().decode(publicKeyStr)));
    signature.initVerify(publicKey);
    signature.update(content.getBytes());
    return signature.verify(Base64.getDecoder().decode(sign));
  }

  public static void main(String[] args) throws Exception {
    String content = "大王叫我來巡山吶";

    //生成密鑰對
    Map<String, String> keyMap = generateKey();

    //私鑰簽名
    String sign = generateSignature(keyMap.get(KEY_TYPE_PRIVATE_KEY), content);
    System.out.println("私鑰簽名:" + sign);

    //公鑰驗證
    boolean verifyResult = verifySignature(keyMap.get(KEY_TYPE_PUBLIC_KEY), content, sign);
    System.out.println("公鑰驗證:" + verifyResult);

    //將內容做下修改,再進行公鑰驗證
    boolean verifyResult2 = verifySignature(keyMap.get(KEY_TYPE_PUBLIC_KEY), content + "啦啦啦啦", sign);
    System.out.println("公鑰驗證:" + verifyResult2);
  }
}

輸出

私鑰簽名:XDWeOUVZhXNPl58mcmRK8ht9TAhnREc+NlnSs2b6PCJuj29ABuoXsjZeJqSspGw8hm9ckHVSTrUt8pX4BFBFzrINDRBsx3TdLp2L8nMkhjFUfo0qcyZo8ReEGFCNr0ergkq2W1Me/5W40GrQz4cJcQ4KV/QWzD8YHWcnDvKg9Q0nXJSngyhJTzUB8o/pgo/tmkA9+bWW212UD9nzEXu5aoPEcYyoo3iFWRX5o9Jgg6ZF+exmWizwZHkg4eD1zC5IN3m4yRS6GRbnZInEuDsOMp9W7HouDLUirkFZiSkyW+DVto+L6CE5eNBrWC52zxiNkVBlkyYKOatSpcrQrtnyiQ==
公鑰驗證:true
公鑰驗證:false

看完上述內容,你們對在Java項目中怎么實現一個非對稱加密算法有進一步的了解嗎?如果還想了解更多知識或者相關內容,請關注億速云行業資訊頻道,感謝大家的支持。

向AI問一下細節

免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。

AI

扎鲁特旗| 石嘴山市| 武山县| 景谷| 绥阳县| 淮安市| 延川县| 浙江省| 长白| 扎兰屯市| 营山县| 赫章县| 噶尔县| 阿瓦提县| 玉山县| 得荣县| 潮安县| 兴仁县| 沐川县| 忻城县| 曲水县| 永州市| 封丘县| 菏泽市| 旌德县| 武功县| 云梦县| 综艺| 拉萨市| 奉新县| 栾城县| 大新县| 乾安县| 泸西县| 海伦市| 乌什县| 东丰县| 大足县| 甘孜| 扎鲁特旗| 大悟县|