常用數位簽章演算法RSA與DSA的Java程式內實現樣本_java

來源:互聯網
上載者:User

RSA密碼編譯演算法
我們來回顧一下RSA的密碼編譯演算法。我們從公開金鑰加密演算法和簽名演算法的定義出發,用比較規範的語言來描述這一演算法。
RSA公開金鑰加密體制包含如下3個演算法:KeyGen(密鑰產生演算法),Encrypt(密碼編譯演算法)以及Decrypt(解密演算法)。
密鑰產生演算法以安全常數作為輸入,輸出一個公開金鑰PK,和一個私密金鑰SK。安全常數用於確定這個密碼編譯演算法的安全性有多高,一般以密碼編譯演算法使用的質數p的大小有關。越大,質數p一般越大,保證體制有更高的安全性。在RSA中,密鑰產生演算法如下:演算法首先隨機產生兩個不同大質數p和q,計算N=pq。隨後,演算法計算歐拉函數。接下來,演算法隨機播放一個小於的整數e,並計算e關於的模反元素d。最後,公開金鑰為PK=(N, e),私密金鑰為SK=(N, d)。
密碼編譯演算法以公開金鑰PK和待加密的訊息M作為輸入,輸出密文CT。在RSA中,密碼編譯演算法如下:演算法直接輸出密文為
解密演算法以私密金鑰SK和密文CT作為輸入,輸出訊息M。在RSA中,解密演算法如下:演算法直接輸出明文為。由於e和d在下互逆,因此我們有:
所以,從演算法描述中我們也可以看出:公開金鑰用於對資料進行加密,私密金鑰用於對資料進行解密。當然了,這個也可以很直觀的理解:公開金鑰就是公開的密鑰,其公開了大家才能用它來加密資料。私密金鑰是私人的密鑰,誰有這個密鑰才能夠解密密文。否則大家都能看到私密金鑰,就都能解密,那不就亂套了。
下面就來看一下Java中的簡單實現:

