private String generateSubjectKeyIdentifier(Certificate certificate) throws IOException {
    String subjectKeyIdentifier;
    ASN1InputStream is;
    SubjectPublicKeyInfo spki;
    SubjectKeyIdentifier ski;

    subjectKeyIdentifier = null;
    is = null;
    spki = null;
    ski = null;

    try {
      is = new ASN1InputStream(certificate.getPublicKey().getEncoded());

      spki = new SubjectPublicKeyInfo((ASN1Sequence) is.readObject());
      ski = new SubjectKeyIdentifier(spki);
    } finally {
      if (is != null) {
        is.close();
      }
    }

    subjectKeyIdentifier = new String(Hex.encode(ski.getKeyIdentifier()));

    return subjectKeyIdentifier;
  }
示例#2
0
  /**
   * Constructor from ASN1Sequence
   *
   * <p>the principal will be a list of constructed sets, each containing an (OID, String) pair.
   */
  public X509Name(ASN1Sequence seq) {
    this.seq = seq;

    Enumeration e = seq.getObjects();

    while (e.hasMoreElements()) {
      ASN1Set set = ASN1Set.getInstance(e.nextElement());

      for (int i = 0; i < set.size(); i++) {
        ASN1Sequence s = ASN1Sequence.getInstance(set.getObjectAt(i));

        if (s.size() != 2) {
          throw new IllegalArgumentException("badly sized pair");
        }

        ordering.addElement(DERObjectIdentifier.getInstance(s.getObjectAt(0)));

        DEREncodable value = s.getObjectAt(1);
        if (value instanceof DERString) {
          values.addElement(((DERString) value).getString());
        } else {
          values.addElement("#" + bytesToString(Hex.encode(value.getDERObject().getDEREncoded())));
        }
        added.addElement((i != 0) ? TRUE : FALSE); // to allow earlier JDK compatibility
      }
    }
  }
