Ejemplo n.º 1
0
  /*
   * Check for a valid certificate pair
   */
  private void checkPair() throws CertificateException {

    /* if either of pair is missing, return w/o error */
    if (forward == null || reverse == null) {
      return;
    }
    /*
     * If both elements of the pair are present, check that they
     * are a valid pair.
     */
    X500Principal fwSubject = forward.getSubjectX500Principal();
    X500Principal fwIssuer = forward.getIssuerX500Principal();
    X500Principal rvSubject = reverse.getSubjectX500Principal();
    X500Principal rvIssuer = reverse.getIssuerX500Principal();
    if (!fwIssuer.equals(rvSubject) || !rvIssuer.equals(fwSubject)) {
      throw new CertificateException(
          "subject and issuer names in " + "forward and reverse certificates do not match");
    }

    /* check signatures unless key parameters are missing */
    try {
      PublicKey pk = reverse.getPublicKey();
      if (!(pk instanceof DSAPublicKey) || ((DSAPublicKey) pk).getParams() != null) {
        forward.verify(pk);
      }
      pk = forward.getPublicKey();
      if (!(pk instanceof DSAPublicKey) || ((DSAPublicKey) pk).getParams() != null) {
        reverse.verify(pk);
      }
    } catch (GeneralSecurityException e) {
      throw new CertificateException("invalid signature: " + e.getMessage());
    }
  }
Ejemplo n.º 2
0
 private static void writePemEncrypted(
     BufferedWriter out, String pemHeader, byte[] encoding, CipherSpec cipher, char[] passwd)
     throws IOException {
   Cipher c = cipher.getCipher();
   byte[] iv = new byte[c.getBlockSize()];
   random.nextBytes(iv);
   byte[] salt = new byte[8];
   System.arraycopy(iv, 0, salt, 0, 8);
   OpenSSLPBEParametersGenerator pGen = new OpenSSLPBEParametersGenerator();
   pGen.init(PBEParametersGenerator.PKCS5PasswordToBytes(passwd), salt);
   KeyParameter param = (KeyParameter) pGen.generateDerivedParameters(cipher.getKeyLenInBits());
   SecretKey secretKey =
       new SecretKeySpec(
           param.getKey(), org.jruby.ext.openssl.Cipher.Algorithm.getAlgorithmBase(c));
   byte[] encData = null;
   try {
     c.init(Cipher.ENCRYPT_MODE, secretKey, new IvParameterSpec(iv));
     encData = c.doFinal(encoding);
   } catch (GeneralSecurityException gse) {
     throw new IOException("exception using cipher: " + gse.toString());
   }
   out.write(BEF_G + pemHeader + AFT);
   out.newLine();
   out.write("Proc-Type: 4,ENCRYPTED");
   out.newLine();
   out.write("DEK-Info: " + cipher.getOsslName() + ",");
   writeHexEncoded(out, iv);
   out.newLine();
   out.newLine();
   writeEncoded(out, encData);
   out.write(BEF_E + pemHeader + AFT);
   out.flush();
 }
Ejemplo n.º 3
0
  @JRubyMethod(name = "sign")
  public IRubyObject sign(IRubyObject digest, IRubyObject data) {
    if (!this.callMethod(getRuntime().getCurrentContext(), "private?").isTrue()) {
      throw getRuntime().newArgumentError("Private key is needed.");
    }
    String digAlg = ((Digest) digest).getShortAlgorithm();
    try {
      Signature signature = SecurityHelper.getSignature(digAlg + "WITH" + getAlgorithm());
      signature.initSign(getPrivateKey());
      byte[] inp = data.convertToString().getBytes();
      signature.update(inp);
      byte[] sigge = signature.sign();
      return RubyString.newString(getRuntime(), sigge);
    } catch (GeneralSecurityException gse) {
      throw newPKeyError(getRuntime(), gse.getMessage());
    }
    /*
    GetPKey(self, pkey);
    EVP_SignInit(&ctx, GetDigestPtr(digest));
    StringValue(data);
    EVP_SignUpdate(&ctx, RSTRING(data)->ptr, RSTRING(data)->len);
    str = rb_str_new(0, EVP_PKEY_size(pkey)+16);
    if (!EVP_SignFinal(&ctx, RSTRING(str)->ptr, &buf_len, pkey))
    ossl_raise(ePKeyError, NULL);
    assert(buf_len <= RSTRING(str)->len);
    RSTRING(str)->len = buf_len;
    RSTRING(str)->ptr[buf_len] = 0;

    return str;
         */
  }
