Reads private key from the provided InputStream

@param input InputStream of the private key
@return PGPSecretKey
@throws LRException NO_KEY error if the key cannot be obtained from the input stream
559306
private PGPSecretKey readSecretKey(InputStream input) throws LRException
    {
        PGPSecretKeyRingCollection pgpSec;

        try
        {
            pgpSec = new PGPSecretKeyRingCollection(PGPUtil.getDecoderStream(input));
        }
        catch (Exception e)
        {
            throw new LRException(LRException.NO_KEY);
        }

        java.util.Iterator keyRingIter = pgpSec.getKeyRings();
        while (keyRingIter.hasNext()) {
            PGPSecretKeyRing keyRing = (PGPSecretKeyRing) keyRingIter.next();

            java.util.Iterator keyIter = keyRing.getSecretKeys();
            while (keyIter.hasNext()) {
                PGPSecretKey key = (PGPSecretKey) keyIter.next();

                if (key.isSigningKey()) {
                    return key;
                }
            }
        }

        throw new LRException(LRException.NO_KEY);
    }
595331
public InputStream openStream(final Key job_key) {
    InputStream is = new InputStream() {
      final long[] sz = new long[1];
      private int _cidx, _pidx, _sz;
      private C1NChunk _c0;

      @Override
      public int available() {
        if (_c0 == null || _sz >= _c0._len) {
          sz[0] += _c0 != null ? _c0._len : 0;
          if (_cidx >= nChunks()) return 0;
          _c0 = chunkForChunkIdx(_cidx++);
          _sz = C1NChunk._OFF;
          if (job_key != null)
            Job.update(_c0._len, job_key);
        }
        return _c0._len - _sz;
      }

      @Override
      public void close() {
        _cidx = nChunks();
        _c0 = null;
        _sz = 0;
      }

      @Override
      public int read() throws IOException {
        return available() == 0 ? -1 : 0xFF & _c0._mem[_sz++];
      }

      @Override
      public int read(byte[] b, int off, int len) {
        if (b == null) { // Back-channel read of cidx
          if (_cidx > _pidx) { // Remove prev chunk from memory
            Value v = Value.STORE_get(chunkKey(_pidx++));
            if (v != null && v.isPersisted()) {
              v.freePOJO();           // Eagerly toss from memory
              v.freeMem();
            } // Else not found, or not on disk somewhere
          }
          return _cidx;
        }
        int sz = available();
        if (sz == 0)
          return -1;
        len = Math.min(len, sz);
        System.arraycopy(_c0._mem, _sz, b, off, len);
        _sz += len;
        return len;
      }
    };
    try {
      is.available();
    } catch (IOException e) {
      throw new RuntimeException(e);
    }
    return is;
  }
595636
private PublicKey readKey(InputStream is) {
        InputStreamReader isr = new InputStreamReader(is);
        PEMParser r = new PEMParser(isr);
        try {
            Object o = r.readObject();
            if (o instanceof PEMKeyPair) {
                PEMKeyPair keyPair = (PEMKeyPair) o;
                if (keyPair.getPublicKeyInfo() != null &&
                        keyPair.getPublicKeyInfo().getEncoded().length > 0) {
                    return provider.getPublicKey(keyPair.getPublicKeyInfo());
                }
            } else if (o instanceof SubjectPublicKeyInfo) {
                return provider.getPublicKey((SubjectPublicKeyInfo) o);
            }
        } catch (IOException e) {
            // Ignoring, returning null
            log.warn("Failed to get key from PEM file", e);
        } finally {
            IoUtils.closeQuietly(isr,r);
        }

        return null;
    }
424824
public static ByteBuffer decode(String input) throws IOException {
		return decode(input.getBytes(StandardCharsets.US_ASCII));
	}
189903
static SecretKeySpec readSecretKey(DecryptionSetup ds) {
    Keyed<?> ksObject = DKV.getGet(ds._keystore_id);
    ByteVec ksVec = (ByteVec) (ksObject instanceof Frame ? ((Frame) ksObject).vec(0) : ksObject);
    InputStream ksStream = ksVec.openStream(null /*job key*/);
    try {
      KeyStore keystore = KeyStore.getInstance(ds._keystore_type);
      keystore.load(ksStream, ds._password);

      if (! keystore.containsAlias(ds._key_alias)) {
        throw new IllegalArgumentException("Alias for key not found");
      }

      java.security.Key key = keystore.getKey(ds._key_alias, ds._password);
      return new SecretKeySpec(key.getEncoded(), key.getAlgorithm());
    } catch (GeneralSecurityException e) {
      throw new RuntimeException("Unable to load key " + ds._key_alias + " from keystore " + ds._keystore_id, e);
    } catch (IOException e) {
      throw new RuntimeException("Failed to read keystore " + ds._keystore_id, e);
    }
  }