示例#3
0
  /**
   * Creates a test signature and verifies it.
   *
   * @param privateKey Private key to sign with
   * @param publicKey Public key to verify with
   * @param signatureProvider Name of provider to sign with
   * @throws NoSuchAlgorithmException In case the key or signature algorithm is unknown
   * @throws NoSuchProviderException In case the supplied provider name is unknown or BC is not
   *     installed
   * @throws InvalidKeyException If signature verification failed or the key was invalid
   * @throws SignatureException If the signature could not be made or verified correctly
   */
  public static void testSignAndVerify(
      PrivateKey privateKey, PublicKey publicKey, String signatureProvider)
      throws NoSuchAlgorithmException, NoSuchProviderException, InvalidKeyException,
          SignatureException {
    final byte input[] = "Lillan gick pa vagen ut, motte dar en katt...".getBytes();
    final String sigAlg = suggestSigAlg(publicKey);
    if (sigAlg == null) {
      throw new NoSuchAlgorithmException("Unknown key algorithm: " + publicKey.getAlgorithm());
    }
    if (LOG.isDebugEnabled()) {
      LOG.debug("Testing keys with algorithm: " + publicKey.getAlgorithm());
      LOG.debug("testSigAlg: " + sigAlg);
      LOG.debug("provider: " + signatureProvider);
      LOG.trace("privateKey: " + privateKey);
      LOG.trace("privateKey class: " + privateKey.getClass().getName());
      LOG.trace("publicKey: " + publicKey);
      LOG.trace("publicKey class: " + publicKey.getClass().getName());
    }
    final Signature signSignature = Signature.getInstance(sigAlg, signatureProvider);
    signSignature.initSign(privateKey);
    signSignature.update(input);
    byte[] signBA = signSignature.sign();
    if (LOG.isTraceEnabled()) {
      LOG.trace("Created signature of size: " + signBA.length);
      LOG.trace("Created signature: " + new String(Hex.encode(signBA)));
    }

    final Signature verifySignature = Signature.getInstance(sigAlg, "BC");
    verifySignature.initVerify(publicKey);
    verifySignature.update(input);
    if (!verifySignature.verify(signBA)) {
      throw new InvalidKeyException("Test signature inconsistent");
    }
  }
  public boolean EncryptMsg(String TobeEncrypted, String CertFile) throws Exception {
    reset();

    byte[] plain = TobeEncrypted.getBytes(encoding);
    byte[] iv = "12345678".getBytes(encoding);

    RSAKeyParameters rsaParams = null;
    rsaParams = getRSAKeyParameters(CertFile);

    BigInteger mod = rsaParams.getModulus();

    int keylen = mod.bitLength() / 8;
    if (plain.length > keylen - 11) {
      SecureRandom securerandom = new SecureRandom();
      DESedeKeyGenerator desedeKeyGenerator = new DESedeKeyGenerator();
      desedeKeyGenerator.init(new KeyGenerationParameters(securerandom, 192));
      byte[] key = desedeKeyGenerator.generateKey();
      if (key.length != 24) {
        throw new Exception("密钥长度不为24,加密失败");
      }

      byte[] encryptedPlain = new byte[plain.length];
      DESedeEngine desede = new DESedeEngine();
      BufferedBlockCipher bufferedBlockCipher =
          new BufferedBlockCipher(new OFBBlockCipher(desede, 8 * desede.getBlockSize()));
      CipherParameters desedeParams = new ParametersWithIV(new DESedeParameters(key), iv);
      bufferedBlockCipher.init(true, desedeParams);
      int outOff = bufferedBlockCipher.processBytes(plain, 0, plain.length, encryptedPlain, 0);
      bufferedBlockCipher.doFinal(encryptedPlain, outOff);
      byte[] encryptedKey = (byte[]) null;
      AsymmetricBlockCipher rsa = new PKCS1Encoding(new RSAEngine());
      rsa.init(true, rsaParams);
      encryptedKey = rsa.processBlock(key, 0, key.length);
      this.lastResult =
          new String(Hex.encode(iv))
              + new String(Hex.encode(encryptedKey))
              + new String(Hex.encode(encryptedPlain));
    } else {
      byte[] encrypted = (byte[]) null;
      AsymmetricBlockCipher rsa = new PKCS1Encoding(new RSAEngine());
      rsa.init(true, rsaParams);
      encrypted = rsa.processBlock(plain, 0, plain.length);
      this.lastResult = new String(Hex.encode(encrypted));
    }

    return true;
  }
示例#5
0
 public boolean isPublicKeyBlackListed(PublicKey publicKey) {
   byte[] encoded = publicKey.getEncoded();
   Digest digest = AndroidDigestFactory.getSHA1();
   digest.update(encoded, 0, encoded.length);
   byte[] out = new byte[digest.getDigestSize()];
   digest.doFinal(out, 0);
   for (byte[] blacklisted : pubkeyBlacklist) {
     if (Arrays.equals(blacklisted, Hex.encode(out))) {
       return true;
     }
   }
   return false;
 }
示例#6
0
 /**
  * Creates a SHA-1 hash for the public key.
  *
  * @param key to create hash for
  * @return Hex encoded hash
  */
 public static String createKeyHash(PublicKey key) {
   try {
     MessageDigest md = MessageDigest.getInstance("SHA1", "BC");
     final String res = new String(Hex.encode(md.digest(key.getEncoded())));
     return res;
   } catch (NoSuchProviderException ex) {
     final String message = "No such provider trying to hash public key";
     LOG.error(message, ex);
     throw new RuntimeException(message, ex);
   } catch (NoSuchAlgorithmException ex) {
     final String message = "No such algorithm trying to hash public key";
     LOG.error(message, ex);
     throw new RuntimeException(message, ex);
   }
 }
  private void showAdvancedInfo() {
    String certificate = null;
    // advanced info: package certificate SHA-256
    try {
      MessageDigest md = MessageDigest.getInstance("SHA-256");
      md.update(mAppSettings.getPackageCertificate());
      byte[] digest = md.digest();
      certificate = new String(Hex.encode(digest));
    } catch (NoSuchAlgorithmException e) {
      Log.e(Constants.TAG, "Should not happen!", e);
    }

    AdvancedAppSettingsDialogFragment dialogFragment =
        AdvancedAppSettingsDialogFragment.newInstance(mAppSettings.getPackageName(), certificate);

    dialogFragment.show(getSupportFragmentManager(), "advancedDialog");
  }