Ejemplo n.º 4
0
  Cipher createAsymmetricWrapper(ASN1ObjectIdentifier algorithm, Map extraAlgNames)
      throws OperatorCreationException {
    try {
      String cipherName = null;

      if (!extraAlgNames.isEmpty()) {
        cipherName = (String) extraAlgNames.get(algorithm);
      }

      if (cipherName == null) {
        cipherName = (String) asymmetricWrapperAlgNames.get(algorithm);
      }

      if (cipherName != null) {
        try {
          // this is reversed as the Sun policy files now allow unlimited strength RSA
          return helper.createCipher(cipherName);
        } catch (NoSuchAlgorithmException e) {
          // try alternate for RSA
          if (cipherName.equals("RSA/ECB/PKCS1Padding")) {
            try {
              return helper.createCipher("RSA/NONE/PKCS1Padding");
            } catch (NoSuchAlgorithmException ex) {
              // Ignore
            }
          }
          // Ignore
        }
      }

      return helper.createCipher(algorithm.getId());
    } catch (GeneralSecurityException e) {
      throw new OperatorCreationException("cannot create cipher: " + e.getMessage(), e);
    }
  }
Ejemplo n.º 5
0
  public SSLContext getSSLContext() {
    TrustManager mytm[] = null;
    KeyManager mykm[] = null;

    try {
      if (UtilMethods.isSet(truststore_path) && UtilMethods.isSet(truststore_password)) {
        mytm =
            new TrustManager[] {
              new MyX509TrustManager(truststore_path, truststore_password.toCharArray())
            };
      }

      if (UtilMethods.isSet(keystore_path) && UtilMethods.isSet(keystore_password)) {
        mykm =
            new KeyManager[] {new MyX509KeyManager(keystore_path, keystore_password.toCharArray())};
      }
    } catch (Exception ex) {
      Logger.error(this.getClass(), ex.toString());
      Logger.debug(this.getClass(), ex.getMessage(), ex);
    }

    SSLContext ctx = null;
    try {
      ctx = SSLContext.getInstance("SSL");
      ctx.init(mykm, mytm, null);
    } catch (java.security.GeneralSecurityException ex) {
      Logger.error(this.getClass(), ex.getMessage(), ex);
    }
    return ctx;
  }
Ejemplo n.º 6
0
 private KeyManager[] getKeyManagers(InputStream certificate, String passphrase)
     throws IOException {
   if (key_managers == null) {
     KeyStore ks;
     try {
       ks = KeyStore.getInstance("PKCS12");
     } catch (KeyStoreException e) {
       throw new RuntimeException("Unable to create key store.");
     }
     char certphrase[] = passphrase.toCharArray();
     try {
       ks.load(certificate, certphrase);
     } catch (GeneralSecurityException e) {
       throw new RuntimeException("Bad certificate or unknown type.");
     } finally {
       closeQuietly(certificate);
     }
     KeyManagerFactory kmf;
     try {
       kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
       kmf.init(ks, certphrase);
     } catch (GeneralSecurityException e) {
       throw new RuntimeException(e.getMessage());
     }
     key_managers = kmf.getKeyManagers();
   }
   return key_managers;
 }
Ejemplo n.º 7
0
  private void setSignatureParameters(Signature var1, DEREncodable var2)
      throws NoSuchAlgorithmException, SignatureException, InvalidKeyException {
    if (var2 != null) {
      if (!DERNull.INSTANCE.equals(var2)) {
        String var3 = var1.getAlgorithm();
        Provider var4 = var1.getProvider();
        AlgorithmParameters var5 = AlgorithmParameters.getInstance(var3, var4);

        try {
          byte[] var6 = var2.getDERObject().getDEREncoded();
          var5.init(var6);
        } catch (IOException var17) {
          StringBuilder var9 = (new StringBuilder()).append("IOException decoding parameters: ");
          String var10 = var17.getMessage();
          String var11 = var9.append(var10).toString();
          throw new SignatureException(var11);
        }

        if (var1.getAlgorithm().endsWith("MGF1")) {
          try {
            AlgorithmParameterSpec var7 = var5.getParameterSpec(PSSParameterSpec.class);
            var1.setParameter(var7);
          } catch (GeneralSecurityException var16) {
            StringBuilder var13 = (new StringBuilder()).append("Exception extracting parameters: ");
            String var14 = var16.getMessage();
            String var15 = var13.append(var14).toString();
            throw new SignatureException(var15);
          }
        }
      }
    }
  }
