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;
class RSAUtil {
private final static int KEY_SIZE = 1024;
public static Map<Integer, String> keyMap = new HashMap<>();
public static void genKeyPair() throws Exception {
KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance("RSA");
keyPairGen.initialize(KEY_SIZE, new SecureRandom());
KeyPair keyPair = keyPairGen.generateKeyPair();
RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();
RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
String publicKeyString = encryptBASE64(publicKey.getEncoded());
String privateKeyString = encryptBASE64(privateKey.getEncoded());
keyMap.put(0, publicKeyString);
keyMap.put(1, privateKeyString);
}
public static String encryptBASE64(byte[] key) {
return Base64.getEncoder().encodeToString(key);
}
public static byte[] decryptBASE64(String key) {
return Base64.getDecoder().decode(key);
}
public static String encrypt(String str, String publicKey) throws Exception {
byte[] decoded = decryptBASE64(publicKey);
RSAPublicKey pubKey = (RSAPublicKey) KeyFactory.getInstance("RSA").generatePublic(new X509EncodedKeySpec(decoded));
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.ENCRYPT_MODE, pubKey);
return encryptBASE64(cipher.doFinal(str.getBytes(StandardCharsets.UTF_8)));
}
public static String decrypt(String str, String privateKey) throws Exception {
byte[] inputByte = decryptBASE64(str);
byte[] decoded = decryptBASE64(privateKey);
RSAPrivateKey priKey = (RSAPrivateKey) KeyFactory.getInstance("RSA").generatePrivate(new PKCS8EncodedKeySpec(decoded));
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;
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())
.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);
{
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()));
}
}
}