示例#8
0
  /**
   * Compute the Message Authentication Code (MAC) value over the supplied input.
   *
   * <p>It is up to the caller to ensure that the specified algorithm ID is consistent with the type
   * of signing key supplied.
   *
   * @param signingKey the key with which to compute the MAC
   * @param jcaAlgorithmID the Java JCA algorithm ID to use
   * @param input the input over which to compute the MAC
   * @return the computed MAC value
   * @throws SecurityException thrown if the MAC computation results in an error
   */
  public static byte[] signMAC(Key signingKey, String jcaAlgorithmID, byte[] input)
      throws SecurityException {
    log.debug(
        "Computing MAC over input using key of type {} and JCA algorithm ID {}",
        signingKey.getAlgorithm(),
        jcaAlgorithmID);

    try {
      Mac mac = Mac.getInstance(jcaAlgorithmID);
      mac.init(signingKey);
      mac.update(input);
      byte[] rawMAC = mac.doFinal();
      log.debug("Computed MAC: {}", new String(Hex.encode(rawMAC)));
      return rawMAC;
    } catch (GeneralSecurityException e) {
      log.error("Error during MAC generation", e);
      throw new SecurityException("Error during MAC generation", e);
    }
  }
示例#9
0
  /**
   * Compute the raw signature value over the supplied input.
   *
   * <p>It is up to the caller to ensure that the specified algorithm ID is consistent with the type
   * of signing key supplied.
   *
   * @param signingKey the private key with which to compute the signature
   * @param jcaAlgorithmID the Java JCA algorithm ID to use
   * @param input the input over which to compute the signature
   * @return the computed signature value
   * @throws SecurityException thrown if the signature computation results in an error
   */
  public static byte[] sign(PrivateKey signingKey, String jcaAlgorithmID, byte[] input)
      throws SecurityException {
    log.debug(
        "Computing signature over input using private key of type {} and JCA algorithm ID {}",
        signingKey.getAlgorithm(),
        jcaAlgorithmID);

    try {
      Signature signature = Signature.getInstance(jcaAlgorithmID);
      signature.initSign(signingKey);
      signature.update(input);
      byte[] rawSignature = signature.sign();
      log.debug("Computed signature: {}", new String(Hex.encode(rawSignature)));
      return rawSignature;
    } catch (GeneralSecurityException e) {
      log.error("Error during signature generation", e);
      throw new SecurityException("Error during signature generation", e);
    }
  }
示例#10
0
  /**
   * Sign some data with my private key, so that others can verify it.
   *
   * @param data
   * @return
   */
  public static String sign(String data) {
    String sign = null;
    try {
      Signature signature = Signature.getInstance("SHA256WithRSAEncryption");

      signature.initSign(getKey().getPrivate());

      signature.update(data.getBytes());
      byte[] signatureBytes = signature.sign();
      sign = new String(Hex.encode(signatureBytes));
    } catch (InvalidKeyException e) {
      logger.error("FATAL: couldn't sign with private key", e);
    } catch (SignatureException e) {
      logger.error("FATAL: couldn't sign with private key", e);
    } catch (NoSuchAlgorithmException e) {
      logger.error("FATAL: couldn't sign with private key", e);
    }
    return sign;
  }