Ejemplo n.º 8
0
  public int read(byte[] b, int off, int len) throws IOException {
    int total = 0;

    if (available() <= 0) return -1;

    while (len > 0) {
      if (_chunk == null) {
        try {
          _chunk = nextChunk();
        } catch (GeneralSecurityException e) {
          throw new EncryptedDocumentException(e.getMessage(), e);
        }
      }
      int count = (int) (chunkSize - (_pos & chunkMask));
      int avail = available();
      if (avail == 0) {
        return total;
      }
      count = Math.min(avail, Math.min(count, len));
      System.arraycopy(_chunk, (int) (_pos & chunkMask), b, off, count);
      off += count;
      len -= count;
      _pos += count;
      if ((_pos & chunkMask) == 0) _chunk = null;
      total += count;
    }

    return total;
  }
 private void init() throws GeneralSecurityException, IOException {
   // Unfortunately, we don't know that the signature is
   // correct until we have read the whole stream.
   // So, we read the stream until the end, and we see if we
   // get any exception.
   long a = 0;
   if (_logger.isInfoEnabled()) {
     a = System.currentTimeMillis();
   }
   byte buffer[] = new byte[1000];
   try {
     while (in.read(buffer, 0, buffer.length) != -1) ;
   } catch (Exception e) {
     String message = "Invalid JAR file";
     if (_url != null) {
       message += ": " + _url;
     }
     GeneralSecurityException gse = new GeneralSecurityException(message);
     gse.initCause(e);
     throw gse;
   }
   if (_logger.isInfoEnabled()) {
     long b = System.currentTimeMillis();
     m_totalTime += (b - a);
     _logger.info("Time spent: " + (b - a) + " Total: " + m_totalTime);
   }
 }
  /**
   * @param config The Properties holding a username, password etc.
   * @param properties Properties holding server settings and configuration
   */
  public ComposeMailScreen(Properties config) {
    this.username = config.getProperty("username");
    Authenticator authenticator =
        new Authenticator() {
          @Override
          protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(username, password);
          }
        };

    this.keyWords = new ArrayList<String>();
    this.session = Session.getInstance(config, authenticator);
    // The password which will be decrypted
    String passwordDec = config.getProperty("password");
    try {
      passwordDec = ProtectedPassword.decrypt(passwordDec);
    } catch (GeneralSecurityException ex) {
      JOptionPane.showMessageDialog(
          rootPane, ex.toString(), "GeneralSecurityException", JOptionPane.ERROR_MESSAGE);
    } catch (IOException ex) {
      JOptionPane.showMessageDialog(
          rootPane, ex.toString(), "GeneralSecurityException", JOptionPane.ERROR_MESSAGE);
    }

    this.password = passwordDec;
    initComponents();
    this.setLocationRelativeTo(null);
  }
