Example #1
1
  public static void main(String[] args) throws Exception {

    // Generate 20 serial numbers with dup and a special order
    int count = 20;
    BigInteger[] serials = new BigInteger[count];
    for (int i = 0; i < count; i++) {
      serials[i] = BigInteger.valueOf(i * 7 % 10);
    }

    // Generates a CRL
    X509CRLEntry[] badCerts = new X509CRLEntry[count];
    for (int i = 0; i < count; i++) {
      badCerts[i] =
          new X509CRLEntryImpl(serials[i], new Date(System.currentTimeMillis() + i * 1000));
    }
    X500Name owner = new X500Name("CN=CA");
    X509CRLImpl crl = new X509CRLImpl(owner, new Date(), new Date(), badCerts);
    KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
    crl.sign(kpg.genKeyPair().getPrivate(), "SHA1withRSA");
    byte[] data = crl.getEncodedInternal();

    // Check the encoding
    checkData(crl, data, serials);

    // Load a CRL from raw data
    CertificateFactory cf = CertificateFactory.getInstance("X.509");
    X509CRLImpl crl2 = (X509CRLImpl) cf.generateCRL(new ByteArrayInputStream(data));

    // Check the encoding again
    data = crl2.getEncodedInternal();
    checkData(crl2, data, serials);
  }
Example #2
0
 @Override
 public void setAlgorithm(KeyAgreementType dhMode) {
   if (keyType != null && keyType.keyType == dhMode.keyType) return;
   keyType = dhMode;
   KeyPairGenerator kpg = null;
   try {
     switch (keyType.keyType) {
       case KeyAgreementType.DH_MODE_DH3K:
         algorithm = "DH";
         kpg = KeyPairGenerator.getInstance(algorithm, "ZBC");
         kpg.initialize(576);
         keyPair = kpg.genKeyPair();
         break;
       case KeyAgreementType.DH_MODE_EC25:
         algorithm = "ECDH";
         kpg = KeyPairGenerator.getInstance(algorithm, "ZBC");
         // kpg.initialize(256);
         kpg.initialize(ECNamedCurveTable.getParameterSpec("P-256"));
         keyPair = kpg.genKeyPair();
         break;
       case KeyAgreementType.DH_MODE_EC38:
         algorithm = "ECDH";
         kpg = KeyPairGenerator.getInstance(algorithm, "ZBC");
         // kpg.initialize(384);
         kpg.initialize(ECNamedCurveTable.getParameterSpec("P-384"));
         keyPair = kpg.genKeyPair();
         break;
       default:
         break;
     }
     keyFactory = KeyFactory.getInstance(algorithm, "ZBC");
   } catch (Exception e) {
     e.printStackTrace();
   }
 }
  public void generateLocalKeyPair(String fullUserId) {

    String userId = Address.stripResource(fullUserId);

    OtrDebugLogger.log("generating local key pair for: " + userId);

    KeyPair keyPair;
    try {

      KeyPairGenerator kpg = KeyPairGenerator.getInstance(KEY_ALG);
      kpg.initialize(KEY_SIZE);

      keyPair = kpg.genKeyPair();
    } catch (NoSuchAlgorithmException e) {
      OtrDebugLogger.log("no such algorithm", e);
      return;
    }

    OtrDebugLogger.log("SUCCESS! generating local key pair for: " + userId);

    // Store Private Key.
    PrivateKey privKey = keyPair.getPrivate();
    PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(privKey.getEncoded());

    this.store.setProperty(userId + ".privateKey", pkcs8EncodedKeySpec.getEncoded());

    // Store Public Key.
    PublicKey pubKey = keyPair.getPublic();
    storeLocalPublicKey(userId, pubKey);

    store.save();
  }
  /*
   * Get a temporary RSA KeyPair.
   */
  KeyPair getRSAKeyPair(boolean export, SecureRandom random) {
    int length, index;
    if (ExportControl.hasStrongCrypto && !export) {
      length = 1024;
      index = INDEX_RSA512;
    } else {
      length = 512;
      index = INDEX_RSA1024;
    }

    KeyPair kp;
    EphemeralKeyPair ekp = keys[index];
    synchronized (ekp) {
      kp = ekp.getKeyPair();
      if (kp == null) {
        try {
          KeyPairGenerator kgen = KeyPairGenerator.getInstance("RSA");
          kgen.initialize(length, random);
          ekp = new EphemeralKeyPair(kgen.genKeyPair());
          kp = ekp.getKeyPair();
          keys[index] = ekp;
        } catch (Exception e) {
          // ignore
        }
      }
    }
    return kp;
  }
  @Test
  public void testApply() {
    final Crypto crypto = createMock(Crypto.class);
    KeyPairGenerator rsaKeyPairGenerator = createMock(KeyPairGenerator.class);
    final SecureRandom secureRandom = createMock(SecureRandom.class);

    expect(crypto.rsaKeyPairGenerator()).andReturn(rsaKeyPairGenerator);
    rsaKeyPairGenerator.initialize(2048, secureRandom);
    expect(rsaKeyPairGenerator.genKeyPair()).andReturn(keyPair);

    replay(crypto, rsaKeyPairGenerator, secureRandom);

    RsaSshKeyPairGenerator supplier =
        Guice.createInjector(
                new AbstractModule() {
                  protected void configure() {
                    bind(Crypto.class).toInstance(crypto);
                    bind(SecureRandom.class).toInstance(secureRandom);
                  }
                })
            .getInstance(RsaSshKeyPairGenerator.class);

    assertEquals(
        supplier.get(),
        ImmutableMap.of(
            "public", openSshKey, "private", PRIVATE_KEY.replaceAll("\n", lineSeparator)));

    verify(crypto, rsaKeyPairGenerator, secureRandom);
  }