示例#11
0
  public void testECB(int strength, byte[] keyBytes, byte[] input, byte[] output) throws Exception {
    Key key;
    Cipher in, out;
    CipherInputStream cIn;
    CipherOutputStream cOut;
    ByteArrayInputStream bIn;
    ByteArrayOutputStream bOut;

    key = new SecretKeySpec(keyBytes, "GOST28147");

    in = Cipher.getInstance("GOST28147/ECB/NoPadding", "BC");
    out = Cipher.getInstance("GOST28147/ECB/NoPadding", "BC");
    out.init(Cipher.ENCRYPT_MODE, key);
    in.init(Cipher.DECRYPT_MODE, key);

    //
    // encryption pass
    //
    bOut = new ByteArrayOutputStream();

    cOut = new CipherOutputStream(bOut, out);

    for (int i = 0; i != input.length / 2; i++) {
      cOut.write(input[i]);
    }
    cOut.write(input, input.length / 2, input.length - input.length / 2);
    cOut.close();

    byte[] bytes;

    bytes = bOut.toByteArray();

    if (!areEqual(bytes, output)) {
      fail(
          "GOST28147 failed encryption - expected "
              + new String(Hex.encode(output))
              + " got "
              + new String(Hex.encode(bytes)));
    }

    //
    // decryption pass
    //
    bIn = new ByteArrayInputStream(bytes);

    cIn = new CipherInputStream(bIn, in);

    DataInputStream dIn = new DataInputStream(cIn);

    bytes = new byte[input.length];

    for (int i = 0; i != input.length / 2; i++) {
      bytes[i] = (byte) dIn.read();
    }
    dIn.readFully(bytes, input.length / 2, bytes.length - input.length / 2);

    if (!areEqual(bytes, input)) {
      fail(
          "GOST28147 failed decryption - expected "
              + new String(Hex.encode(input))
              + " got "
              + new String(Hex.encode(bytes)));
    }
  }
示例#12
0
 private static void writeHexEncoded(BufferedWriter out, byte[] bytes) throws IOException {
   bytes = Hex.encode(bytes);
   for (int i = 0; i != bytes.length; i++) {
     out.write((char) bytes[i]);
   }
 }
示例#13
0
  /**
   * Returns a string representation of this CRL.
   *
   * @return a string representation of this CRL.
   */
  public String toString() {
    StringBuffer buf = new StringBuffer();
    String nl = System.getProperty("line.separator");

    buf.append("              Version: ").append(this.getVersion()).append(nl);
    buf.append("             IssuerDN: ").append(this.getIssuerDN()).append(nl);
    buf.append("          This update: ").append(this.getThisUpdate()).append(nl);
    buf.append("          Next update: ").append(this.getNextUpdate()).append(nl);
    buf.append("  Signature Algorithm: ").append(this.getSigAlgName()).append(nl);

    byte[] sig = this.getSignature();

    buf.append("            Signature: ").append(new String(Hex.encode(sig, 0, 20))).append(nl);
    for (int i = 20; i < sig.length; i += 20) {
      if (i < sig.length - 20) {
        buf.append("                       ").append(new String(Hex.encode(sig, i, 20))).append(nl);
      } else {
        buf.append("                       ")
            .append(new String(Hex.encode(sig, i, sig.length - i)))
            .append(nl);
      }
    }

    Extensions extensions = c.getTBSCertList().getExtensions();

    if (extensions != null) {
      Enumeration e = extensions.oids();

      if (e.hasMoreElements()) {
        buf.append("           Extensions: ").append(nl);
      }

      while (e.hasMoreElements()) {
        ASN1ObjectIdentifier oid = (ASN1ObjectIdentifier) e.nextElement();
        Extension ext = extensions.getExtension(oid);

        if (ext.getExtnValue() != null) {
          byte[] octs = ext.getExtnValue().getOctets();
          ASN1InputStream dIn = new ASN1InputStream(octs);
          buf.append("                       critical(").append(ext.isCritical()).append(") ");
          try {
            if (oid.equals(Extension.cRLNumber)) {
              buf.append(
                      new CRLNumber(ASN1Integer.getInstance(dIn.readObject()).getPositiveValue()))
                  .append(nl);
            } else if (oid.equals(Extension.deltaCRLIndicator)) {
              buf.append(
                      "Base CRL: "
                          + new CRLNumber(
                              ASN1Integer.getInstance(dIn.readObject()).getPositiveValue()))
                  .append(nl);
            } else if (oid.equals(Extension.issuingDistributionPoint)) {
              buf.append(IssuingDistributionPoint.getInstance(dIn.readObject())).append(nl);
            } else if (oid.equals(Extension.cRLDistributionPoints)) {
              buf.append(CRLDistPoint.getInstance(dIn.readObject())).append(nl);
            } else if (oid.equals(Extension.freshestCRL)) {
              buf.append(CRLDistPoint.getInstance(dIn.readObject())).append(nl);
            } else {
              buf.append(oid.getId());
              buf.append(" value = ").append(ASN1Dump.dumpAsString(dIn.readObject())).append(nl);
            }
          } catch (Exception ex) {
            buf.append(oid.getId());
            buf.append(" value = ").append("*****").append(nl);
          }
        } else {
          buf.append(nl);
        }
      }
    }
    Set set = getRevokedCertificates();
    if (set != null) {
      Iterator it = set.iterator();
      while (it.hasNext()) {
        buf.append(it.next());
        buf.append(nl);
      }
    }
    return buf.toString();
  }
