Java 安全

package jwt_demo;

import javax.crypto.*;
import javax.crypto.spec.SecretKeySpec;
import java.io.*;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.Arrays;
import java.util.Base64;

public class AESUtil {
    private static final String ALGORITHM = "AES";

    private final static String charsetName = "UTF-8";

    public static SecretKey generateKey() throws NoSuchAlgorithmException {
        KeyGenerator secretGenerator = KeyGenerator.getInstance(ALGORITHM);
        secretGenerator.init(256);
        SecureRandom secureRandom = new SecureRandom();
        secretGenerator.init(secureRandom);
        return secretGenerator.generateKey();
    }

    private static byte[] saveSecretKey(SecretKey secretKey) {
        Base64.Encoder en = Base64.getEncoder();
        return en.encode(secretKey.getEncoded());
    }

    private static SecretKey getSavedSecretKey(byte[] key) {
        Base64.Decoder de = Base64.getDecoder();
        byte[] dekey = de.decode(key);
        return new SecretKeySpec(dekey, ALGORITHM);
    }


    private static byte[] aes(byte[] contentArray, int mode, SecretKey secretKey) throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException {
        Cipher cipher = Cipher.getInstance(ALGORITHM);
        cipher.init(mode, secretKey);
        return cipher.doFinal(contentArray);
    }

    public static byte[] encrypt(String content, SecretKey secretKey) throws IllegalBlockSizeException, InvalidKeyException, BadPaddingException, NoSuchAlgorithmException, NoSuchPaddingException {
        return encrypt(content.getBytes(), secretKey);
    }

    public static byte[] encrypt(byte[] content, SecretKey secretKey) throws IllegalBlockSizeException, InvalidKeyException, BadPaddingException, NoSuchAlgorithmException, NoSuchPaddingException {
        return aes(content, Cipher.ENCRYPT_MODE, secretKey);
    }

    public static String decrypt(byte[] contentArray, SecretKey secretKey) throws IllegalBlockSizeException, InvalidKeyException, BadPaddingException, NoSuchAlgorithmException, NoSuchPaddingException, UnsupportedEncodingException {
        byte[] result = aes(contentArray, Cipher.DECRYPT_MODE, secretKey);
        return new String(result, charsetName);
    }

    public static String decrypt(String contentArray, SecretKey secretKey) throws IllegalBlockSizeException, InvalidKeyException, BadPaddingException, NoSuchAlgorithmException, NoSuchPaddingException, UnsupportedEncodingException {
        return decrypt(contentArray.getBytes(), secretKey);
    }

    public static void saveKey(SecretKey secretKey, String fileName) throws IOException {
        OutputStream outputStream = new FileOutputStream(new File(fileName));
        byte[] savedKey = saveSecretKey(secretKey);
        outputStream.write(savedKey);
    }


    public static SecretKey getKey(String filename) throws IOException {
        byte[] key = readFromFile(filename);
        return getSavedSecretKey(key);
    }

    public static byte[] readFromFile(String filename) throws IOException {
        FileChannel fc;
        fc = new RandomAccessFile(filename, "r").getChannel();
        MappedByteBuffer byteBuffer = fc.map(FileChannel.MapMode.READ_ONLY, 0,
                fc.size()).load();
        byte[] result = new byte[(int) fc.size()];
        if (byteBuffer.remaining() > 0) {
            byteBuffer.get(result, 0, byteBuffer.remaining());
        }
        byteBuffer.clear();
        fc.close();
        return result;
    }

    public static void writeToFile(String filename, byte[] data) throws IOException {
        OutputStream outputStream = new FileOutputStream(new File(filename));
        BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(outputStream);
        bufferedOutputStream.write(data);
        bufferedOutputStream.close();
    }


    public static void main(String[] args) throws NoSuchAlgorithmException, InvalidKeyException, BadPaddingException, NoSuchPaddingException, IllegalBlockSizeException, UnsupportedEncodingException {
        var key = generateKey();

        byte[] a = encrypt("hello world", key);


        String b = decrypt(a, key);

        System.out.println(Arrays.toString(a));

        System.out.println(b);
    }
}
package jwt_demo;

import javax.crypto.Cipher;

import java.nio.charset.StandardCharsets;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.SecureRandom;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;

/**
 * Java RSA 加密工具類
 * 參考: https://blog.csdn.net/qy20115549/article/details/83105736
 */
class RSAUtil {
    /**
     * 密鑰長度 於原文長度對應 以及越長速度越慢
     */
    private final static int KEY_SIZE = 1024;
    /**
     * 用於封裝隨機產生的公鑰與私鑰
     */
    public static Map<Integer, String> keyMap = new HashMap<>();

    /**
     * 隨機生成密鑰對
     *
     * @throws Exception
     */
    public static void genKeyPair() throws Exception {
        // KeyPairGenerator類用於生成公鑰和私鑰對,基於RSA算法生成對象
        KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance("RSA");
        // 初始化密鑰對生成器
        keyPairGen.initialize(KEY_SIZE, new SecureRandom());
        // 生成一個密鑰對,保存在keyPair中
        KeyPair keyPair = keyPairGen.generateKeyPair();
        // 得到私鑰
        RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();
        // 得到公鑰
        RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
        String publicKeyString = encryptBASE64(publicKey.getEncoded());
        // 得到私鑰字符串
        String privateKeyString = encryptBASE64(privateKey.getEncoded());
        // 將公鑰和私鑰保存到Map
        //0表示公鑰
        keyMap.put(0, publicKeyString);
        //1表示私鑰
        keyMap.put(1, privateKeyString);
    }

