Java–加密解密

來源:互聯網
上載者:User
package com.joye3g.ed;public class Main {public static void main(String[] args) throws Exception {//initThreeDES();//initAES();//initRSA();//initMD5();//initSHA();initHMAC();}public static void initThreeDES(){ThreeDES des = new ThreeDES();        String msg = "安全編程技術_加密解密";      System.out.println("明文是" + msg);   byte[] enc = des.createEncryptor(msg);   System.out.println("密文是" + new String(enc));     byte[] dec = des.createDecryptor(enc);      System.out.println("解密後的結果是" + new String(dec)); }public static void initAES(){AES aes = new AES();        String msg = "安全編程技術_加密解密";      System.out.println("明文是" + msg);   byte[] enc = aes.createEncryptor(msg);   System.out.println("密文是" + new String(enc));     byte[] dec = aes.createDecryptor(enc);      System.out.println("解密後的結果是" + new String(dec)); }public static void initRSA(){RSA rsa = new RSA();String msg = "安全編程技術_加密解密";    System.out.println("明文是:" + msg);   //用公開金鑰加密    byte[] srcBytes = msg.getBytes();    byte[] resultBytes = rsa.encrypt(srcBytes);    String result = new String(resultBytes);   System.out.println("用公開金鑰加密後密文是:" + result);       //用私密金鑰解密   byte[] decBytes = rsa.decrypt(resultBytes);    String dec = new String(decBytes);    System.out.println("用私密金鑰解密後結果是:" + dec); }public static void initMD5(){String msg = "安全編程技術_加密解密";    System.out.println("明文是" + msg);MD5 md5 = new MD5();   byte[] resultBytes = md5.encrypt(msg);   String result = new String(resultBytes);   System.out.println("密文是" + result);}public static void initSHA(){String msg = "安全編程技術_加密解密";    System.out.println("明文是" + msg);SHA sha = new SHA();   byte[] resultBytes = sha.encrypt(msg);   String result = new String(resultBytes);   System.out.println("密文是" + result);}public static void initHMAC(){//要計算訊息驗證碼的字串   String str="安全編程技術_加密解密";  System.out.println("明文是:" + str);  HMAC hmac = new HMAC();byte[] certifyCode = hmac.createEncryptor(str);System.out.println("密文是:" + new String(certifyCode));}}

AES:

package com.joye3g.ed;import java.security.NoSuchAlgorithmException;import java.security.Security;import javax.crypto.Cipher;import javax.crypto.KeyGenerator;import javax.crypto.NoSuchPaddingException;import javax.crypto.SecretKey;public class AES {// KeyGenerator提供對稱金鑰產生器的功能,支援各種演算法private KeyGenerator keyGenerator;// SecretKey負責儲存對稱金鑰private SecretKey secretKey;// Cipher負責完成加密或解密工作private Cipher cipher;// 該位元組數組負責儲存加密的結果private byte[] cipherByte;@SuppressWarnings("restriction")public AES() {Security.addProvider(new com.sun.crypto.provider.SunJCE());// 執行個體化支援AES演算法的金鑰產生器,演算法名稱用AEStry {keyGenerator = KeyGenerator.getInstance("AES");// 產生密鑰secretKey = keyGenerator.generateKey();// 產生Cipher對象,指定其支援AES演算法cipher = Cipher.getInstance("AES");} catch (NoSuchAlgorithmException e) {e.printStackTrace();} catch (NoSuchPaddingException e) {e.printStackTrace();}}/* 對字串str加密 */public byte[] createEncryptor(String str) {try {// 根據金鑰組Cipher對象進行初始化,ENCRYPT_MODE表示加密模式cipher.init(Cipher.ENCRYPT_MODE, secretKey);byte[] src = str.getBytes();// 將加密結果儲存進cipherBytecipherByte = cipher.doFinal(src);} catch (java.security.InvalidKeyException ex) {ex.printStackTrace();} catch (javax.crypto.BadPaddingException ex) {ex.printStackTrace();} catch (javax.crypto.IllegalBlockSizeException ex) {ex.printStackTrace();}return cipherByte;}/* 對位元組數組buff解密 */public byte[] createDecryptor(byte[] buff) {try {// 根據金鑰組Cipher對象進行初始化,ENCRYPT_MODE表示解密模式cipher.init(Cipher.DECRYPT_MODE, secretKey);// 將得到明文存入cipherByte字元數組cipherByte = cipher.doFinal(buff);} catch (java.security.InvalidKeyException ex) {ex.printStackTrace();} catch (javax.crypto.BadPaddingException ex) {ex.printStackTrace();} catch (javax.crypto.IllegalBlockSizeException ex) {ex.printStackTrace();}return cipherByte;}}

DES:

package com.joye3g.ed;import java.security.NoSuchAlgorithmException;import java.security.Security;import javax.crypto.Cipher;import javax.crypto.KeyGenerator;import javax.crypto.NoSuchPaddingException;import javax.crypto.SecretKey;public class DES {// KeyGenerator提供對稱金鑰產生器的功能,支援各種演算法private KeyGenerator keyGenerator;// SecretKey負責儲存對稱金鑰private SecretKey secretKey;// Cipher負責完成加密或解密工作private Cipher cipher;// 該位元組數組負責儲存加密的結果private byte[] cipherByte;@SuppressWarnings("restriction")public DES() {Security.addProvider(new com.sun.crypto.provider.SunJCE());try {// 執行個體化支援DES演算法的金鑰產生器(演算法名稱命名需按規定,否則拋出異常)keyGenerator = KeyGenerator.getInstance("DES");// 產生密鑰secretKey = keyGenerator.generateKey();// 產生Cipher對象,指定其支援DES演算法cipher = Cipher.getInstance("DES");} catch (NoSuchAlgorithmException ex) {ex.printStackTrace();} catch (NoSuchPaddingException ex) {ex.printStackTrace();}}/* 對字串str加密 */public byte[] createEncryptor(String str) {try {// 根據金鑰組Cipher對象進行初始化,ENCRYPT_MODE表示加密模式cipher.init(Cipher.ENCRYPT_MODE, secretKey);byte[] src = str.getBytes();// 將加密結果儲存進cipherBytecipherByte = cipher.doFinal(src);} catch (java.security.InvalidKeyException ex) {ex.printStackTrace();} catch (javax.crypto.BadPaddingException ex) {ex.printStackTrace();} catch (javax.crypto.IllegalBlockSizeException ex) {ex.printStackTrace();}return cipherByte;}/* 對位元組數組buff解密 */public byte[] createDecryptor(byte[] buff) {try {// 根據金鑰組Cipher對象進行初始化,ENCRYPT_MODE表示解密模式cipher.init(Cipher.DECRYPT_MODE, secretKey);// 將得到的明文存入cipherByte字元數組cipherByte = cipher.doFinal(buff);} catch (java.security.InvalidKeyException ex) {ex.printStackTrace();} catch (javax.crypto.BadPaddingException ex) {ex.printStackTrace();} catch (javax.crypto.IllegalBlockSizeException ex) {ex.printStackTrace();}return cipherByte;}}

HMAC:

package com.joye3g.ed;import java.io.UnsupportedEncodingException;import java.security.InvalidKeyException;import java.security.NoSuchAlgorithmException;import javax.crypto.KeyGenerator;import javax.crypto.Mac;import javax.crypto.SecretKey;import javax.crypto.spec.SecretKeySpec;public class HMAC {private Mac mac;public HMAC() {try {// 用DES演算法得到計算驗證碼的密鑰KeyGenerator keyGen = KeyGenerator.getInstance("DESede");SecretKey key = keyGen.generateKey();byte[] keyByte = key.getEncoded();// 產生MAC對象SecretKeySpec SKS = new SecretKeySpec(keyByte, "HMACMD5");mac = Mac.getInstance("HMACMD5");mac.init(SKS);} catch (InvalidKeyException e) {e.printStackTrace();} catch (NoSuchAlgorithmException e) {e.printStackTrace();}}public byte[] createEncryptor(String str) {// 傳入要計算驗證碼的字串byte[] certifyCode = null;try {mac.update(str.getBytes("UTF8"));// 計算驗證碼certifyCode = mac.doFinal();return certifyCode;} catch (IllegalStateException e) {e.printStackTrace();} catch (UnsupportedEncodingException e) {e.printStackTrace();}return null;}}

MD5:

package com.joye3g.ed;import java.security.MessageDigest;import java.security.NoSuchAlgorithmException;public class MD5 {private MessageDigest md5;public MD5() {//根據MD5演算法產生MessageDigest對象   try {md5 = MessageDigest.getInstance("MD5");} catch (NoSuchAlgorithmException e) {e.printStackTrace();}   }// MD5加密 public byte[] encrypt(String msg) {  byte[] srcBytes = msg.getBytes();  //使用srcBytes更新摘要   md5.update(srcBytes);    //完成雜湊計算,得到並返回密文  return md5.digest();  }}

RSA:

package com.joye3g.ed;import java.security.KeyPair;import java.security.KeyPairGenerator;import java.security.NoSuchAlgorithmException;import java.security.interfaces.RSAPrivateKey;import java.security.interfaces.RSAPublicKey;import javax.crypto.Cipher;import javax.crypto.NoSuchPaddingException;public class RSA {private RSAPrivateKey privateKey;private RSAPublicKey publicKey;private Cipher cipher;public RSA() {try {// KeyPairGenerator類用於產生公開金鑰和私密金鑰對,基於RSA演算法產生對象KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance("RSA");// 初始化金鑰組產生器,密鑰大小為1024位keyPairGen.initialize(1024);// 產生一個金鑰組儲存在keyPair中KeyPair keyPair = keyPairGen.generateKeyPair();// 得到私密金鑰privateKey = (RSAPrivateKey) keyPair.getPrivate();// 得到公開金鑰publicKey = (RSAPublicKey) keyPair.getPublic();// 根據私密金鑰對Cipher對象進行初始化cipher = Cipher.getInstance("RSA");} catch (NoSuchAlgorithmException e) {e.printStackTrace();} catch (NoSuchPaddingException e) {e.printStackTrace();}}/* 對srcBytes加密 */public byte[] encrypt(byte[] srcBytes) {if (publicKey != null) {try {// 根據公開金鑰,對Cipher對象進行初始化cipher.init(Cipher.ENCRYPT_MODE, publicKey);// 將加密結果儲存進resultBytesbyte[] resultBytes = cipher.doFinal(srcBytes);return resultBytes;} catch (Exception e) {e.printStackTrace();}}return null;}/* 對encBytes解密 */public byte[] decrypt(byte[] encBytes) {if (privateKey != null) {try {cipher.init(Cipher.DECRYPT_MODE, privateKey);// 將解密結果儲存進resultBytesbyte[] decBytes = cipher.doFinal(encBytes);return decBytes;} catch (Exception e) {e.printStackTrace();}}return null;}}

SHA:

package com.joye3g.ed;import java.security.MessageDigest;import java.security.NoSuchAlgorithmException;public class SHA {private MessageDigest md5;public SHA() {//根據MD5演算法產生MessageDigest對象   try {md5 = MessageDigest.getInstance("MD5");} catch (NoSuchAlgorithmException e) {e.printStackTrace();}   }// MD5加密 public byte[] encrypt(String msg) {  byte[] srcBytes = msg.getBytes();  //使用srcBytes更新摘要   md5.update(srcBytes);    //完成雜湊計算,得到並返回密文  return md5.digest();  }}

3DES:

package com.joye3g.ed;import java.security.NoSuchAlgorithmException;import java.security.Security;import javax.crypto.Cipher;import javax.crypto.KeyGenerator;import javax.crypto.NoSuchPaddingException;import javax.crypto.SecretKey;public class ThreeDES {// KeyGenerator提供對稱金鑰產生器的功能,支援各種演算法private KeyGenerator keyGenerator;// SecretKey負責儲存對稱金鑰private SecretKey secretKey;// Cipher負責完成加密或解密工作private Cipher cipher;// 該位元組數組負責儲存加密的結果private byte[] cipherByte;@SuppressWarnings("restriction")public ThreeDES() {Security.addProvider(new com.sun.crypto.provider.SunJCE());// 執行個體化支援3DES演算法的金鑰產生器,演算法名稱用DESedetry {keyGenerator = KeyGenerator.getInstance("DESede");// 產生密鑰secretKey = keyGenerator.generateKey();// 產生Cipher對象,指定其支援3DES演算法cipher = Cipher.getInstance("DESede");} catch (NoSuchAlgorithmException e) {e.printStackTrace();} catch (NoSuchPaddingException e) {e.printStackTrace();}}/* 對字串str加密 */public byte[] createEncryptor(String str) {try {// 根據金鑰組Cipher對象進行初始化,ENCRYPT_MODE表示加密模式cipher.init(Cipher.ENCRYPT_MODE, secretKey);byte[] src = str.getBytes();// 將加密結果儲存進cipherBytecipherByte = cipher.doFinal(src);} catch (java.security.InvalidKeyException ex) {ex.printStackTrace();} catch (javax.crypto.BadPaddingException ex) {ex.printStackTrace();} catch (javax.crypto.IllegalBlockSizeException ex) {ex.printStackTrace();}return cipherByte;}/* 對位元組數組buff解密 */public byte[] createDecryptor(byte[] buff) {try {// 根據金鑰組Cipher對象進行初始化,ENCRYPT_MODE表示解密模式cipher.init(Cipher.DECRYPT_MODE, secretKey);// 將得到明文存入cipherByte字元數組cipherByte = cipher.doFinal(buff);} catch (java.security.InvalidKeyException ex) {ex.printStackTrace();} catch (javax.crypto.BadPaddingException ex) {ex.printStackTrace();} catch (javax.crypto.IllegalBlockSizeException ex) {ex.printStackTrace();}return cipherByte;}}

 

 

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.