Example #6
0
  public void init(int key_size) throws Exception {
    String name = null;
    if (key_size == 256) name = "secp256r1";
    else if (key_size == 384) name = "secp384r1";
    else if (key_size == 521) name = "secp521r1";
    else throw new JSchException("unsupported key size: " + key_size);

    for (int i = 0; i < 1000; i++) {
      KeyPairGenerator kpg = KeyPairGenerator.getInstance("EC");
      ECGenParameterSpec ecsp = new ECGenParameterSpec(name);
      kpg.initialize(ecsp);
      KeyPair kp = kpg.genKeyPair();
      prvKey = (ECPrivateKey) kp.getPrivate();
      pubKey = (ECPublicKey) kp.getPublic();
      params = pubKey.getParams();
      d = ((ECPrivateKey) prvKey).getS().toByteArray();
      ECPoint w = pubKey.getW();
      r = w.getAffineX().toByteArray();
      s = w.getAffineY().toByteArray();

      if (r.length != s.length) continue;
      if (key_size == 256 && r.length == 32) break;
      if (key_size == 384 && r.length == 48) break;
      if (key_size == 521 && r.length == 66) break;
    }
    if (d.length < r.length) {
      d = insert0(d);
    }
  }
Example #7
0
 public KeyPair generateKeyPair() {
   try {
     KeyPairGenerator generator = KeyPairGenerator.getInstance(ALGORITHM_RSA);
     generator.initialize(2048);
     return generator.genKeyPair();
   } catch (NoSuchAlgorithmException e) {
     throw new IllegalStateException(e);
   }
 }
 private static PrivateKey getPrivateKey() throws Exception {
   if (PRIVATE_KEY == null) {
     KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("DSA");
     keyPairGenerator.initialize(1024, new SecureRandom());
     KeyPair keyPair = keyPairGenerator.genKeyPair();
     PRIVATE_KEY = keyPair.getPrivate();
   }
   return PRIVATE_KEY;
 }
  public static void main(String args[]) {
    try {
      // ReceiveMessageInterface rmiclient;
      RmiServer server = new RmiServer();
      // rmiclient=(ReceiveMessageInterface)(registry.lookup("rmiclient"));
      // rmiclient.generateKeys(publicKey);
      KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
      keyGen.initialize(1024);
      KeyPair keypair = keyGen.genKeyPair();
      publicKey = keypair.getPublic();
      privateKey = keypair.getPrivate();

      BufferedImage image = ImageIO.read(new File("/home/subba/Desktop/test/iris1.bmp"));

      // write it to byte array in-memory (jpg format)
      ByteArrayOutputStream b = new ByteArrayOutputStream();
      ImageIO.write(image, "bmp", b);

      // do whatever with the array...
      byte[] jpgByteArray = b.toByteArray();

      // convert it to a String with 0s and 1s
      StringBuilder sb = new StringBuilder();
      int i = 0;
      for (byte by : jpgByteArray) {
        i++;
        if (i > 366) break;
        sb.append(Integer.toBinaryString(by & 0xFF));
      }
      sb.append("0000000000000000000000000000000000000000000");
      System.out.println(sb.toString().length());
      System.out.println(sb.toString());
      int token = 170;
      StringBuilder sb1 = new StringBuilder();
      sb1.append(Integer.toBinaryString(token));
      for (int j = 0; j < 102; j++) {
        sb1.append("00000000000000000000");
      }
      System.out.println("Binary is " + sb1.length());
      for (i = 0; i < sb.length(); i++) {
        bioTemplate.append(sb.charAt(i) ^ sb1.charAt(i));
      }

      /*MessageDigest digest = MessageDigest.getInstance("SHA-256");
      byte[] hashvalue=serviceProviderKey.getBytes();
      digest.update(hashvalue);
      Phashdigest=digest.digest();
      */

      securePassword = getSecurePassword(serviceProviderKey, "200");
      System.out.println(securePassword);
    } catch (Exception e) {
      e.printStackTrace();
      System.exit(1);
    }
  }