820893
public static JsonWebKey fromRSA(KeyPair keyPair) {

        RSAPrivateCrtKey privateKey = (RSAPrivateCrtKey) keyPair.getPrivate();
        JsonWebKey key = null;

        if (privateKey != null) {

            key = new JsonWebKey().withKty(JsonWebKeyType.RSA).withN(toByteArray(privateKey.getModulus()))
                    .withE(toByteArray(privateKey.getPublicExponent()))
                    .withD(toByteArray(privateKey.getPrivateExponent())).withP(toByteArray(privateKey.getPrimeP()))
                    .withQ(toByteArray(privateKey.getPrimeQ())).withDp(toByteArray(privateKey.getPrimeExponentP()))
                    .withDq(toByteArray(privateKey.getPrimeExponentQ()))
                    .withQi(toByteArray(privateKey.getCrtCoefficient()));
        } else {

            RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();

            key = new JsonWebKey().withKty(JsonWebKeyType.RSA).withN(toByteArray(publicKey.getModulus()))
                    .withE(toByteArray(publicKey.getPublicExponent())).withD(null).withP(null).withQ(null).withDp(null)
                    .withDq(null).withQi(null);
        }

        return key;
    }
430677
protected PGPPublicKeyRing readPublicKeyRing(InputStream publicKey) {
    LOGGER.trace("readPublicKeyRing(InputStream)");
    PGPPublicKeyRing result = null;
    LOGGER.debug("Wrapping public key stream in decoder stream");
    try( InputStream decoderStream = PGPUtil.getDecoderStream(publicKey) ) {
      LOGGER.debug("Creating PGP Object Factory");
      PGPObjectFactory pgpObjectFactory = new PGPObjectFactory(decoderStream, new BcKeyFingerprintCalculator());
      Object o = null;
      LOGGER.debug("Looking up PGP Public KeyRing");
      while( (o = pgpObjectFactory.nextObject()) != null && result == null ) {
        if( o instanceof PGPPublicKeyRing ) {
          LOGGER.info("PGP Public KeyRing retrieved");
          result = (PGPPublicKeyRing)o;
        }
      }
    } catch (IOException e) {
      LOGGER.error("{}", e.getMessage());
    }
    return result;
  }