Ejemplo n.º 11
0
  private X509Certificate[] doBuild(X509Certificate[] chain, Collection otherCerts)
      throws CertificateException {
    try {
      PKIXBuilderParameters params = (PKIXBuilderParameters) parameterTemplate.clone();
      setDate(params);

      // setup target constraints
      X509CertSelector selector = new X509CertSelector();
      selector.setCertificate(chain[0]);
      params.setTargetCertConstraints(selector);

      // setup CertStores
      Collection certs = new ArrayList();
      certs.addAll(Arrays.asList(chain));
      if (otherCerts != null) {
        certs.addAll(otherCerts);
      }
      CertStore store =
          CertStore.getInstance("Collection", new CollectionCertStoreParameters(certs));
      params.addCertStore(store);

      // do the build
      CertPathBuilder builder = CertPathBuilder.getInstance("PKIX");
      PKIXCertPathBuilderResult result = (PKIXCertPathBuilderResult) builder.build(params);

      return toArray(result.getCertPath(), result.getTrustAnchor());
    } catch (GeneralSecurityException e) {
      throw new ValidatorException("PKIX path building failed: " + e.toString(), e);
    }
  }
 public byte[] encrypt(byte[] data, byte[] key, byte[] ivec, int usage) throws KrbCryptoException {
   try {
     return Des3.encrypt(key, usage, ivec, data, 0, data.length);
   } catch (GeneralSecurityException e) {
     KrbCryptoException ke = new KrbCryptoException(e.getMessage());
     ke.initCause(e);
     throw ke;
   }
 }
 private static SSLContext createEasySSLContext() throws IOException {
   try {
     final SSLContext context = SSLContext.getInstance("TLS");
     context.init(null, new TrustManager[] {new NaiveTrustManager()}, null);
     return context;
   } catch (GeneralSecurityException e) {
     throw new IOException(e.getMessage());
   }
 }
 @Override
 public void logEvent(String message, int entityId, Class entityClass, Date date) {
   User user = (User) Utility.getAuthenticatedUser();
   try {
     auditLogRecordRepo.logEvent(
         user, PBEWithMD5AndDES.encrypt(message), entityId, entityClass, date);
   } catch (GeneralSecurityException e) {
     e.printStackTrace();
   }
 }
 public byte[] decrypt(byte[] cipher, byte[] key, byte[] ivec, int usage)
     throws KrbApErrException, KrbCryptoException {
   try {
     return Des3.decrypt(key, usage, ivec, cipher, 0, cipher.length);
   } catch (GeneralSecurityException e) {
     KrbCryptoException ke = new KrbCryptoException(e.getMessage());
     ke.initCause(e);
     throw ke;
   }
 }
Ejemplo n.º 16
0
  public static void crypt(String inFilename, String outFilename, int mode) {
    InputStream in = null;
    OutputStream out = null;
    ObjectInputStream keyin = null;
    try {
      in = new FileInputStream(inFilename);
      out = new FileOutputStream(outFilename);
      keyin = new ObjectInputStream(new FileInputStream(keyFilename));
      // 获取到密钥
      Key key = (Key) keyin.readObject();
      // 使用AES算法获取密码对象
      Cipher cipher = Cipher.getInstance("AES");
      // 通过设置模式和密钥来初始化
      cipher.init(mode, key);

      // 获取密码块大小,16
      int blockSize = cipher.getBlockSize();
      // 该密码块对应的输出缓存区大小,用于存放密码对象输出的数据块
      int outputSize = cipher.getOutputSize(blockSize);
      byte[] inBytes = new byte[blockSize];
      byte[] outBytes = new byte[outputSize];
      int length = 0;

      boolean more = true;
      while (more) {
        length = in.read(inBytes);
        // 如果能读到blockSize大小的块
        if (length == blockSize) {
          // 数据块存入outBytes
          int outLength = cipher.update(inBytes, 0, blockSize, outBytes);
          out.write(outBytes, 0, outLength);
        } else {
          more = false;
        }
      }
      // 如果最后一个输入数据块的字节数小于blockSize,剩下的字节将会自动填充
      if (length > 0) {
        outBytes = cipher.doFinal(inBytes, 0, length);
      } else {
        outBytes = cipher.doFinal();
      }
      out.write(outBytes);

    } catch (IOException e) {
      e.printStackTrace();
    } catch (ClassNotFoundException e) {
      e.printStackTrace();
    } catch (GeneralSecurityException e) {
      e.printStackTrace();
    } finally {
      Closer.close(in);
      Closer.close(out);
      Closer.close(keyin);
    }
  }
  /**
   * Creates the GenericStreamCipher or GenericBlockCipher data structure for specified data of
   * specified type.
   *
   * @throws AlertException if alert was occurred.
   */
  @Override
  protected byte[] encrypt(byte type, byte[] fragment, int offset, int len) {
    try {
      int content_mac_length = len + hash_size;
      int padding_length = is_block_cipher ? ((8 - (++content_mac_length & 0x07)) & 0x07) : 0;
      byte[] res = new byte[content_mac_length + padding_length];
      System.arraycopy(fragment, offset, res, 0, len);

      mac_material_header[0] = type;
      mac_material_header[3] = (byte) ((0x00FF00 & len) >> 8);
      mac_material_header[4] = (byte) (0x0000FF & len);

      encMac.update(write_seq_num);
      encMac.update(mac_material_header);
      encMac.update(fragment, offset, len);
      encMac.doFinal(res, len);

      // if (logger != null) {
      //    logger.println("MAC Material:");
      //    logger.print(write_seq_num);
      //    logger.print(mac_material_header);
      //    logger.print(fragment, offset, len);
      // }

      if (is_block_cipher) {
        // do padding:
        Arrays.fill(res, content_mac_length - 1, res.length, (byte) (padding_length));
      }
      if (logger != null) {
        logger.println(
            "SSLRecordProtocol.do_encryption: Generic"
                + (is_block_cipher
                    ? "BlockCipher with padding[" + padding_length + "]:"
                    : "StreamCipher:"));
        logger.print(res);
      }
      byte[] rez = new byte[encCipher.getOutputSize(res.length)];
      // We should not call just doFinal because it reinitialize
      // the cipher, but as says rfc 2246:
      // "For stream ciphers that do not use a synchronization
      // vector (such as RC4), the stream cipher state from the end
      // of one record is simply used on the subsequent packet."
      // and for block ciphers:
      // "The IV for subsequent records is the last ciphertext block from
      // the previous record."
      // i.e. we should keep the cipher state.
      encCipher.update(res, 0, res.length, rez);
      incSequenceNumber(write_seq_num);
      return rez;
    } catch (GeneralSecurityException e) {
      e.printStackTrace();
      throw new AlertException(
          AlertProtocol.INTERNAL_ERROR, new SSLProtocolException("Error during the encryption"));
    }
  }
  /**
   * Calculates keyed checksum.
   *
   * @param data the data used to generate the checksum.
   * @param size length of the data.
   * @param key the key used to encrypt the checksum.
   * @return keyed checksum.
   */
  public byte[] calculateKeyedChecksum(byte[] data, int size, byte[] key, int usage)
      throws KrbCryptoException {

    try {
      return Aes128.calculateChecksum(key, usage, data, 0, size);
    } catch (GeneralSecurityException e) {
      KrbCryptoException ke = new KrbCryptoException(e.getMessage());
      ke.initCause(e);
      throw ke;
    }
  }