Example #10
0
  public static void requestToken(final Context context) throws Exception {

    // Generate RSA key pairs
    KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
    keyGen.initialize(1024);
    final KeyPair keypair = keyGen.genKeyPair();
    byte[] publicKey = keypair.getPublic().getEncoded();

    String public_key =
        "-----BEGIN PUBLIC KEY-----\\n"
            + Base64.encodeToString(publicKey, Base64.NO_WRAP)
            + "\\n-----END PUBLIC KEY-----\\n";

    // request Key
    String url = StateData.ServerAddress + "client/get_key";
    String data = "{\"public\":\"" + public_key + "\"}";

    Handler handler =
        new Handler() {
          public void handleMessage(Message msg) {
            try {
              String response = (String) msg.obj;
              // token parse
              if (!response.contains(ENC_DATA)) {
                Log.v("", "enc data does not exist");
                return;
              }
              String enc_data = Encryptor.getJsonToken(response, ENC_DATA);

              Cipher rsa;
              rsa = Cipher.getInstance("RSA");
              rsa.init(Cipher.DECRYPT_MODE, keypair.getPrivate());
              byte[] utf8 = rsa.doFinal(Base64.decode(enc_data, Base64.NO_WRAP));
              String enc_data2 = new String(utf8, "UTF8");

              Encryptor.baseKey = Encryptor.getJsonToken(enc_data2, "basekey");
              Encryptor.token = Encryptor.getJsonToken(enc_data2, "token");

              SharedPreferences prefs =
                  context.getSharedPreferences(Encryptor.ENCRYPTION, Context.MODE_PRIVATE);
              Editor editor = prefs.edit();
              editor.putString(Encryptor.ENCRYPTION_BASE_KEY, Encryptor.baseKey);
              editor.putString(Encryptor.ENCRYPTION_TOKEN, Encryptor.token);
              editor.commit();

            } catch (Exception e) {
              e.printStackTrace();
            }
          }
        };

    Network network = new Network();
    network.setNetworkOption(url, data, Method.POST, false);
    network.setHandler(handler);
    network.start();
  }
Example #11
0
 /**
  * 随机生成RSA密钥对
  *
  * @param keyLength 密钥长度,范围:512~2048<br>
  *     一般1024
  * @return
  */
 public static KeyPair generateRSAKeyPair(int keyLength) {
   try {
     KeyPairGenerator kpg = KeyPairGenerator.getInstance(RSA);
     kpg.initialize(keyLength);
     return kpg.genKeyPair();
   } catch (NoSuchAlgorithmException e) {
     e.printStackTrace();
     return null;
   }
 }
Example #12
0
  public static void main(String[] args) throws Exception {
    if (args.length != 3) {
      System.out.println("Usage: JwtGenerator <subject> <issuer> <audience>");
      System.exit(1);
    }

    KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
    keyGen.initialize(512);
    KeyPair keyPair = keyGen.genKeyPair();
    PublicKey publicKey = keyPair.getPublic();

    long validTime = System.currentTimeMillis() + 1000 * 60 * 60 * 24 / 2;
    String jwt =
        new JwtBuilderFactory()
            .jws(new SigningManager().newRsaSigningHandler(keyPair.getPrivate()))
            .headers()
            .alg(JwsAlgorithm.RS256)
            .done()
            .claims(
                new JwtClaimsSet(
                    json(object(
                            field("iss", args[0]),
                            field("sub", args[1]),
                            field("aud", args[2]),
                            field("exp", validTime / 1000)))
                        .asMap()))
            .build();
    System.out.println("JWT: " + jwt);

    Calendar expiry = Calendar.getInstance();
    expiry.add(Calendar.DAY_OF_YEAR, 7);

    X509CertInfo info = new X509CertInfo();
    CertificateValidity interval = new CertificateValidity(new Date(), new Date(validTime));
    BigInteger sn = new BigInteger(64, new SecureRandom());
    X500Name owner = new X500Name("CN=ForgeRock,L=Bristol,C=GB");

    info.set(X509CertInfo.VALIDITY, interval);
    info.set(X509CertInfo.SERIAL_NUMBER, new CertificateSerialNumber(sn));
    info.set(X509CertInfo.SUBJECT, new CertificateSubjectName(owner));
    info.set(X509CertInfo.ISSUER, new CertificateIssuerName(owner));
    info.set(X509CertInfo.KEY, new CertificateX509Key(publicKey));
    info.set(X509CertInfo.VERSION, new CertificateVersion(CertificateVersion.V3));
    AlgorithmId algo = new AlgorithmId(AlgorithmId.sha256WithRSAEncryption_oid);
    info.set(X509CertInfo.ALGORITHM_ID, new CertificateAlgorithmId(algo));

    // Sign the cert to identify the algorithm that's used.
    X509CertImpl cert = new X509CertImpl(info);
    cert.sign(keyPair.getPrivate(), "SHA256withRSA");
    System.out.println("Certificate:");
    BASE64Encoder encoder = new BASE64Encoder();
    System.out.println(X509Factory.BEGIN_CERT);
    encoder.encodeBuffer(cert.getEncoded(), System.out);
    System.out.println(X509Factory.END_CERT);
  }
 public void rsaCypher(String rString, InputStream inputStream, File directory)
     throws InvalidKeyException, NoSuchPaddingException, NoSuchAlgorithmException, IOException,
         BadPaddingException, IllegalBlockSizeException {
   kpg = KeyPairGenerator.getInstance("RSA");
   kpg.initialize(1024);
   kp = kpg.genKeyPair();
   privateKey = kp.getPrivate();
   cipher = Cipher.getInstance("RSA");
   File root = new File(Environment.getExternalStorageDirectory() + "/Notes/", "rsapublick.txt");
   // Read text from file
   if (root.exists()) {
     StringBuilder text = new StringBuilder();
     try {
       BufferedReader br = new BufferedReader(new FileReader(root));
       String line;
       while ((line = br.readLine()) != null) {
         text.append(line);
         text.append('\n');
       }
       br.close();
       byte[] keyBytes = Base64.decode(text.toString().getBytes("utf-8"), 0);
       X509EncodedKeySpec spec = new X509EncodedKeySpec(keyBytes);
       KeyFactory keyFactory = KeyFactory.getInstance("RSA");
       publicKey = keyFactory.generatePublic(spec);
     } catch (IOException e) {
       // You'll need to add proper error handling here
     } catch (InvalidKeySpecException e) {
       e.printStackTrace();
     }
   } else {
     publicKey = kp.getPublic();
     byte[] pKbytes = Base64.encode(publicKey.getEncoded(), 0);
     String pK = new String(pKbytes);
     String pubKey = "-----BEGIN public KEY-----\n" + pK + "-----END public KEY-----\n";
     System.out.println(pubKey);
     generateNoteOnSD("rsapublick.txt", pK, directorio);
   }
   this.cipher.init(Cipher.ENCRYPT_MODE, publicKey);
   byte[] bytes = getBytesFromInputStream(inputStream);
   byte[] encrypted = blockCipher(bytes, Cipher.ENCRYPT_MODE);
   FileOutputStream fileOutputStream = new FileOutputStream(directory);
   fileOutputStream.write(encrypted);
   fileOutputStream.close();
   System.out.println("Encryptado RSA Finalizado");
   root = new File(Environment.getExternalStorageDirectory() + "/Notes/", "rsaOrivatek.txt");
   if (!root.exists()) {
     byte[] pKbytes = Base64.encode(getPrivateKey().getEncoded(), 0);
     String pK = new String(pKbytes);
     String pubKey = "-----BEGIN private KEY-----\n" + pK + "-----END private KEY-----\n";
     System.out.println(pubKey);
     generateNoteOnSD("rsaOrivatek.txt", pK, directorio);
   }
 }