示例#14
0
 /**
  * Hex-encodes the given byte array.
  *
  * @param data the value to encode
  * @return hex encoded String of the data
  */
 public static String encodeHex(byte[] data) {
   return new String(Hex.encode(data));
 }
示例#15
0
 /**
  * This is a general purpose checksum generator method.
  *
  * @param digest Any class that extends {@link GeneralDigest}.
  * @param bytes bytes on which the checksum is to be generated.
  * @return checksum as per the digest.
  * @see CryptoHelper#generateMD5Checksum(byte[])
  * @see CryptoHelper#generateMD5Checksum(InputStream)
  * @see CryptoHelper#generateMD5Checksum(String)
  * @see CryptoHelper#generateSHA1Checksum(byte[])
  * @see CryptoHelper#generateSHA1Checksum(InputStream)
  * @see CryptoHelper#generateSHA1Checksum(String)
  */
 public static String generateChecksum(GeneralDigest digest, byte[] bytes) {
   digest.update(bytes, 0, bytes.length);
   byte[] checkSum = new byte[digest.getDigestSize()];
   digest.doFinal(checkSum, 0);
   return toString(Hex.encode(checkSum));
 }
示例#16
0
  //
  // ONE TIME ADD WARRANTS
  //
  //
  private static void oneTimeAddWarrants() {

    String jsonString = "";

    try {
      jsonString = readFile("./json/warrants.json", StandardCharsets.UTF_8);
    } catch (IOException e) {
      System.out.println(e);
    }

    try {
      JSONObject rootObject = new JSONObject(jsonString); // Parse the JSON to a JSONObject
      JSONArray rows = rootObject.getJSONArray("stuff"); // Get all JSONArray rows

      // System.out.println("row lengths: " + rows.length());

      set2 = new HashSet<>();

      for (int j = 0; j < rows.length(); j++) { // Iterate each element in the elements array
        JSONObject element = rows.getJSONObject(j); // Get the element object

        String defendant = element.getString("Defendant");

        String strarr[] = defendant.split(" ");
        String temp = strarr[1];
        int len = strarr[0].length();
        strarr[0] = strarr[0].substring(0, len - 1);
        strarr[1] = strarr[0];
        strarr[0] = temp;

        String firstLast = strarr[0] + strarr[1];
        firstLast = firstLast.toLowerCase();

        set2.add(firstLast);
        // System.out.println(firstLast);

        int zipCode = 0;
        Boolean isZipCodeNull = element.isNull("ZIP Code");
        if (!isZipCodeNull) zipCode = element.getInt("ZIP Code");
        String dob = element.getString("Date of Birth");
        String caseNumber = element.getString("Case Number");

        String firstLastDOB = firstLast + dob;

        // pick a ssn from list
        String ssn = ssnList.get(ssnCounter);
        ssnCounter--;
        ssnHashMap.put(firstLast, ssn);

        // compute salt
        final Random ran = new SecureRandom();
        byte[] salt = new byte[32];
        ran.nextBytes(salt);
        String saltString = Base64.encodeBase64String(salt);

        // System.out.println("saltstring: " + saltString);
        saltHashMap.put(firstLast, saltString);

        // compute ripemd160 hash of ssn + salt
        String saltPlusSsn = saltString + ssn;
        // System.out.println("salt plus ssn: " + saltPlusSsn);

        String resultingHash = "";
        try {
          byte[] r = saltPlusSsn.getBytes("US-ASCII");
          RIPEMD160Digest d = new RIPEMD160Digest();
          d.update(r, 0, r.length);
          byte[] o = new byte[d.getDigestSize()];
          d.doFinal(o, 0);
          ByteArrayOutputStream baos = new ByteArrayOutputStream(40);
          Hex.encode(o, baos);
          resultingHash = new String(baos.toByteArray(), StandardCharsets.UTF_8);

          hashedssnHashMap.put(firstLast, resultingHash);
        } catch (UnsupportedEncodingException e) {
          System.out.println(e);
        } catch (IOException i) {
          System.out.println(i);
        }

        // compareNames();

        Map<String, AttributeValue> item =
            newWarrantItem(
                firstLast, firstLastDOB, resultingHash, defendant, zipCode, dob, caseNumber);
        PutItemRequest putItemRequest = new PutItemRequest("warrants-table", item);
        PutItemResult putItemResult = dynamoDB.putItem(putItemRequest);
      }
    } catch (JSONException e) {
      // JSON Parsing error
      e.printStackTrace();
    }
  }