Ejemplo n.º 19
0
 public static String encrypt(byte[] key, Map<String, Object> req) {
   String request = JsonUtil.toJson(req).toString();
   byte[] hex = null;
   try {
     hex = DESUtil.ecbEncrypt(key, request.getBytes(), 2);
   } catch (GeneralSecurityException e) {
     logger.error(e.getMessage());
     logger.error(e.getStackTrace().toString());
   }
   return BytesUtil.bytesToHex(hex);
 }
  /**
   * Verifies keyed checksum.
   *
   * @param data the data.
   * @param size the length of data.
   * @param key the key used to encrypt the checksum.
   * @param checksum
   * @return true if verification is successful.
   */
  public boolean verifyKeyedChecksum(byte[] data, int size, byte[] key, byte[] checksum, int usage)
      throws KrbCryptoException {

    try {
      byte[] newCksum = Aes128.calculateChecksum(key, usage, data, 0, size);
      return isChecksumEqual(checksum, newCksum);
    } catch (GeneralSecurityException e) {
      KrbCryptoException ke = new KrbCryptoException(e.getMessage());
      ke.initCause(e);
      throw ke;
    }
  }
 public void run() {
   try {
     Subject server = subjectFactory.getSubjectForHost(getHostName(exchange));
     // The AcceptSecurityContext takes over responsibility for setting the result.
     Subject.doAs(server, new AcceptSecurityContext(result, exchange, challenge));
   } catch (GeneralSecurityException e) {
     e.printStackTrace();
     result.setResult(new AuthenticationResult(null, AuthenticationOutcome.NOT_AUTHENTICATED));
   } catch (PrivilegedActionException e) {
     e.printStackTrace();
     result.setResult(new AuthenticationResult(null, AuthenticationOutcome.NOT_AUTHENTICATED));
   }
 }
  public ASN1Sequence generateRecipientEncryptedKeys(
      AlgorithmIdentifier keyAgreeAlgorithm,
      AlgorithmIdentifier keyEncryptionAlgorithm,
      GenericKey contentEncryptionKey)
      throws CMSException {
    init(keyAgreeAlgorithm.getAlgorithm());

    PrivateKey senderPrivateKey = this.senderPrivateKey;

    ASN1ObjectIdentifier keyAgreementOID = keyAgreeAlgorithm.getAlgorithm();

    if (keyAgreementOID.getId().equals(CMSEnvelopedGenerator.ECMQV_SHA1KDF)) {
      senderPrivateKey =
          new MQVPrivateKeySpec(
              senderPrivateKey, ephemeralKP.getPrivate(), ephemeralKP.getPublic());
    }

    ASN1EncodableVector recipientEncryptedKeys = new ASN1EncodableVector();
    for (int i = 0; i != recipientIDs.size(); i++) {
      PublicKey recipientPublicKey = (PublicKey) recipientKeys.get(i);
      KeyAgreeRecipientIdentifier karId = (KeyAgreeRecipientIdentifier) recipientIDs.get(i);

      if (keyAgreementOID.getId().equals(CMSEnvelopedGenerator.ECMQV_SHA1KDF)) {
        recipientPublicKey = new MQVPublicKeySpec(recipientPublicKey, recipientPublicKey);
      }

      try {
        // Use key agreement to choose a wrap key for this recipient
        KeyAgreement keyAgreement = helper.createKeyAgreement(keyAgreementOID);
        keyAgreement.init(senderPrivateKey, random);
        keyAgreement.doPhase(recipientPublicKey, true);
        SecretKey keyEncryptionKey =
            keyAgreement.generateSecret(keyEncryptionAlgorithm.getAlgorithm().getId());

        // Wrap the content encryption key with the agreement key
        Cipher keyEncryptionCipher = helper.createCipher(keyEncryptionAlgorithm.getAlgorithm());

        keyEncryptionCipher.init(Cipher.WRAP_MODE, keyEncryptionKey, random);

        byte[] encryptedKeyBytes = keyEncryptionCipher.wrap(helper.getJceKey(contentEncryptionKey));

        ASN1OctetString encryptedKey = new DEROctetString(encryptedKeyBytes);

        recipientEncryptedKeys.add(new RecipientEncryptedKey(karId, encryptedKey));
      } catch (GeneralSecurityException e) {
        throw new CMSException("cannot perform agreement step: " + e.getMessage(), e);
      }
    }

    return new DERSequence(recipientEncryptedKeys);
  }