Example #14
0
 /** @return keyPair */
 public static KeyPair generateKeyPair() {
   long ts = System.currentTimeMillis();
   try {
     KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(KEY_ALGO, "BC");
     keyPairGenerator.initialize(1024);
     KeyPair keyPair = keyPairGenerator.genKeyPair();
     log.trace("Generate msgSignatureKeyPair needed {} ms", System.currentTimeMillis() - ts);
     return keyPair;
   } catch (NoSuchAlgorithmException | NoSuchProviderException e) {
     e.printStackTrace();
     throw new RuntimeException("Could not create key.");
   }
 }
  public static String Go(String rsa_len) throws NoSuchAlgorithmException {

    KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
    keyGen.initialize(Integer.valueOf(rsa_len));
    byte[] publicKey = keyGen.genKeyPair().getPublic().getEncoded();
    StringBuffer retString = new StringBuffer();

    for (int i = 0; i < publicKey.length; ++i) {
      retString.append(Integer.toHexString(0x0100 + (publicKey[i] & 0x00FF)).substring(1));
    }

    return retString.toString();
  }
Example #16
0
  public static KeyPair getRSAKeyPair() {
    KeyPairGenerator keyPairGenerator = null;
    KeyPair keyPair = null;

    try {
      keyPairGenerator = KeyPairGenerator.getInstance("RSA");
      keyPairGenerator.initialize(Constants.KEY_NO_OF_BITS);

      keyPair = keyPairGenerator.genKeyPair();
    } catch (NoSuchAlgorithmException e) {
      e.printStackTrace();
    }

    return keyPair;
  }
Example #17
0
 @Override
 public KeyPair getLocalKeyPair(SessionID arg0) throws OtrException {
   if (this.keyPair == null) {
     KeyPairGenerator kg;
     try {
       kg = KeyPairGenerator.getInstance("DSA");
       this.keyPair = kg.genKeyPair();
       this.saveKey();
       mXmppConnectionService.databaseBackend.updateAccount(account);
     } catch (NoSuchAlgorithmException e) {
       Log.d(Config.LOGTAG, "error generating key pair " + e.getMessage());
     }
   }
   return this.keyPair;
 }
Example #18
0
    public RSAKeyPair() {
      KeyPairGenerator keyGen = null;
      try {
        keyGen = KeyPairGenerator.getInstance("RSA");
      } catch (NoSuchAlgorithmException e) {
        throw new SolrException(SolrException.ErrorCode.SERVER_ERROR, e);
      }
      keyGen.initialize(512);
      java.security.KeyPair keyPair = keyGen.genKeyPair();
      privateKey = keyPair.getPrivate();
      publicKey = keyPair.getPublic();

      X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(publicKey.getEncoded());

      pubKeyStr = Base64.byteArrayToBase64(x509EncodedKeySpec.getEncoded());
    }
  private final KeyPair[] loadRSAKeys() {
    final KeyPair[] keyPairs = new KeyPair[KEYS_SIZE];

    try {
      final KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
      final RSAKeyGenParameterSpec spec =
          new RSAKeyGenParameterSpec(512, RSAKeyGenParameterSpec.F4);
      keyGen.initialize(spec);

      for (int i = 0; i < KEYS_SIZE; i++) {
        keyPairs[i] = keyGen.genKeyPair();
      }
    } catch (Exception e) {

    }

    return keyPairs;
  }
 @Security.Authenticated(SignedIn.class)
 public Result generateKey(String applicationId) throws IOException {
   Logger.info(String.format("Generating new key pair for %s", applicationId));
   KeyPair keyPair = keyPairGenerator.genKeyPair();
   Application app = Application.find.byId(applicationId);
   app.key = keyPair.getPublic().getEncoded();
   app.save();
   String filename = "privatekey-" + applicationId + ".pem";
   String filepath = "generated_keys/" + filename;
   File pemfile = new File(filepath);
   pemfile.getParentFile().mkdirs();
   PemObject pemObject = new PemObject(PEM_FILE_HEADER, keyPair.getPrivate().getEncoded());
   PemWriter writer = new PemWriter(new FileWriter(pemfile));
   writer.writeObject(pemObject);
   writer.flush();
   writer.close();
   response().setContentType("application/x-download");
   response().setHeader("Content-disposition", "attachment; filename=" + filename);
   return ok(pemfile);
 }
