/*
Converts to PEM encoding.
Assumes keyData is initialized.
179608
private String toPEM() {

        byte[] data = (this.keyData == null) ? this.encodedKey : Base64.encode(this.keyData);

        String header = HEADER;

        if (isEncrypted()) {
            StringBuffer buf = new StringBuffer(header);
            buf.append(PEMUtil.LINE_SEP);
            buf.append("Proc-Type: 4,ENCRYPTED");
            buf.append(PEMUtil.LINE_SEP);
            buf.append("DEK-Info: ").append(this.encAlgStr);
            buf.append(",").append(PEMUtil.toHex(initializationVector.getIV()));
            buf.append(PEMUtil.LINE_SEP);
            header = buf.toString();
        }

        ByteArrayOutputStream out = new ByteArrayOutputStream();

        try {
            PEMUtil.writeBase64(out,
                    header,
                    data,
                    "-----END RSA PRIVATE KEY-----");
        } catch (IOException e) {
            // JGLOBUS-91
            throw new RuntimeException("Unexpected error", e);
        }

        return new String(out.toByteArray());
    }
1219003
private static String getKeyValuePair(final Entry<String,String> param, 
        final boolean formEncoding)
        {
        try 
            {
            return getKeyValuePair(param.getKey(),param.getValue(),formEncoding);
            }
        catch (final Exception e)
            {
            LOG.error("Could not get encoding for: {}", param, e);
            return "unknown=unknown";
            }
        }
1070308
public PrivateKey bytesToPrivateKey(byte[] pemKey) throws CryptoException {
        PrivateKey pk = null;
        CryptoException ce = null;

        try {
            PemReader pr = new PemReader(new StringReader(new String(pemKey)));
            PemObject po = pr.readPemObject();
            PEMParser pem = new PEMParser(new StringReader(new String(pemKey)));

            if (po.getType().equals("PRIVATE KEY")) {
                pk = new JcaPEMKeyConverter().getPrivateKey((PrivateKeyInfo) pem.readObject());
            } else {
                logger.trace("Found private key with type " + po.getType());
                PEMKeyPair kp = (PEMKeyPair) pem.readObject();
                pk = new JcaPEMKeyConverter().getPrivateKey(kp.getPrivateKeyInfo());
            }
        } catch (Exception e) {
            throw new CryptoException("Failed to convert private key bytes", e);
        }
        return pk;
    }
1148748
private static function loadKeyFromPEM($pem, $password = null)
    {
        if (preg_match('#DEK-Info: (.+),(.+)#', $pem, $matches)) {
            $pem = self::decodePem($pem, $matches, $password);
        }

        $res = openssl_pkey_get_private($pem);
        if ($res === false) {
            $res = openssl_pkey_get_public($pem);
        }
        Assertion::false($res === false, 'Unable to load the key');

        $details = openssl_pkey_get_details($res);
        Assertion::isArray($details, 'Unable to get details of the key');
        Assertion::keyExists($details, 'type', 'Unable to get details of the key');

        switch ($details['type']) {
            case OPENSSL_KEYTYPE_EC:
                $ec_key = new ECKey($pem);

                return $ec_key->toArray();
            case OPENSSL_KEYTYPE_RSA:
                 $rsa_key = new RSAKey($pem);

                 return $rsa_key->toArray();
            default:
                throw new \InvalidArgumentException('Unsupported key type');
        }
    }
1318239
function(cert) {
      // convert from PEM
      if(typeof cert === 'string') {
        cert = forge.pki.certificateFromPem(cert);
      }
      msg.certificates.push(cert);
    }
30002
function _rsapem_publicKeyToX509HexString(rsaKey) {
    var encodedIdentifier = "06092A864886F70D010101";
    var encodedNull = "0500";
    var headerSequence = "300D" + encodedIdentifier + encodedNull;

    var keys = _rsapem_derEncodeNumber(rsaKey.n);
    keys += _rsapem_derEncodeNumber(rsaKey.e);

    var keySequence = "0030" + _rsapem_encodeLength(keys.length / 2) + keys;
    var bitstring = "03" + _rsapem_encodeLength(keySequence.length / 2) + keySequence;

    var mainSequence = headerSequence + bitstring;

    return "30" + _rsapem_encodeLength(mainSequence.length / 2) + mainSequence;
}
873745
private static void savePrivateKeyPKCS8(OutputStream os, PrivateKey key)
    throws IllegalArgumentException, IOException {

    CertificateUtils.savePrivateKey(os, key, Encoding.PEM, null, null);

  }
1365401
private byte[] getByteKey(K key){
		if(key instanceof String){
			String preKey = this.keyPrefix + key;
    		return preKey.getBytes();
    	}else{
    		return SerializeUtils.serialize(key);
    	}
	}
887520
function pkcs1unpad2(d,n) {
  var b = d.toByteArray();
  var i = 0;
  while(i < b.length && b[i] == 0) ++i;
  if(b.length-i != n-1 || b[i] != 2)
    return null;
  ++i;
  while(b[i] != 0)
    if(++i >= b.length) return null;
  var ret = "";
  while(++i < b.length) {
    var c = b[i] & 255;
    if(c < 128) { // utf-8 decode
      ret += String.fromCharCode(c);
    }
    else if((c > 191) && (c < 224)) {
      ret += String.fromCharCode(((c & 31) << 6) | (b[i+1] & 63));
      ++i;
    }
    else {
      ret += String.fromCharCode(((c & 15) << 12) | ((b[i+1] & 63) << 6) | (b[i+2] & 63));
      i += 2;
    }
  }
  return ret;
}
432801
private static String getKeyValuePair(final Pair<String,String> param, 
        final boolean formEncoding)
        {
        try 
            {
            return getKeyValuePair(param.getFirst(), param.getSecond(), 
                formEncoding);
            }
        catch (final Exception e)
            {
            LOG.error("Could not get encoding for: {}", param, e);
            return "unknown=unknown";
            }
        }
1175307
private static String getKeyValuePair(final String key, final String value, 
        final boolean formEncoding)
        {
        final StringBuilder sb = new StringBuilder ();
        
        final String firstEncoded;
        final String secondEncoded;
        if (formEncoding)
            {
            firstEncoded = urlFormEncode (key);
            secondEncoded = urlFormEncode (value);
            }
        else
            {
            firstEncoded = urlNonFormEncode (key);
            secondEncoded = urlNonFormEncode (value);
            }
        sb.append (firstEncoded);
        sb.append ('=');
        sb.append (secondEncoded);
        
        return sb.toString ();
        }
915007
public byte[] encryptData(PublicKey key,byte[] data)
    {
    	try {
    		if(data==null || data.length<=0)
    		{
    			return null;
    		}
			Cipher cipher=Cipher.getInstance(algorithm);
			cipher.init(Cipher.ENCRYPT_MODE, key);
			return cipher.doFinal(data);
		} catch (Exception e) {
			log.error(e.getMessage(),e);
		}
    	return null;
    }
659114
def load_pem_private_key(data, password):
    """"""
    key = _serialization.load_pem_private_key(
        data, password, _backends.default_backend())
    return key
251815
private byte[][] decode(byte[] encodedPublicKey) {
        byte[][] decodedKey = new byte[2][];
        decodedKey[MODULUS] = new byte[MODULUS_LENGTH];
        decodedKey[EXPONENT] = new byte[EXPONENT_LENGTH];
        System.arraycopy(encodedPublicKey, 0, decodedKey[MODULUS], 0, MODULUS_LENGTH);
        System.arraycopy(encodedPublicKey, MODULUS_LENGTH, decodedKey[EXPONENT], 0, EXPONENT_LENGTH);
        return decodedKey;
    }
420654
private ByteBuffer encodeAndAllocateBuffer(String key) {
        if (key == null) {
            return ByteBuffer.wrap(EMPTY);
        }

        CharsetEncoder encoder = CharsetUtil.encoder(charset);
        ByteBuffer buffer = ByteBuffer.allocate((int) (encoder.maxBytesPerChar() * key.length()));

        ByteBuf byteBuf = Unpooled.wrappedBuffer(buffer);
        byteBuf.clear();
        encode(key, byteBuf);
        buffer.limit(byteBuf.writerIndex());

        return buffer;
    }
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;
    }
176284
static byte []
fromPublicKey(PublicKey key, int alg) throws DNSSECException
{
	byte [] data = null;

	switch (alg) {
	case Algorithm.RSAMD5:
	case Algorithm.RSASHA1:
	case Algorithm.RSA_NSEC3_SHA1:
	case Algorithm.RSASHA256:
	case Algorithm.RSASHA512:
		if (! (key instanceof RSAPublicKey))
			throw new IncompatibleKeyException();
		return fromRSAPublicKey((RSAPublicKey) key);
	case Algorithm.DSA:
	case Algorithm.DSA_NSEC3_SHA1:
		if (! (key instanceof DSAPublicKey))
			throw new IncompatibleKeyException();
		return fromDSAPublicKey((DSAPublicKey) key);
	default:
		throw new UnsupportedAlgorithmException(alg);
	}
}