Ejemplo n.º 23
0
  /**
   * Verifies a signed message and returns the signed data.
   *
   * @param message The enveloping signed XML object.
   * @return the original XML object.
   */
  public XMLObjectWrapper verifyXMLWrapper(XMLSignatureWrapper message) throws IOException {
    if (message.wrappedData == null) {
      throw new IOException("Message data not wrapped.");
    }
    try {
      checkMainReference(message);
      checkKeyInfoReference(message);
      verify(message);
    } catch (GeneralSecurityException gse) {
      throw new IOException(gse.getMessage());
    }

    return message.wrappedData;
  }
Ejemplo n.º 24
0
  protected void loadKey(InputStream input) throws CredentialException {

    // JGLOBUS-95: BC seems to have some PEM utility but the actual
    // load is in private methods and cannot be leveraged.
    // Investigate availability of standard libraries for these
    // low level reads. FOr now, copying from CoG
    try {
      this.opensslKey = new BouncyCastleOpenSSLKey(input);
    } catch (IOException e) {
      throw new CredentialException(e.getMessage(), e);
    } catch (GeneralSecurityException e) {
      throw new CredentialException(e.getMessage(), e);
    }
  }
  @Override
  protected void handleIntent() {
    TermService service = getTermService();
    if (service == null) {
      finish();
      return;
    }

    Intent myIntent = getIntent();
    String action = myIntent.getAction();
    if (action.equals(ACTION_RUN_SHORTCUT)) {
      String encCommand = myIntent.getStringExtra(EXTRA_SHORTCUT_COMMAND);
      if (encCommand == null) {
        Log.e(TermDebug.LOG_TAG, "No command provided in shortcut!");
        finish();
        return;
      }

      // Decrypt and verify the command
      ShortcutEncryption.Keys keys = ShortcutEncryption.getKeys(this);
      if (keys == null) {
        // No keys -- no valid shortcuts can exist
        Log.e(TermDebug.LOG_TAG, "No shortcut encryption keys found!");
        finish();
        return;
      }
      String command;
      try {
        command = ShortcutEncryption.decrypt(encCommand, keys);
      } catch (GeneralSecurityException e) {
        Log.e(TermDebug.LOG_TAG, "Invalid shortcut: " + e.toString());
        finish();
        return;
      }

      String handle = myIntent.getStringExtra(EXTRA_WINDOW_HANDLE);
      if (handle != null) {
        // Target the request at an existing window if open
        handle = appendToWindow(handle, command);
      } else {
        // Open a new window
        handle = openNewWindow(command);
      }
      Intent result = new Intent();
      result.putExtra(EXTRA_WINDOW_HANDLE, handle);
      setResult(RESULT_OK, result);
    }

    finish();
  }
 static {
   try {
     KeyFactory factory = KeyFactory.getInstance(KEY_ALGORITHM);
     X509EncodedKeySpec spec =
         new X509EncodedKeySpec(DatatypeConverter.parseBase64Binary(KEY_B64_ENCODED));
     key = factory.generatePublic(spec);
   } catch (GeneralSecurityException e) {
     key = null;
     // no log service available yet, so use syserr
     System.err.println(
         "Failed to initialize public key to verify extension certificates. Revoking permissions for all extensions!");
     e.printStackTrace();
   }
 }
