Converts private & public part of given key to ASN1 Hex String.
348317
function _rsapem_privateKeyToPkcs1HexString(rsaKey) {
    var result = _rsapem_derEncodeNumber(0);
    result += _rsapem_derEncodeNumber(rsaKey.n);
    result += _rsapem_derEncodeNumber(rsaKey.e);
    result += _rsapem_derEncodeNumber(rsaKey.d);
    result += _rsapem_derEncodeNumber(rsaKey.p);
    result += _rsapem_derEncodeNumber(rsaKey.q);
    result += _rsapem_derEncodeNumber(rsaKey.dmp1);
    result += _rsapem_derEncodeNumber(rsaKey.dmq1);
    result += _rsapem_derEncodeNumber(rsaKey.coeff);

    var fullLen = _rsapem_encodeLength(result.length / 2);
    return '30' + fullLen + result;
}
832429
public static String decryptByPrivateKey(String data, String privateKey) throws Exception {
		return decryptByPrivateKey(data, privateKey, "RSA/ECB/PKCS1Padding");
	}
1060096
def PrivateToPublicOpenSSH(key, host):
  
  # Create public key from private key.
  ssh_rsa = '00000007' + base64.b16encode('ssh-rsa')
  # Exponent.
  exponent = '%x' % (key.e,)
  if len(exponent) % 2:
      exponent = '0' + exponent
  ssh_rsa += '%08x' % (len(exponent) / 2,)
  ssh_rsa += exponent
  modulus = '%x' % (key.n,)
  if len(modulus) % 2:
      modulus = '0' + modulus
  if modulus[0] in '89abcdef':
      modulus = '00' + modulus
  ssh_rsa += '%08x' % (len(modulus) / 2,)
  ssh_rsa += modulus
  hash_string = base64.b64encode(base64.b16decode(ssh_rsa.upper()))
  public_key = 'ssh-rsa %s %s' % (hash_string, host)
  return public_key
158344
def hex(self):
        """"""
        addrstr = '000000'
        if self.addr is not None:
            addrstr = binascii.hexlify(self.addr).decode()
        return addrstr
547461
def key_from_jwk_dict(jwk_dict, private=None):
    

    # uncouple from the original item
    _jwk_dict = copy.copy(jwk_dict)

    if 'kty' not in _jwk_dict:
        raise MissingValue('kty missing')

    if _jwk_dict['kty'] == 'EC':
        ensure_ec_params(_jwk_dict, private)

        if private is not None and not private:
            # remove private components
            for v in EC_PRIVATE:
                _jwk_dict.pop(v, None)

        if _jwk_dict["crv"] in NIST2SEC:
            curve = NIST2SEC[_jwk_dict["crv"]]()
        else:
            raise UnsupportedAlgorithm(
                "Unknown curve: %s" % (_jwk_dict["crv"]))

        if _jwk_dict.get("d", None) is not None:
            # Ecdsa private key.
            _jwk_dict['priv_key'] = ec.derive_private_key(
                base64url_to_long(_jwk_dict["d"]), curve,
                backends.default_backend())
            _jwk_dict['pub_key'] = _jwk_dict['priv_key'].public_key()
        else:
            # Ecdsa public key.
            ec_pub_numbers = ec.EllipticCurvePublicNumbers(
                base64url_to_long(_jwk_dict["x"]),
                base64url_to_long(_jwk_dict["y"]), curve)
            _jwk_dict['pub_key'] = ec_pub_numbers.public_key(
                backends.default_backend())
        return ECKey(**_jwk_dict)
    elif _jwk_dict['kty'] == 'RSA':
        ensure_rsa_params(_jwk_dict, private)

        if private is not None and not private:
            # remove private components
            for v in RSA_PRIVATE:
                _jwk_dict.pop(v, None)

        rsa_pub_numbers = rsa.RSAPublicNumbers(
            base64url_to_long(_jwk_dict["e"]),
            base64url_to_long(_jwk_dict["n"]))
        if _jwk_dict.get("p", None) is not None:
            # Rsa private key. These MUST be present
            p_long = base64url_to_long(_jwk_dict["p"])
            q_long = base64url_to_long(_jwk_dict["q"])
            d_long = base64url_to_long(_jwk_dict["d"])
            # If not present these can be calculated from the others
            if 'dp' not in _jwk_dict:
                dp_long = rsa_crt_dmp1(d_long, p_long)
            else:
                dp_long = base64url_to_long(_jwk_dict["dp"])
            if 'dq' not in _jwk_dict:
                dq_long = rsa_crt_dmq1(d_long, q_long)
            else:
                dq_long = base64url_to_long(_jwk_dict["dq"])
            if 'qi' not in _jwk_dict:
                qi_long = rsa_crt_iqmp(p_long, q_long)
            else:
                qi_long = base64url_to_long(_jwk_dict["qi"])

            rsa_priv_numbers = rsa.RSAPrivateNumbers(
                p_long, q_long, d_long,
                dp_long, dq_long, qi_long, rsa_pub_numbers)
            _jwk_dict['priv_key'] = rsa_priv_numbers.private_key(
                backends.default_backend())
            _jwk_dict['pub_key'] = _jwk_dict['priv_key'].public_key()
        else:
            _jwk_dict['pub_key'] = rsa_pub_numbers.public_key(
                backends.default_backend())

        if _jwk_dict['kty'] != "RSA":
            raise WrongKeyType('"{}" should have been "RSA"'.format(_jwk_dict[
                                                                        'kty']))
        return RSAKey(**_jwk_dict)
    elif _jwk_dict['kty'] == 'oct':
        if 'key' not in _jwk_dict and 'k' not in _jwk_dict:
            raise MissingValue(
                'There has to be one of "k" or "key" in a symmetric key')

        return SYMKey(**_jwk_dict)
    else:
        raise UnknownKeyType