    //編碼返回字符串
    public static String encryptBASE64(byte[] key) {
        return Base64.getEncoder().encodeToString(key);
    }

    //解碼返回byte
    public static byte[] decryptBASE64(String key) {
        return Base64.getDecoder().decode(key);
    }

    /**
     * RSA公鑰加密
     *
     * @param str       加密字符串
     * @param publicKey 公鑰
     * @return 密文
     * @throws Exception 加密過程中的異常信息
     */
    public static String encrypt(String str, String publicKey) throws Exception {
        //base64編碼的公鑰
        byte[] decoded = decryptBASE64(publicKey);
        RSAPublicKey pubKey = (RSAPublicKey) KeyFactory.getInstance("RSA").generatePublic(new X509EncodedKeySpec(decoded));
        //RSA加密
        Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.ENCRYPT_MODE, pubKey);
        return encryptBASE64(cipher.doFinal(str.getBytes(StandardCharsets.UTF_8)));
    }

    /**
     * RSA私鑰解密
     *
     * @param str        加密字符串
     * @param privateKey 私鑰
     * @return 明文
     * @throws Exception 解密過程中的異常信息
     */
    public static String decrypt(String str, String privateKey) throws Exception {
        //64位解碼加密後的字符串
        byte[] inputByte = decryptBASE64(str);
        //base64編碼的私鑰
        byte[] decoded = decryptBASE64(privateKey);
        RSAPrivateKey priKey = (RSAPrivateKey) KeyFactory.getInstance("RSA").generatePrivate(new PKCS8EncodedKeySpec(decoded));
        //RSA解密
        Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.DECRYPT_MODE, priKey);
        return new String(cipher.doFinal(inputByte));
    }


    public static void main(String[] args) throws Exception {
        long temp = System.currentTimeMillis();
        //生成公鑰和私鑰
        genKeyPair();
        //加密字符串
        System.out.println("公鑰:" + keyMap.get(0));
        System.out.println("私鑰:" + keyMap.get(1));
        System.out.println("生成密鑰消耗時間:" + (System.currentTimeMillis() - temp) / 1000.0 + "秒");


        String message = "RSA測試aaa";
        System.out.println("原文:" + message);

        temp = System.currentTimeMillis();
        String messageEn = encrypt(message, keyMap.get(0));
        System.out.println("密文:" + messageEn);
        System.out.println("加密消耗時間:" + (System.currentTimeMillis() - temp) / 1000.0 + "秒");

        temp = System.currentTimeMillis();

        String messageDe = decrypt(messageEn, keyMap.get(1));
        System.out.println("解密:" + messageDe);
        System.out.println("解密消耗時間:" + (System.currentTimeMillis() - temp) / 1000.0 + "秒");
    }
}
package jwt_demo;

import io.jsonwebtoken.*;
import io.jsonwebtoken.io.Decoders;
import io.jsonwebtoken.io.Encoders;
import io.jsonwebtoken.security.Keys;

import javax.crypto.SecretKey;
import java.text.SimpleDateFormat;
import java.util.Date;

public class App {
    public static void main(String[] args) {
        long now = System.currentTimeMillis();//當前時間
        long exp = now + 1000 * 60;//過期時間爲1分鐘

        // 這裏是編碼
//        String secretString = "oP7WStjRND1iUQtALAAIUWEQSpjMyF7uXUda8Y2lDPQ=";
//        SecretKey key = Keys.hmacShaKeyFor(Decoders.BASE64.decode(secretString));
//        System.out.println(Encoders.BASE64.encode(key.getEncoded()));


        SecretKey key1 = Keys.secretKeyFor(SignatureAlgorithm.HS512);
        String secretString1 = Encoders.BASE64.encode(key1.getEncoded());
        System.out.println(secretString1);


        JwtBuilder builder = Jwts.builder().setId("888")
                .setIssuer("me")
                .setAudience("you")
                .setIssuedAt(new Date()) // for example, now
                .setSubject("小白")
                .setIssuedAt(new Date())
                .signWith(key1)
                .setExpiration(new Date(exp))
                .claim("hello", "world")
                .setHeaderParam("kid", "myKeyId");
        String token = builder.compact();

        // 這裏是解碼
        SecretKey keyss = Keys.hmacShaKeyFor(Decoders.BASE64.decode(secretString1));
        Jws<Claims> jws = Jwts.parserBuilder()
                .requireSubject("小白")
                .setSigningKey(keyss).build()
                .parseClaimsJws(token);

        {
            // jws
            System.out.println(Encoders.BASE64.encode(keyss.getEncoded()));
            System.out.println(jws.getSignature());
            System.out.println(jws.getClass().getName());
            JwsHeader header = jws.getHeader();
            System.out.println(header.getKeyId());
            Claims claim = jws.getBody();
            System.out.println(claim.getId());
            System.out.println(claim.getSubject());
            System.out.println(claim.getIssuedAt());
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy‐MM‐dd hh:mm:ss");
            System.out.println("簽發時間:" + sdf.format(claim.getIssuedAt()));
            System.out.println("過期時 間:" + sdf.format(claim.getExpiration()));
            System.out.println("當前時間:" + sdf.format(new Date()));
        }

    }

}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章