package com.stone.security;  import java.security.KeyPair; import java.security.KeyPairGenerator; import java.security.PrivateKey; import java.security.PublicKey; import java.util.Arrays;  import javax.crypto.Cipher;  /**  * RSA演算法 公開金鑰加密 非對稱式加密  */ public class RSA {  public static final String KEY_ALGORITHM = "RSA";  public static final String CIPHER_ALGORITHM_ECB1 = "RSA/ECB/PKCS1Padding";  public static final String CIPHER_ALGORITHM_ECB2 = "RSA/ECB/OAEPWithSHA-1AndMGF1Padding"; //不能用  public static final String CIPHER_ALGORITHM_ECB3 = "OAEPWithSHA-256AndMGF1Padding"; //不能用   static PublicKey publicKey;  static PrivateKey privateKey;  static Cipher cipher;  static KeyPair keyPair;   public static void main(String[] args) throws Exception {  method1("斯柯達U*(Sfsad7f()*^%%$");  method2("斯柯達U*(Sfsad7f()*^%%$");  method3("斯柯達U*(Sfsad7f()*^%%$");    }   /**  * 公開金鑰加密,私密金鑰解密 使用預設CIPHER_ALGORITHM_ECB1  * @param str  * @throws Exception  */  static void method1(String str) throws Exception {  KeyPairGenerator keyGenerator = KeyPairGenerator.getInstance(KEY_ALGORITHM);  KeyPair keyPair = keyGenerator.generateKeyPair();  publicKey = keyPair.getPublic();  privateKey = keyPair.getPrivate();  cipher = Cipher.getInstance(KEY_ALGORITHM);  cipher.init(Cipher.ENCRYPT_MODE, publicKey); //公開金鑰加密  byte[] encrypt = cipher.doFinal(str.getBytes());  System.out.println("公開金鑰加密後1:" + Arrays.toString(encrypt));    cipher.init(Cipher.DECRYPT_MODE, privateKey);//私密金鑰解密  byte[] decrypt = cipher.doFinal(encrypt);  System.out.println("私密金鑰解密後1:" + new String(decrypt));  }   /**  * 私密金鑰加密,公開金鑰解密 使用預設CIPHER_ALGORITHM_ECB1  * @param str  * @throws Exception  */  static void method2(String str) throws Exception {  KeyPairGenerator keyGenerator = KeyPairGenerator.getInstance(KEY_ALGORITHM);  KeyPair keyPair = keyGenerator.generateKeyPair();  publicKey = keyPair.getPublic();  privateKey = keyPair.getPrivate();  cipher = Cipher.getInstance(KEY_ALGORITHM);  cipher.init(Cipher.ENCRYPT_MODE, privateKey); //私密金鑰加密  byte[] encrypt = cipher.doFinal(str.getBytes());  System.out.println("私密金鑰加密後2:" + Arrays.toString(encrypt));    cipher.init(Cipher.DECRYPT_MODE, publicKey);//公開金鑰解密  byte[] decrypt = cipher.doFinal(encrypt);  System.out.println("公開金鑰解密後2:" + new String(decrypt));  }   /**  * 私密金鑰加密,公開金鑰解密 使用CIPHER_ALGORITHM_ECB1 = RSA/ECB/PKCS1Padding  * @param str  * @throws Exception  */  static void method3(String str) throws Exception {  KeyPairGenerator keyGenerator = KeyPairGenerator.getInstance(KEY_ALGORITHM);  KeyPair keyPair = keyGenerator.generateKeyPair();  publicKey = keyPair.getPublic();  privateKey = keyPair.getPrivate();  cipher = Cipher.getInstance(CIPHER_ALGORITHM_ECB1);  cipher.init(Cipher.ENCRYPT_MODE, privateKey); //私密金鑰加密  byte[] encrypt = cipher.doFinal(str.getBytes());  System.out.println("私密金鑰加密後3:" + Arrays.toString(encrypt));    cipher.init(Cipher.DECRYPT_MODE, publicKey);//公開金鑰解密  byte[] decrypt = cipher.doFinal(encrypt);  System.out.println("公開金鑰解密後3:" + new String(decrypt));  } } 

DSA演算法和數位簽章
DSA 一般用於數位簽章和認證。
DSA是Schnorr和ElGamal簽名演算法的變種,被美國NIST作為DSS(DigitalSignature Standard)。
DSA是基於整數有限域離散對數難題的,其安全性與RSA相比差不多。
在DSA數位簽章和認證中,寄件者使用自己的私密金鑰對檔案或訊息進行簽名,接受者收到訊息後使用寄件者的公開金鑰
來驗證簽名的真實性。DSA只是一種演算法,和RSA不同之處在於它不能用作加密和解密,也不能進行金鑰交換,
只用於簽名,它比RSA要快很多.

package com.stone.security;  import java.security.Key; import java.security.KeyFactory; import java.security.KeyPair; import java.security.KeyPairGenerator; import java.security.PrivateKey; import java.security.PublicKey; import java.security.SecureRandom; import java.security.Signature; import java.security.spec.PKCS8EncodedKeySpec; import java.security.spec.X509EncodedKeySpec; import java.util.HashMap; import java.util.Map;  import sun.misc.BASE64Decoder; import sun.misc.BASE64Encoder;  /**  * DSA-Digital Signature Algorithm 是Schnorr和ElGamal簽名演算法的變種,被美國NIST作為DSS(DigitalSignature Standard)。  * 簡單的說,這是一種更進階的驗證方式,用作數位簽章。不單單只有公開金鑰、私密金鑰,還有數位簽章。私密金鑰加密產生數位簽章,公開金鑰驗證資料及簽名。  * 如果資料和簽名不匹配則認為驗證失敗!即 傳輸中的資料 可以不再加密,接收方獲得資料後,拿到公開金鑰與簽名 驗證資料是否有效  */ public class DSA {  /** *不僅可以使用DSA演算法,同樣也可以使用RSA演算法做數位簽章 */  public static final String KEY_ALGORITHM = "RSA";  public static final String SIGNATURE_ALGORITHM = "MD5withRSA";*/   public static final String KEY_ALGORITHM = "DSA";  public static final String SIGNATURE_ALGORITHM = "DSA";   public static final String DEFAULT_SEED = "$%^*%^()(HJG8awfjas7"; //預設種子  public static final String PUBLIC_KEY = "DSAPublicKey";  public static final String PRIVATE_KEY = "DSAPrivateKey";   public static void main(String[] args) throws Exception {  String str = "!@#$!#^$#&ZXVDF呆軍工路愛著你*()_+";  byte[] data = str.getBytes();    Map<String, Object> keyMap = initKey();// 構建密鑰  PublicKey publicKey = (PublicKey) keyMap.get(PUBLIC_KEY);  PrivateKey privateKey = (PrivateKey) keyMap.get(PRIVATE_KEY);  System.out.println("私密金鑰format:" + privateKey.getFormat());  System.out.println("公開金鑰format:" + publicKey.getFormat());      // 產生簽名  String sign = sign(data, getPrivateKey(keyMap));    // 驗證簽名  boolean verify1 = verify("aaa".getBytes(), getPublicKey(keyMap), sign);  System.err.println("經驗證 資料和簽名匹配:" + verify1);    boolean verify = verify(data, getPublicKey(keyMap), sign);  System.err.println("經驗證 資料和簽名匹配:" + verify);  }   /**  * 產生密鑰  *  * @param seed 種子  * @return 金鑰組象  * @throws Exception  */  public static Map<String, Object> initKey(String seed) throws Exception {  System.out.println("產生密鑰");    KeyPairGenerator keygen = KeyPairGenerator.getInstance(KEY_ALGORITHM);  SecureRandom secureRandom = new SecureRandom();  secureRandom.setSeed(seed.getBytes());  //Modulus size must range from 512 to 1024 and be a multiple of 64  keygen.initialize(640, secureRandom);    KeyPair keys = keygen.genKeyPair();  PrivateKey privateKey = keys.getPrivate();  PublicKey publicKey = keys.getPublic();    Map<String, Object> map = new HashMap<String, Object>(2);  map.put(PUBLIC_KEY, publicKey);  map.put(PRIVATE_KEY, privateKey);  return map;  }   /**  * 產生預設密鑰  *  * @return 金鑰組象  * @throws Exception  */  public static Map<String, Object> initKey() throws Exception {  return initKey(DEFAULT_SEED);  }   /**  * 取得私密金鑰  *  * @param keyMap  * @return  * @throws Exception  */  public static String getPrivateKey(Map<String, Object> keyMap) throws Exception {  Key key = (Key) keyMap.get(PRIVATE_KEY);  return encryptBASE64(key.getEncoded()); //base64加密私密金鑰  }   /**  * 取得公開金鑰  *  * @param keyMap  * @return  * @throws Exception  */  public static String getPublicKey(Map<String, Object> keyMap) throws Exception {  Key key = (Key) keyMap.get(PUBLIC_KEY);  return encryptBASE64(key.getEncoded()); //base64加密公開金鑰  }   /**  * 用私密金鑰對資訊進行數位簽章  * @param data 加密資料  * @param privateKey 私密金鑰-base64加密的  * @return  * @throws Exception  */  public static String sign(byte[] data, String privateKey) throws Exception {  System.out.println("用私密金鑰對資訊進行數位簽章");    byte[] keyBytes = decryptBASE64(privateKey);  PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(keyBytes);  KeyFactory factory = KeyFactory.getInstance(KEY_ALGORITHM);  PrivateKey priKey = factory.generatePrivate(keySpec);//產生 私密金鑰    //用私密金鑰對資訊進行數位簽章  Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM);  signature.initSign(priKey);  signature.update(data);  return encryptBASE64(signature.sign());  }   /**  * BASE64Encoder 加密  * @param data 要加密的資料  * @return 加密後的字串  */  private static String encryptBASE64(byte[] data) {  BASE64Encoder encoder = new BASE64Encoder();  String encode = encoder.encode(data);  return encode;  }   /**  * BASE64Decoder 解密  * @param data 要解密的字串  * @return 解密後的byte[]  * @throws Exception  */  private static byte[] decryptBASE64(String data) throws Exception {  BASE64Decoder decoder = new BASE64Decoder();  byte[] buffer = decoder.decodeBuffer(data);  return buffer;  }   /**  * 校正數位簽章  * @param data 加密資料  * @param publicKey  * @param sign 數位簽章  * @return  * @throws Exception  */  public static boolean verify(byte[] data, String publicKey, String sign) throws Exception {  byte[] keyBytes = decryptBASE64(publicKey);  X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyBytes);  KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);  PublicKey pubKey = keyFactory.generatePublic(keySpec);    Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM);  signature.initVerify(pubKey);  signature.update(data);    return signature.verify(decryptBASE64(sign)); //驗證簽名  }  } 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.