Ejemplo n.º 27
0
  Cipher createRFC3211Wrapper(ASN1ObjectIdentifier algorithm) throws CMSException {
    String cipherName = (String) BASE_CIPHER_NAMES.get(algorithm);

    if (cipherName == null) {
      throw new CMSException("no name for " + algorithm);
    }

    cipherName += "RFC3211Wrap";

    try {
      return helper.createCipher(cipherName);
    } catch (GeneralSecurityException e) {
      throw new CMSException("cannot create cipher: " + e.getMessage(), e);
    }
  }
Ejemplo n.º 28
0
  public PrivateKey getPrivateKey(String password) throws CredentialException {

    if (this.opensslKey.isEncrypted()) {
      if (password == null) {
        throw new CredentialException("Key encrypted, password required");
      } else {
        try {
          this.opensslKey.decrypt(password);
        } catch (GeneralSecurityException exp) {
          throw new CredentialException(exp.getMessage(), exp);
        }
      }
    }
    return this.opensslKey.getPrivateKey();
  }
Ejemplo n.º 29
0
  /**
   * Set the default X509 Trust Manager to an instance of a fake class that trust all certificates,
   * even the self-signed ones. This method uses the old deprecated API from the <code>com.sun.ssl
   * </code> package.
   *
   * @deprecated see {@link #_trustAllHttpsCertificates()}.
   */
  private static void __trustAllHttpsCertificates() {
    com.sun.net.ssl.SSLContext context;

    // Create a trust manager that does not validate certificate chains
    if (__trustManagers == null) {
      __trustManagers = new com.sun.net.ssl.TrustManager[] {new _FakeX509TrustManager()};
    } // if
    // Install the all-trusting trust manager
    try {
      context = com.sun.net.ssl.SSLContext.getInstance("SSL");
      context.init(null, __trustManagers, new SecureRandom());
    } catch (GeneralSecurityException gse) {
      throw new IllegalStateException(gse.getMessage());
    } // catch
    com.sun.net.ssl.HttpsURLConnection.setDefaultSSLSocketFactory(context.getSocketFactory());
  } // __trustAllHttpsCertificates
  public byte[] generateWrappedKey(GenericKey encryptionKey) throws OperatorException {
    Key contentEncryptionKeySpec = OperatorUtils.getJceKey(encryptionKey);

    Cipher keyEncryptionCipher =
        helper.createSymmetricWrapper(this.getAlgorithmIdentifier().getAlgorithm());

    try {
      keyEncryptionCipher.init(Cipher.WRAP_MODE, wrappingKey, random);

      return keyEncryptionCipher.wrap(contentEncryptionKeySpec);
    } catch (InvalidKeyException e) {
      throw new OperatorException("cannot wrap key: " + e.getMessage(), e);
    } catch (GeneralSecurityException e) {
      throw new OperatorException("cannot wrap key: " + e.getMessage(), e);
    }
  }