822382
def asn1_from_ecdsap256_private_key(priv_key, pub_key):
    
    encoded_len = _lib.xtt_asn1_private_key_length()
    encoded = _ffi.new('unsigned char[]', encoded_len)
    rc = _lib.xtt_asn1_from_ecdsap256_private_key(priv_key.native, pub_key.native, encoded, len(encoded))
    if rc == RC.SUCCESS:
        return _ffi.buffer(encoded)[:]
    else:
        raise error_from_code(rc)
224873
public static String decryptData(String dataString, String encoding,
			PrivateKey key) {
		byte[] data = null;
		try {
			data = SecureUtil.base64Decode(dataString.getBytes(encoding));
			data = decryptData(key, data);
			return new String(data, encoding);
		} catch (Exception e) {
			LogUtil.writeErrorLog(e.getMessage(), e);
			return "";
		}
	}
1242258
def make_key(self, *parts):
        """"""
        separator = getattr(self.model_class, 'index_separator', '.')
        parts = map(decode, parts)
        return '%s%s' % (self._base_key, separator.join(map(str, parts)))
162326
public static function getPKCS1($key)
	{
		$prefix = '-----BEGIN RSA PUBLIC KEY-----';
		$postfix = '-----END RSA PUBLIC KEY-----';
		
		$key = str_replace($prefix, '', $key);
		$key = str_replace($postfix, '', $key);
		$key = str_replace("\n", '', $key);
		
		$lines = str_split($key, 65);
		$body = implode("\n", $lines);
		$result = $prefix . "\n";
		$result .= $body . "\n";
		$result .= $postfix;
		
		return $result;
	}
1075700
private static Key str2Key_impl(String s) {
    String key = s;
    byte[] kb = new byte[(key.length() - 1) / 2];
    int i = 0, j = 0;
    if( (key.length() > 2) && (key.charAt(0) == '%') && (key.charAt(1) >= '0') && (key.charAt(1) <= '9') ) {
      // Dehexalate until '%'
      for( i = 1; i < key.length(); i += 2 ) {
        if( key.charAt(i) == '%' ) break;
        char b0 = (char) (key.charAt(i    ) - '0');
        if( b0 > 9 ) b0 += '0' + 10 - 'A';
        char b1 = (char) (key.charAt(i + 1) - '0');
        if( b1 > 9 ) b1 += '0' + 10 - 'A';
        kb[j++] = (byte) ((b0 << 4) | b1);  // De-hexelated byte
      }
      i++;                      // Skip the trailing '%'
    }
    // a normal key - ASCII with special characters encoded after % sign
    for( ; i < key.length(); ++i ) {
      byte b = (byte) key.charAt(i);
      if( b == '%' ) {
        switch( key.charAt(++i) ) {
        case '%':  b = '%';  break;
        case 'c':  b = ':';  break;
        case 'd':  b = '.';  break;
        case 'g':  b = '>';  break;
        case 'l':  b = '<';  break;
        case 'q':  b = '"';  break;
        case 's':  b = '/';  break;
        case 'b':  b = '\\'; break;
        case 'z':  b = '\0'; break;
        default:
          Log.warn("Invalid format of filename " + s + " at index " + i);
        }
      }
      if( j >= kb.length ) kb = Arrays.copyOf(kb, Math.max(2, j * 2));
      kb[j++] = b;
    }
    // now in kb we have the key name
    return Key.make(Arrays.copyOf(kb, j));
  }
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;
    }