Example #21
0
  /**
   * 生成密钥对
   *
   * @return KeyPair
   * @throws Exception
   */
  public static KeyPair generateKeyPair() throws Exception {

    try {

      KeyPairGenerator keyPairGen =
          KeyPairGenerator.getInstance(
              "RSA", new org.bouncycastle.jce.provider.BouncyCastleProvider());

      final int KEY_SIZE = 1024; // 没什么好说的了,这个值关系到块加密的大小,可以更改,但是不要太大,否则效率会低

      keyPairGen.initialize(KEY_SIZE, new SecureRandom());

      KeyPair keyPair = keyPairGen.genKeyPair();

      return keyPair;

    } catch (Exception e) {

      throw new Exception(e.getMessage());
    }
  }
Example #22
0
  public static void Main() {
    try {
      String path = "C:/Users/LENOVO/workspace/RSA";

      KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");

      keyGen.initialize(4096);
      generatedKeyPair = keyGen.genKeyPair();

      // System.out.println("Generated Key Pair");
      // dumpKeyPair(generatedKeyPair);
      // SaveKeyPair(path, generatedKeyPair);

      // KeyPair loadedKeyPair = LoadKeyPair(path, "RSA");
      // System.out.println("Loaded Key Pair");
      // dumpKeyPair(loadedKeyPair);
    } catch (Exception e) {
      e.printStackTrace();
      return;
    }
  }
Example #23
0
  @Kroll.method
  public KrollDict generateKeyPair() {
    // generate key pair
    //
    KrollDict arg = new KrollDict();

    try {
      KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
      kpg.initialize(1024);
      KeyPair kp = kpg.genKeyPair();
      publicKey = kp.getPublic();
      privateKey = kp.getPrivate();

      arg.put("privateKey", Base64.encodeToString(privateKey.getEncoded(), Base64.NO_WRAP));
      arg.put("publicKey", Base64.encodeToString(publicKey.getEncoded(), Base64.NO_WRAP));

    } catch (Exception e) {
      Log.e(TAG, "RSA key pair error");
    }

    return arg;
  }
