Keygen.java

  1. package cn.home1.environment;

  2. import cn.home1.oss.lib.common.crypto.AesCbcKey;
  3. import cn.home1.oss.lib.common.crypto.AesKeyGenerator;
  4. import cn.home1.oss.lib.common.crypto.JwtKeyGenerator;
  5. import cn.home1.oss.lib.common.crypto.RsaKeys;

  6. import org.springframework.boot.Banner;
  7. import org.springframework.boot.CommandLineRunner;
  8. import org.springframework.boot.builder.SpringApplicationBuilder;

  9. public class Keygen implements CommandLineRunner {

  10.   public static void main(final String... args) {
  11.     new SpringApplicationBuilder()
  12.         .sources(Keygen.class)
  13.         .bannerMode(Banner.Mode.OFF)
  14.         .run(args);
  15.   }

  16.   @Override
  17.   public void run(final String... args) throws Exception {
  18.     if (args.length == 0) {
  19.       System.err.println(this.usage());
  20.     } else {
  21.       final String option = args[0];
  22.       final String result = this.generateKey(option);
  23.       if (result != null) {
  24.         System.out.print(result);
  25.       } else {
  26.         System.err.println(this.usage());
  27.       }
  28.     }
  29.   }

  30.   public String generateKey(final String option) {
  31.     final String spec;
  32.     final String result;
  33.     switch (option) {
  34.       case "-aes":
  35.         spec = AesCbcKey.keySpec(256);
  36.         result = new AesKeyGenerator(spec).generateKey().toString();
  37.         break;
  38.       case "-jwt":
  39.         spec = "HS512";
  40.         result = new JwtKeyGenerator(spec).generateKey().toString();
  41.         break;
  42.       case "-rsa":
  43.         final int keySize = 1024;
  44.         result = RsaKeys.generateRsaKey(keySize);
  45.         break;
  46.       // support "-jks" ?
  47.       default:
  48.         result = null;
  49.         break;
  50.     }
  51.     return result;
  52.   }

  53.   private String usage() {
  54.     return "" + //
  55.         "Usage: java -jar oss-lib-common-*.jar [OPTION]\n" + //
  56.         "\t-aes\n" + //
  57.         "\t\tgenerate random AES CBC key\n" + //
  58.         "\t-jwt\n" + //
  59.         "\t\tgenerate random JWT HS512 key\n" + //
  60.         "\t-rsa\n" + //
  61.         "\t\tgenerate random RSA1024 key\n" + //
  62.         "";
  63.   }
  64. }