示例#17
0
  //
  // ONE TIME ADD CITATIONS
  //
  //
  private static void oneTimeAddCitations() {

    String jsonString = "";

    try {
      jsonString = readFile("./json/citations.json", StandardCharsets.UTF_8);
    } catch (IOException e) {
      System.out.println(e);
    }

    try {
      JSONObject rootObject = new JSONObject(jsonString); // Parse the JSON to a JSONObject
      JSONArray rows = rootObject.getJSONArray("stuff"); // Get all JSONArray rows

      System.out.println("row lengths: " + rows.length());

      set1 = new HashSet<>();

      for (int j = 0; j < rows.length(); j++) { // Iterate each element in the elements array
        JSONObject element = rows.getJSONObject(j); // Get the element object

        int id = element.getInt("id");
        int citationNumber = element.getInt("citation_number");
        String citationDate = " ";
        Boolean isCitationDateNull = element.isNull("citation_date");
        if (!isCitationDateNull) citationDate = element.getString("citation_date");
        String firstName = element.getString("first_name");
        String lastName = element.getString("last_name");
        String firstLastName = firstName + lastName;
        firstLastName = firstLastName.toLowerCase();
        set1.add(firstLastName);

        // System.out.println(firstLastName);
        String dob = " ";
        Boolean isDobNull = element.isNull("date_of_birth");
        if (!isDobNull) {
          dob = element.getString("date_of_birth");
          dob = (dob.split(" "))[0];
        }

        // pick a ssn from list
        String ssn = ssnList.get(ssnCounter);
        ssnCounter--;
        ssnHashMap.put(firstLastName, ssn);

        System.out.println(firstLastName + " " + ssn);

        // compute salt
        final Random ran = new SecureRandom();
        byte[] salt = new byte[32];
        ran.nextBytes(salt);
        String saltString = Base64.encodeBase64String(salt);

        // System.out.println("saltstring: " + saltString);
        saltHashMap.put(firstLastName, saltString);

        // compute ripemd160 hash of ssn + salt
        String saltPlusSsn = saltString + ssn;
        // System.out.println("salt plus ssn: " + saltPlusSsn);

        String resultingHash = "";
        try {
          byte[] r = saltPlusSsn.getBytes("US-ASCII");
          RIPEMD160Digest d = new RIPEMD160Digest();
          d.update(r, 0, r.length);
          byte[] o = new byte[d.getDigestSize()];
          d.doFinal(o, 0);
          ByteArrayOutputStream baos = new ByteArrayOutputStream(40);
          Hex.encode(o, baos);
          resultingHash = new String(baos.toByteArray(), StandardCharsets.UTF_8);

          hashedssnHashMap.put(firstLastName, resultingHash);
        } catch (UnsupportedEncodingException e) {
          System.out.println(e);
        } catch (IOException i) {
          System.out.println(i);
        }

        String fldob = firstLastName + dob;
        String da = " ";
        Boolean isDaNull = element.isNull("defendant_address");
        if (!isDaNull) da = element.getString("defendant_address");
        String dc = " ";
        Boolean isDcNull = element.isNull("defendant_city");
        if (!isDcNull) dc = element.getString("defendant_city");
        String ds = " ";
        Boolean isDsNull = element.isNull("defendant_state");
        if (!isDsNull) ds = element.getString("defendant_state");
        String dln = " ";
        Boolean isDlnNull = element.isNull("drivers_license_number");
        if (!isDlnNull) dln = element.getString("drivers_license_number");
        String cd = " ";
        Boolean isCdNull = element.isNull("court_date");
        if (!isCdNull) cd = element.getString("court_date");
        String cl = " ";
        Boolean isClNull = element.isNull("court_location");
        if (!isClNull) cl = element.getString("court_location");
        String ca = " ";
        Boolean isCaNull = element.isNull("court_address");
        if (!isCaNull) ca = element.getString("court_address");
        /*
        Map<String, AttributeValue> item = newCitationItem(citationNumber, citationDate, firstName, lastName, firstLastName, dob, fldob, resultingHash, da, dc, ds, dln, cd, cl, ca);
        PutItemRequest putItemRequest = new PutItemRequest("citations-table", item);
        PutItemResult putItemResult = dynamoDB.putItem(putItemRequest);
        */
      }
    } catch (JSONException e) {
      // JSON Parsing error
      e.printStackTrace();
    }
  }