Example #24
0
  /*
   * 产生RSA公私钥对
   */
  public static void genRSAKeyPair() {
    KeyPairGenerator rsaKeyGen = null;
    KeyPair rsaKeyPair = null;
    try {
      System.out.println("Generating a pair of RSA key ... ");
      rsaKeyGen = KeyPairGenerator.getInstance("RSA");
      SecureRandom random = new SecureRandom();
      random.setSeed(System.currentTimeMillis());

      // rsaKeyGen.initialize(1024, random);
      rsaKeyGen.initialize(1024);
      rsaKeyPair = rsaKeyGen.genKeyPair();
      PublicKey rsaPublic = rsaKeyPair.getPublic();
      PrivateKey rsaPrivate = rsaKeyPair.getPrivate();

      System.out.println("公钥:" + bytesToHexStr(rsaPublic.getEncoded()));
      System.out.println("私钥:" + bytesToHexStr(rsaPrivate.getEncoded()));
      System.out.println("1024-bit RSA key GENERATED.");
    } catch (Exception e) {
      System.out.println("genRSAKeyPair:" + e);
    }
  }
  @Override
  public void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    response.setContentType("text/html");

    String param = "";
    boolean flag = true;
    java.util.Enumeration<String> names = request.getHeaderNames();
    while (names.hasMoreElements() && flag) {
      String name = (String) names.nextElement();
      java.util.Enumeration<String> values = request.getHeaders(name);
      if (values != null) {
        while (values.hasMoreElements() && flag) {
          String value = (String) values.nextElement();
          if (value.equals("vector")) {
            param = name;
            flag = false;
          }
        }
      }
    }

    String bar = new Test().doSomething(param);

    // Code based on example from:
    // http://examples.javacodegeeks.com/core-java/crypto/encrypt-decrypt-file-stream-with-des/

    try {
      javax.crypto.Cipher c = javax.crypto.Cipher.getInstance("RSA/ECB/PKCS1Padding", "SunJCE");
      // Prepare the cipher to encrypt
      java.security.KeyPairGenerator keyGen = java.security.KeyPairGenerator.getInstance("RSA");
      keyGen.initialize(1024);
      java.security.PublicKey publicKey = keyGen.genKeyPair().getPublic();
      c.init(javax.crypto.Cipher.ENCRYPT_MODE, publicKey);

      // encrypt and store the results
      byte[] input = {(byte) '?'};
      Object inputParam = bar;
      if (inputParam instanceof String) input = ((String) inputParam).getBytes();
      if (inputParam instanceof java.io.InputStream) {
        byte[] strInput = new byte[1000];
        int i = ((java.io.InputStream) inputParam).read(strInput);
        if (i == -1) {
          response
              .getWriter()
              .println(
                  "This input source requires a POST, not a GET. Incompatible UI for the InputStream source.");
          return;
        }
        input = java.util.Arrays.copyOf(strInput, i);
      }
      byte[] result = c.doFinal(input);

      java.io.File fileTarget =
          new java.io.File(
              new java.io.File(org.owasp.benchmark.helpers.Utils.testfileDir), "passwordFile.txt");
      java.io.FileWriter fw =
          new java.io.FileWriter(fileTarget, true); // the true will append the new data
      fw.write(
          "secret_value=" + org.owasp.esapi.ESAPI.encoder().encodeForBase64(result, true) + "\n");
      fw.close();
      response
          .getWriter()
          .println(
              "Sensitive value: '"
                  + org.owasp.esapi.ESAPI.encoder().encodeForHTML(new String(input))
                  + "' encrypted and stored<br/>");

    } catch (java.security.NoSuchAlgorithmException e) {
      response
          .getWriter()
          .println(
              "Problem executing crypto - javax.crypto.Cipher.getInstance(java.lang.String,java.security.Provider) Test Case");
      e.printStackTrace(response.getWriter());
      throw new ServletException(e);
    } catch (java.security.NoSuchProviderException e) {
      response
          .getWriter()
          .println(
              "Problem executing crypto - javax.crypto.Cipher.getInstance(java.lang.String,java.security.Provider) Test Case");
      e.printStackTrace(response.getWriter());
      throw new ServletException(e);
    } catch (javax.crypto.NoSuchPaddingException e) {
      response
          .getWriter()
          .println(
              "Problem executing crypto - javax.crypto.Cipher.getInstance(java.lang.String,java.security.Provider) Test Case");
      e.printStackTrace(response.getWriter());
      throw new ServletException(e);
    } catch (javax.crypto.IllegalBlockSizeException e) {
      response
          .getWriter()
          .println(
              "Problem executing crypto - javax.crypto.Cipher.getInstance(java.lang.String,java.security.Provider) Test Case");
      e.printStackTrace(response.getWriter());
      throw new ServletException(e);
    } catch (javax.crypto.BadPaddingException e) {
      response
          .getWriter()
          .println(
              "Problem executing crypto - javax.crypto.Cipher.getInstance(java.lang.String,java.security.Provider) Test Case");
      e.printStackTrace(response.getWriter());
      throw new ServletException(e);
    } catch (java.security.InvalidKeyException e) {
      response
          .getWriter()
          .println(
              "Problem executing crypto - javax.crypto.Cipher.getInstance(java.lang.String,java.security.Provider) Test Case");
      e.printStackTrace(response.getWriter());
      throw new ServletException(e);
    }
    response
        .getWriter()
        .println(
            "Crypto Test javax.crypto.Cipher.getInstance(java.lang.String,java.lang.String) executed");
  } // end doPost
  public static void testGenP12() throws Exception {

    String rootCerBase64 =
        "MIIDvTCCAqWgAwIBAgIEEioP6zANBgkqhkiG9w0BAQsFADCBjjELMAkGA1UEBhMC"
            + "Q04xETAPBgNVBAgTCHNoYW5naGFpMREwDwYDVQQHEwhzaGFuZ2hhaTEzMDEGA1UE"
            + "Cgwq5LiK5rW36YeR6bm/6YeR6J6N5L+h5oGv5pyN5Yqh5pyJ6ZmQ5YWs5Y+4MQsw"
            + "CQYDVQQLEwJJVDEXMBUGA1UEAxMOb3Blbi5qbGZleC5jb20wHhcNMTQwODIxMDM0"
            + "NTQ5WhcNMjQwODE4MDM0NTQ5WjCBjjELMAkGA1UEBhMCQ04xETAPBgNVBAgTCHNo"
            + "YW5naGFpMREwDwYDVQQHEwhzaGFuZ2hhaTEzMDEGA1UECgwq5LiK5rW36YeR6bm/"
            + "6YeR6J6N5L+h5oGv5pyN5Yqh5pyJ6ZmQ5YWs5Y+4MQswCQYDVQQLEwJJVDEXMBUG"
            + "A1UEAxMOb3Blbi5qbGZleC5jb20wggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEK"
            + "AoIBAQCQ4q4Yh8EPHbAP+BMiystXOEV56OE+IUwxSS7fRZ3ZrIEPImpnCiAe1txZ"
            + "vk0Lgv8ZWqrj4ErOT5FoOWfQW6Vva1DOXknCzFbypJMjqVnIS1/OwB64sYg4naLc"
            + "mM95GAHtEv9qxIWLbPhoLShz54znRNbM7mZJyT4BwLhKuKmfdo3UEuXvcoUFLN2l"
            + "f2wiTNmgMgpxcnCsWAx2nJaonPGCVXeQu0PXCVmCTyUUCWdT7P1io5yEpuRP/Dac"
            + "//g7Em8rkulgeO7e3gnEbrgrczsr2H1KJLTBjQmyWeWZg7LRYML6oHODrrDb0x++"
            + "yDT01p2BJHlvw/UzJq3I/CCci0lFAgMBAAGjITAfMB0GA1UdDgQWBBS1Lo57VqvU"
            + "BnfyJu51JO9csLJenjANBgkqhkiG9w0BAQsFAAOCAQEACcfPaVl5PIkBZ6cXyHuj"
            + "rJZkZH7Koqhx12DNeCoohdQkRda/gWeHVPsO7snK63sFhoY08OGVgvTRhgzwSBxJ"
            + "cx9GkCyojfHo5xZoOlSQ01PygyScd42DlseNiwXZGBfoxacLEYkIP6OXrDa+wNAP"
            + "gHnLI+37tzkafoPT0xoV/E9thvUUKX1jSIL5UCoGuso6FWLiZgDxD8wKgd22FcYo"
            + "T7B7DHG4R+0rgav81J9xjgOR3ayvNrb86iVvVBmrIiM7Gc2hf5PMiiAOaISST2cJ"
            + "x90X7TUA/f0qrYKveTvkRT77nLfzHV1a+PTS7PwkCXUt/NRm4VwseyGIgQ4FXH6W"
            + "zw==";

    // 解析root CA 证书
    X509Certificate rootcaCertificate =
        CertificateCoder.getX509Certificate(Base64.decodeBase64(rootCerBase64));
    // 解析root CA 私钥
    String rootcaDer = FileUtils.readFileToString(new File("d:\\rootcakey.pem"), "UTF-8");
    PrivateKey rootcaPrivateKey = PKCSCertificateCoder.getPrivateKeyFromPem(rootcaDer, "");
    System.out.println(rootcaPrivateKey);

    // 1.生成用户密钥对
    Security.addProvider(new BouncyCastleProvider());
    KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA", "BC");
    kpg.initialize(2048);
    KeyPair kp = kpg.genKeyPair();

    // 2.生成用户证书请求
    PKCS10CertificationRequest p10 = genPKCS10(kp);
    SubjectPublicKeyInfo subPublicKeyInfo = p10.getSubjectPublicKeyInfo();
    RSAKeyParameters rsa = (RSAKeyParameters) PublicKeyFactory.createKey(subPublicKeyInfo);
    RSAPublicKeySpec rsaSpec = new RSAPublicKeySpec(rsa.getModulus(), rsa.getExponent());
    KeyFactory kf = KeyFactory.getInstance("RSA");
    PublicKey publicKey = kf.generatePublic(rsaSpec);

    // 3.生成用户证书
    X509Certificate clientCertificate =
        buildEndEntityCert(publicKey, rootcaPrivateKey, rootcaCertificate);
    FileUtils.writeByteArrayToFile(new File("d:\\client.cer"), clientCertificate.getEncoded());

    // 4.生成用户p12文件
    storeP12(
        kp,
        new X509Certificate[] {clientCertificate, rootcaCertificate},
        "d:\\client.p12",
        "123456");

    FileOutputStream fos = new FileOutputStream(new File("d:\\client1.p12"));
    X509Certificate[] chain =
        new X509Certificate[] {rootcaCertificate, clientCertificate, clientCertificate};
    genPKCS12File(fos, kp.getPrivate(), chain);
  }