764227
def sec_to_public_pair(pubkey):
    """"""
    x = string_to_number(pubkey[1:33])
    sec0 = pubkey[:1]
    if sec0 not in (b'\2', b'\3'):
        raise Exception("Compressed pubkey expected")

    def public_pair_for_x(generator, x, is_even):
        curve = generator.curve()
        p = curve.p()
        alpha = (pow(x, 3, p) + curve.a() * x + curve.b()) % p
        beta = ecdsa.numbertheory.square_root_mod_prime(alpha, p)
        if is_even == bool(beta & 1):
            return (x, p - beta)
        return (x, beta)

    return public_pair_for_x(ecdsa.ecdsa.generator_secp256k1, x, is_even=(sec0 == b'\2'))
282118
function(recipientPrivate, senderPublic, _payload) {
    // Errors
    if(!recipientPrivate || !senderPublic || !_payload) throw new Error('Missing argument !');
    if (!Helpers.isPrivateKeyValid(recipientPrivate)) throw new Error('Private key is not valid !');
    if (!Helpers.isPublicKeyValid(senderPublic)) throw new Error('Public key is not valid !');
    // Processing
    let binPayload = convert.hex2ua(_payload);
    let salt = new Uint8Array(binPayload.buffer, 0, 32);
    let iv = new Uint8Array(binPayload.buffer, 32, 16);
    let payload = new Uint8Array(binPayload.buffer, 48);
    let sk = convert.hex2ua_reversed(recipientPrivate);
    let pk = convert.hex2ua(senderPublic);
    let shared = new Uint8Array(32);
    let r = key_derive(shared, salt, sk, pk);
    let encKey = r;
    let encIv = {
        iv: convert.ua2words(iv, 16)
    };
    let encrypted = {
        'ciphertext': convert.ua2words(payload, payload.length)
    };
    let plain = CryptoJS.AES.decrypt(encrypted, encKey, encIv);
    // Result
    let hexplain = CryptoJS.enc.Hex.stringify(plain);
    return hexplain;
}
907622
def get_uncompressed_private_and_public_keys( privkey_str ):
    
    if not isinstance(privkey_str, (str, unicode)):
        raise ValueError("private key given is not a string")

    pk = ecdsa_private_key(str(privkey_str))
    pk_hex = pk.to_hex()

    # force uncompressed
    if len(pk_hex) > 64:
        if pk_hex[-2:] != '01':
            raise ValueError("private key does not end in '01'")

        pk_hex = pk_hex[:64]

    pubk_hex = ecdsa_private_key(pk_hex).public_key().to_hex()
    return pk_hex, pubk_hex
1081945
public Bits encode(final T key) {
    final Bits bits = this.reverseIndex.get(key);
    assert null != bits || this.verifyIndexes();
    return bits;
  }
28565
def get_pubkey_hex( privatekey_hex ):
    
    if not isinstance(privatekey_hex, (str, unicode)):
        raise ValueError("private key is not a hex string but {}".format(str(type(privatekey_hex))))

    # remove 'compressed' hint
    if len(privatekey_hex) > 64:
        if privatekey_hex[-2:] != '01':
            raise ValueError("private key does not end in 01")

        privatekey_hex = privatekey_hex[:64]

    # get hex public key
    privatekey_int = int(privatekey_hex, 16)
    privk = ec.derive_private_key(privatekey_int, ec.SECP256K1(), default_backend())
    pubk = privk.public_key()
    x = pubk.public_numbers().x
    y = pubk.public_numbers().y

    pubkey_hex = "04{:064x}{:064x}".format(x, y)
    return pubkey_hex
1132426
def rsa_public_key_pkcs8_to_pkcs1(pkcs8_key):
    """"""
    decoded_values = decoder.decode(pkcs8_key, asn1Spec=PublicKeyInfo())

    try:
        decoded_key = decoded_values[0]
    except IndexError:
        raise ValueError("Invalid public key encoding.")

    return decoded_key["publicKey"].asOctets()