//基本加密 String s = base64.getEncoder().encodeToString("qwe".getBytes());
//基本解密 String s1 = new String(base64.getDecoder().decode(s));2、aes加解密
//基本加密 KeyGenerator keyGenerator = KeyGenerator.getInstance("AES"); keyGenerator.init(128,new SecureRandom("123".getBytes())); SecretKey secretKey = keyGenerator.generateKey(); byte[] encoded = secretKey.getEncoded(); SecretKeySpec key = new SecretKeySpec(encoded, "AES"); Cipher aes1 = Cipher.getInstance("AES"); aes1.init(Cipher.ENCRYPT_MODE,key); byte[] bytes = aes1.doFinal("要加密的内容".getBytes());
//基本解密 KeyGenerator kgen1 = KeyGenerator.getInstance("AES"); kgen1.init(128, new SecureRandom("123".getBytes())); SecretKey secretKey1 = kgen1.generateKey(); byte[] enCodeFormat1 = secretKey1.getEncoded(); SecretKeySpec key1 = new SecretKeySpec(enCodeFormat1, "AES"); Cipher cipher1 = Cipher.getInstance("AES");// 创建密码器 cipher1.init(Cipher.DECRYPT_MODE, key1);// 初始化 byte[] result1 = cipher1.doFinal(bytes); //切记不要直接输出byte[]也不toString(); System.out.println(new String(result1));RSA加密
//获取key KeyPairGenerator rsa = KeyPairGenerator.getInstance("RSA"); rsa.initialize(1024); KeyPair keyPair = rsa.generateKeyPair(); PrivateKey aPrivate = keyPair.getPrivate(); System.out.println(aPrivate); PublicKey aPublic = keyPair.getPublic(); System.out.println(aPublic); //------------------------------------------------------------ Cipher rsa1 = Cipher.getInstance("RSA"); rsa1.init(Cipher.ENCRYPT_MODE,aPrivate); //加密 byte[] bytes = rsa1.doFinal("私钥加密".getBytes()); Cipher cipher = Cipher.getInstance("RSA"); cipher.init(Cipher.DECRYPT_MODE,aPublic); //解密 byte[] bytes1 = cipher.doFinal(bytes);jwt的token
导入jar包
io.jsonwebtoken jjwt0.9.1
生成token
KeyGenerator aes = KeyGenerator.getInstance("AES"); aes.init(128); SecretKey secretKey = aes.generateKey(); Mapclaims = new HashMap<>(); claims.put("userMobile", "186"); claims.put("createDate", "2019-10-22"); claims.put("userName", "name"); claims.put("userCompany", "公司"); claims.put("userCountry", "国家"); long ttl = 60*1000; String token = Jwts.builder() .setClaims(claims) .setIssuedAt(new Date()) .setExpiration(new Date(new Date().getTime() + ttl)) .signWith(SignatureAlgorithm.HS256,secretKey) // 签名类型 与 密钥 .compact(); System.out.println(token); //解密 Claims body = Jwts.parser().setSigningKey(secretKey).parseClaimsJws(token).getBody(); System.out.println(body.get("userName"));
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)