Example #27
0
  /** Generates a encrypted private key and certificate request. */
  public static void genCertificateRequest(
      String dname,
      String emailAddressOfCA,
      String password,
      String privKeyLoc,
      String certLoc,
      String certReqLoc)
      throws Exception {

    String sigAlgName = "MD5WithRSA";
    String keyAlgName = "RSA";

    CertUtil.init();

    // Generate a new key pair.
    KeyPairGenerator keygen = KeyPairGenerator.getInstance(keyAlgName);
    KeyPair keyPair = keygen.genKeyPair();
    PrivateKey privKey = keyPair.getPrivate();
    PublicKey pubKey = keyPair.getPublic();

    // Generate the certificate request.
    X509Name name = new X509Name(dname);
    DERConstructedSet derSet = new DERConstructedSet();
    PKCS10CertificationRequest request =
        new PKCS10CertificationRequest(sigAlgName, name, pubKey, derSet, privKey);

    // Save the certificate request to a .pem file.
    byte[] data = request.getEncoded();
    PrintStream ps = new PrintStream(new FileOutputStream(certReqLoc));

    // build / delimited name.
    String certSubject = "";
    StringTokenizer tokens = new StringTokenizer(dname, ",");
    while (tokens.hasMoreTokens()) {
      certSubject = certSubject + "/" + tokens.nextToken();
    }

    /*        ps.print( "\n\n"
    + "Please mail the following certificate request to " + emailAddressOfCA + "\n"
    + "\n"
    + "==================================================================\n"
    + "\n"
    + "Certificate Subject:\n"
    + "\n"
    + certSubject
    + "\n"
    + "\n"
    + "The above string is known as your user certificate subject, and it \n"
    + "uniquely identifies this user.\n"
    + "\n"
    + "To install this user certificate, please save this e-mail message\n"
    + "into the following file.\n"
    + "\n"
    + "\n"
    + certLoc
    + "\n"
    + "\n"
    + "\n"
    + "      You need not edit this message in any way. Simply \n"
    + "      save this e-mail message to the file.\n"
    + "\n"
    + "\n"
    + "If you have any questions about the certificate contact\n"
    + "the Certificate Authority at " + emailAddressOfCA + "\n"
    + "\n");*/
    ps.print(toPEM(data));
    ps.close();

    // Save private key to a .pem file.
    OpenSSLKey key = new BouncyCastleOpenSSLKey(privKey);
    if (password.length() != 0) {
      key.encrypt(password);
    }
    key.writeTo(new File(privKeyLoc).getAbsolutePath());
    // set read only permissions
    Util.setFilePermissions(privKeyLoc, 600);

    // Create an empty cert file.
    /*        File f = new File(certLoc);
    f.createNewFile();*/
  }
  public static void main(String[] args) throws Exception {
    // prompt user to enter a port number

    System.out.print("Enter the port number: ");
    Scanner scan = new Scanner(System.in);
    int port = scan.nextInt();
    scan.nextLine();
    System.out.print("Enter the host name: ");
    String hostName = scan.nextLine();

    // Initialize a key pair generator with the SKIP parameters we sepcified, and genrating a pair
    // This will take a while: 5...15 seconrds

    System.out.println("Generating a Diffie-Hellman keypair: ");
    KeyPairGenerator kpg = KeyPairGenerator.getInstance("DH");
    kpg.initialize(PARAMETER_SPEC);
    KeyPair keyPair = kpg.genKeyPair();
    System.out.println("key pair has been made...");

    // one the key pair has been generated, we want to listen on
    // a given port for a connection to come in
    // once we get a connection, we will get two streams, One for input
    // and one for output
    // open a port and wait for a connection

    ServerSocket ss = new ServerSocket(port);
    System.out.println("Listeining on port " + port + " ...");
    Socket socket = ss.accept();

    // use to output and input primitive data type

    DataOutputStream out = new DataOutputStream(socket.getOutputStream());

    // next thing to do is send our public key and receive client's
    // this corresponds to server step 3 and step 4 in the diagram

    System.out.println("Sending my public key...");
    byte[] keyBytes = keyPair.getPublic().getEncoded();
    out.writeInt(keyBytes.length);
    out.write(keyBytes);
    System.out.println("Server public key bytes: " + CryptoUtils.toHex(keyBytes));

    // receive the client's public key

    System.out.println("Receiving client's public key...");
    DataInputStream in = new DataInputStream(socket.getInputStream());
    keyBytes = new byte[in.readInt()];
    in.readFully(keyBytes);

    // create client's public key

    KeyFactory kf = KeyFactory.getInstance("DH");
    X509EncodedKeySpec x509Spec = new X509EncodedKeySpec(keyBytes);
    PublicKey clientPublicKey = kf.generatePublic(x509Spec);

    // print out client's public key bytes

    System.out.println(
        "Client public key bytes: " + CryptoUtils.toHex(clientPublicKey.getEncoded()));

    // we can now use the client's public key and
    // our own private key to perform the key agreement

    System.out.println("Performing the key agreement ... ");
    KeyAgreement ka = KeyAgreement.getInstance("DH");
    ka.init(keyPair.getPrivate());
    ka.doPhase(clientPublicKey, true);

    // in a chat application, each character is sendt over the wire, separetly encrypted,
    // Instead of using ECB, we are goin to use CFB, with a block size of 8 bits(1byte)
    // to send each character. We will encrypt the same character in a different way
    // each time. But in order to use CFB8, we need an IVof 8 bytes. We will create
    // that IV randomly and and send it to the client. It doesn't matter if somoene
    // eavesdrops on the IV when it is sent over the wire. it's not sensitive info

    // creating the IV and sending it corresponds to step 6 and 7

    byte[] iv = new byte[8];
    SecureRandom sr = new SecureRandom();
    sr.nextBytes(iv);
    out.write(iv);

    // we generate the secret byte array we share with the client and use it
    // to create the session key (Step 8)

    byte[] sessionKeyBytes = ka.generateSecret();

    // create the session key

    SecretKeyFactory skf = SecretKeyFactory.getInstance("DESede");
    DESedeKeySpec DESedeSpec = new DESedeKeySpec(sessionKeyBytes);
    SecretKey sessionKey = skf.generateSecret(DESedeSpec);

    // printout session key bytes

    System.out.println("Session key bytes: " + CryptoUtils.toHex(sessionKey.getEncoded()));

    // now use tha that session key and IV to create a CipherInputStream. We will use them to read
    // all character
    // that are sent to us by the client

    System.out.println("Creating the cipher stream ...");
    Cipher decrypter = Cipher.getInstance("DESede/CFB8/NoPadding");
    IvParameterSpec spec = new IvParameterSpec(iv);
    decrypter.init(Cipher.DECRYPT_MODE, sessionKey, spec);
    CipherInputStream cipherIn = new CipherInputStream(socket.getInputStream(), decrypter);

    // we just keep reading the input and print int to the screen, until -1 sent over

    int theCharacter = 0;
    theCharacter = cipherIn.read();
    while (theCharacter != -1) {
      System.out.print((char) theCharacter);
      theCharacter = cipherIn.read();
    }
    // once -1 is received we want to close up our stream and exit

    cipherIn.close();
    in.close();
    out.close();
    socket.close();
  }
 private KeyPair generateKeyPair(int keySize) throws NoSuchAlgorithmException {
   KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
   keyPairGenerator.initialize(keySize);
   return keyPairGenerator.genKeyPair();
 }
Example #30
0
 public static KeyPair generateKeyPair(String algorithm) throws NoSuchAlgorithmException {
   KeyPairGenerator keyGen = KeyPairGenerator.getInstance(algorithm);
   keyGen.initialize(1024);
   return keyGen.genKeyPair();
 }