示例#18
0
  @Override
  protected void doPost(HttpServletRequest req, HttpServletResponse resp)
      throws ServletException, IOException {

    //
    // If OSS is already initialized, bail out
    //

    if (OSS.isInitialized()) {
      resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "Open Secret Server already initialized.");
      return;
    }

    //
    // Extract token
    //

    String b64token = req.getParameter("token");

    //
    // Decode it from base64
    //

    byte[] token = Base64.decode(b64token);

    //
    // Extract wrapped init token and sealed AES key
    //

    byte[] wrappedtoken = CryptoHelper.decodeNetworkString(token, 0);
    byte[] sealedaeskey = CryptoHelper.decodeNetworkString(token, wrappedtoken.length + 4);

    //
    // Unseal AES key
    //

    byte[] aeskey = CryptoHelper.decryptRSA(OSS.getSessionRSAPrivateKey(), sealedaeskey);

    //
    // Unwrap init token
    //

    byte[] inittoken = CryptoHelper.unwrapAES(aeskey, wrappedtoken);

    //
    // Check OSS Token
    //

    OSS.OSSToken osstoken = null;

    try {
      osstoken = OSS.checkToken(inittoken);
    } catch (OSSException osse) {
      LOGGER.error("doPost", osse);
      resp.sendError(HttpServletResponse.SC_BAD_REQUEST, osse.getMessage());
      return;
    }

    //
    // Check signing key fingerprint
    //

    if (!OSS.checkInitSSHKey(osstoken.getKeyblob())) {
      LOGGER.error(
          "["
              + new String(Hex.encode(CryptoHelper.sshKeyBlobFingerprint(osstoken.getKeyblob())))
              + "] (unauthorized) attempted to initialize Open Secret Server.");
      resp.sendError(
          HttpServletResponse.SC_FORBIDDEN,
          "SSH signing key is not authorized to initialize this Open Secret Server.");
      return;
    }

    //
    // Add secret to initialization
    //

    try {
      OSS.init(osstoken.getSecret());
    } catch (OSSException osse) {
      LOGGER.error("doPost", osse);
      resp.sendError(HttpServletResponse.SC_BAD_REQUEST, osse.getMessage());
      return;
    }

    if (!OSS.isInitialized()) {
      LOGGER.info(
          "["
              + new String(Hex.encode(CryptoHelper.sshKeyBlobFingerprint(osstoken.getKeyblob())))
              + "] added secret to intialize Open Secret Server.");
      resp.sendError(
          HttpServletResponse.SC_ACCEPTED,
          "Open Secret Server not yet initialized, needs some more secrets.");
      return;
    } else {
      LOGGER.info(
          "["
              + new String(Hex.encode(CryptoHelper.sshKeyBlobFingerprint(osstoken.getKeyblob())))
              + "] completed intialization of Open Secret Server.");
    }

    resp.setStatus(HttpServletResponse.SC_OK);
  }