118194
public static PrivateKey decryptPrivateKey(String privateKeyStr) {
        try {
            KeyFactory keyFactory = KeyFactory.getInstance(algorithm);
            PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(Base64Util.decode(privateKeyStr));
            return keyFactory.generatePrivate(keySpec);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (InvalidKeySpecException e) {
            e.printStackTrace();
        }
        return null;
    }
923772
public static Key readKey(InputStream keyStream) {
		final PemObject object = readPemObject(keyStream);
		final String type = object.getType();
		if (StrUtil.isNotBlank(type) && type.endsWith("PRIVATE KEY")) {
			return KeyUtil.generateRSAPrivateKey(object.getContent());
		} else {
			return KeyUtil.readX509Certificate(keyStream).getPublicKey();
		}
	}
276946
private static boolean Verify(InputStream isSignature, InputStream isMessage, InputStream isPublicKey) throws LRException
    {
		// Get the public key ring collection from the public key input stream
		PGPPublicKeyRingCollection pgpRings = null;
		
		try
		{
			 pgpRings = new PGPPublicKeyRingCollection(PGPUtil.getDecoderStream(isPublicKey));
		}
		catch (Exception e)
		{
			throw new LRException(LRException.INVALID_PUBLIC_KEY);
		}
	
		// Add the Bouncy Castle security provider
		Security.addProvider(new BouncyCastleProvider());
		
		// Build an output stream from the message for verification
		boolean verify = false;
		int ch;
		ByteArrayOutputStream bOut = new ByteArrayOutputStream();
		ArmoredInputStream aIn  = null;
		
		try
		{
			aIn = new ArmoredInputStream(isMessage);
			// We are making no effort to clean the input for this example
			// If this turns into a fully-featured verification utility in a future version, this will need to be handled
			while ((ch = aIn.read()) >= 0 && aIn.isClearText())
			{
				bOut.write((byte)ch);
			}
			
			bOut.close();
		}
		catch (Exception e)
		{
			throw new LRException(LRException.MESSAGE_INVALID);
		}
		
		// Build an object factory from the signature input stream and try to get an object out of it
		Object o = null;
		try
		{
			PGPObjectFactory pgpFact = new PGPObjectFactory(PGPUtil.getDecoderStream(isSignature));
			o = pgpFact.nextObject();
		}
		catch (Exception e)
		{
			throw new LRException(LRException.SIGNATURE_INVALID);
		}
			
		// Check if the object we fetched is a signature list and if it is, get the signature and use it to verfiy
		try
		{
			if (o instanceof PGPSignatureList)
			{
				PGPSignatureList list = (PGPSignatureList)o;
				if (list.size() > 0)
				{
					PGPSignature sig = list.get(0);
					
					PGPPublicKey publicKey = pgpRings.getPublicKey(sig.getKeyID());
					sig.init(new JcaPGPContentVerifierBuilderProvider().setProvider("BC"), publicKey);
					
					sig.update(bOut.toByteArray());
					verify = sig.verify();
				}
			}
		}
		catch (Exception e)
		{
			throw new LRException(LRException.SIGNATURE_NOT_FOUND);
		}
		
		return verify;
	}
516047
def get_key
      # check for a private key string
      if encoded_key = Gxapi.config.google.respond_to?(:private_key)
        OpenSSL::PKey::RSA.new(
          Base64.decode64(Gxapi.config.google.private_key),
          'notasecret'
        )
      else
        Google::APIClient::KeyUtils.load_from_pkcs12(
          Gxapi.config.google.private_key_path,
          'notasecret'
        )
      end
    end
276579
public static String md5Hex(final String input) {
		if (input == null) {
			throw new NullPointerException("String is null");
		}

    	MessageDigest digest = null;
    	
    	try {
    		digest = MessageDigest.getInstance("MD5");
    	} catch (NoSuchAlgorithmException e) {
    		// this should never happen
    		throw new RuntimeException(e);
    	}
        
        byte[] hash = digest.digest(input.getBytes());
        
        return DatatypeConverter.printHexBinary(hash);
    }
529325
public static String aesDecrypt(byte[] input, byte[] key) {
		byte[] decryptResult = aes(input, key, Cipher.DECRYPT_MODE);
		return new String(decryptResult, Charsets.UTF_8);
	}
1112110
public static PrivateKey readPrivateKey(String pemResName) throws Exception {
        InputStream contentIS = TokenUtils.class.getResourceAsStream(pemResName);
        byte[] tmp = new byte[4096];
        int length = contentIS.read(tmp);
        PrivateKey privateKey = decodePrivateKey(new String(tmp, 0, length));
        return privateKey;
    }
926381
public ECDSASignature doSign(byte[] input) {
        if (input.length != 32) {
            throw new IllegalArgumentException("Expected 32 byte input to ECDSA signature, not " + input.length);
        }
        // No decryption of private key required.
        if (privKey == null)
            throw new MissingPrivateKeyException();
        if (privKey instanceof BCECPrivateKey) {
            ECDSASigner signer = new ECDSASigner(new HMacDSAKCalculator(new SHA256Digest()));
            ECPrivateKeyParameters privKeyParams = new ECPrivateKeyParameters(((BCECPrivateKey) privKey).getD(), CURVE);
            signer.init(true, privKeyParams);
            BigInteger[] components = signer.generateSignature(input);
            return new ECDSASignature(components[0], components[1]).toCanonicalised();
        } else {
            try {
                final Signature ecSig = ECSignatureFactory.getRawInstance(provider);
                ecSig.initSign(privKey);
                ecSig.update(input);
                final byte[] derSignature = ecSig.sign();
                return ECDSASignature.decodeFromDER(derSignature).toCanonicalised();
            } catch (SignatureException | InvalidKeyException ex) {
                throw new RuntimeException("ECKey signing error", ex);
            }
        }
    }
1355040
private PrivateKey getPemPrivateKey(final String keyString) throws EncryptionException {
      try {
         final String privKeyPEM = keyString.replace("-----BEGIN PRIVATE KEY-----", "").replace("-----END PRIVATE KEY-----", "").replaceAll("\\v", "");

         final Base64 b64 = new Base64();
         final byte[] decoded = b64.decode(privKeyPEM);

         final PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(decoded);
         final KeyFactory kf = KeyFactory.getInstance(ALGORITHM);

         return kf.generatePrivate(spec);
      } catch (NoSuchAlgorithmException | InvalidKeySpecException e) {
         throw new EncryptionException("Unable to obtain private key: ", e);
      }
   }
501339
public static Properties load(InputStream input) throws IOException {
		Properties prop = new Properties();
		try {
			prop.load(input);
		} catch (IOException e) {
			throw new IOException("Failed to read properties from input");
		}
		return prop;
	}