Returns private key bytes, padded with zeros to 33 bytes.
@throws java.lang.IllegalStateException if the private key bytes are missing.
503751
public byte[] getPrivKeyBytes33() {
        byte[] bytes33 = new byte[33];
        byte[] priv = getPrivKeyBytes();
        System.arraycopy(priv, 0, bytes33, 33 - priv.length, priv.length);
        return bytes33;
    }
287013
public byte[] getEncoded() throws SshException {
		ByteArrayWriter baw = new ByteArrayWriter();
		try {

			baw.writeString(getAlgorithm());
			baw.writeBigInteger(pubKey.getPublicExponent());
			baw.writeBigInteger(pubKey.getModulus());

			return baw.toByteArray();
		} catch (IOException ex) {
			throw new SshException("Failed to encoded key data",
					SshException.INTERNAL_ERROR, ex);
		} finally {
			try {
				baw.close();
			} catch (IOException e) {
			}
		}
	}
974624
public static PrivateKey decodePrivateKey(String pemEncoded) throws Exception {
        pemEncoded = removeBeginEnd(pemEncoded);
        byte[] pkcs8EncodedBytes = Base64.getDecoder().decode(pemEncoded);

        // extract the private key

        PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(pkcs8EncodedBytes);
        KeyFactory kf = KeyFactory.getInstance("RSA");
        PrivateKey privKey = kf.generatePrivate(keySpec);
        return privKey;
    }
477950
private int getByte(int position) {
    if (position + 1 >= length) {
      throw new IllegalStateException("Malformed DN: " + dn);
    }

    int b1, b2;

    b1 = chars[position];
    if (b1 >= '0' && b1 <= '9') {
      b1 = b1 - '0';
    } else if (b1 >= 'a' && b1 <= 'f') {
      b1 = b1 - 87; // 87 = 'a' - 10
    } else if (b1 >= 'A' && b1 <= 'F') {
      b1 = b1 - 55; // 55 = 'A' - 10
    } else {
      throw new IllegalStateException("Malformed DN: " + dn);
    }

    b2 = chars[position + 1];
    if (b2 >= '0' && b2 <= '9') {
      b2 = b2 - '0';
    } else if (b2 >= 'a' && b2 <= 'f') {
      b2 = b2 - 87; // 87 = 'a' - 10
    } else if (b2 >= 'A' && b2 <= 'F') {
      b2 = b2 - 55; // 55 = 'A' - 10
    } else {
      throw new IllegalStateException("Malformed DN: " + dn);
    }

    return (b1 << 4) + b2;
  }
231671
public static final int getKeySize(Key key) {
        int size = -1;

        if (key instanceof Length) {
            try {
                Length ruler = (Length)key;
                size = ruler.length();
            } catch (UnsupportedOperationException usoe) {
                // ignore the exception
            }

            if (size >= 0) {
                return size;
            }
        }

        // try to parse the length from key specification
        if (key instanceof SecretKey) {
            SecretKey sk = (SecretKey)key;
            String format = sk.getFormat();
            if ("RAW".equals(format) && sk.getEncoded() != null) {
                size = (sk.getEncoded().length * 8);
            }   // Otherwise, it may be a unextractable key of PKCS#11, or
                // a key we are not able to handle.
        } else if (key instanceof RSAKey) {
            RSAKey pubk = (RSAKey)key;
            size = pubk.getModulus().bitLength();
        } else if (key instanceof ECKey) {
            ECKey pubk = (ECKey)key;
            ECParameterSpec params = pubk.getParams();
            // According to RFC 3279 section 2.3.5, EC keys are allowed
            // to inherit parameters in an X.509 certificate issuer's
            // key parameters, so the parameters may be null. The parent
            // key will be rejected if its parameters don't pass, so this
            // is okay.
            if (params != null) {
                size = params.getOrder().bitLength();
            }
        } else if (key instanceof DSAKey) {
            DSAKey pubk = (DSAKey)key;
            DSAParams params = pubk.getParams();
            // According to RFC 3279 section 2.3.2, DSA keys are allowed
            // to inherit parameters in an X.509 certificate issuer's
            // key parameters, so the parameters may be null. The parent
            // key will be rejected if its parameters don't pass, so this
            // is okay.
            if (params != null) {
                size = params.getP().bitLength();
            }
        } else if (key instanceof DHKey) {
            DHKey pubk = (DHKey)key;
            size = pubk.getParams().getP().bitLength();
        }   // Otherwise, it may be a unextractable key of PKCS#11, or
            // a key we are not able to handle.

        return size;
    }
1039835
def serialize_private_key_to_pem(private_key, passphrase_bytes=None):
    
    return private_key.private_bytes(
        encoding=cryptography.hazmat.primitives.serialization.Encoding.PEM,
        format=cryptography.hazmat.primitives.serialization.PrivateFormat.TraditionalOpenSSL,
        encryption_algorithm=cryptography.hazmat.primitives.serialization.BestAvailableEncryption(
            passphrase_bytes
        )
        if passphrase_bytes is not None
        else cryptography.hazmat.primitives.serialization.NoEncryption(),
    )
728721
function _rsapem_privateKeyToPkcs8HexString(rsaKey) {
	var zeroInteger = "020100";
    var encodedIdentifier = "06092A864886F70D010101";
    var encodedNull = "0500";
    var headerSequence = "300D" + encodedIdentifier + encodedNull;
    var keySequence = _rsapem_privateKeyToPkcs1HexString(rsaKey);
    
    var keyOctetString = "04" + _rsapem_encodeLength(keySequence.length / 2) + keySequence;
    
    var mainSequence = zeroInteger + headerSequence + keyOctetString;
    return "30" + _rsapem_encodeLength(mainSequence.length / 2) + mainSequence;
}
232512
private static List<byte[]> parsePrivateKeyASN1(ByteBuffer byteBuffer) {
    final List<byte[]> collection = new ArrayList<byte[]>();
    while (byteBuffer.hasRemaining()) {
      byte type = byteBuffer.get();
      int length = UnsignedBytes.toInt(byteBuffer.get());
      if ((length & 0x80) != 0) {
        int numberOfOctets = length ^ 0x80;
        length = 0;
        for (int i = 0; i < numberOfOctets; ++i) {
          int lengthChunk = UnsignedBytes.toInt(byteBuffer.get());
          length += lengthChunk << (numberOfOctets - i - 1) * 8;
        }
      }
      if (length < 0) {
        throw new IllegalArgumentException();
      }
      if (type == 0x30) {
        int position = byteBuffer.position();
        byte[] data = Arrays.copyOfRange(byteBuffer.array(), position, position + length);
        return parsePrivateKeyASN1(ByteBuffer.wrap(data));
      }
      if (type == 0x02) {
        byte[] segment = new byte[length];
        byteBuffer.get(segment);
        collection.add(segment);
      }
    }
    return collection;
  }
197513
private static PrivateKey loadPrivateKey(byte[] keyBytes) {
        PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(
                keyBytes);
        try {
            KeyFactory factory = KeyFactory.getInstance(KEY_ALGORITHM);
            PrivateKey privateKey = factory
                    .generatePrivate(pkcs8EncodedKeySpec);
            return privateKey;
        } catch (NoSuchAlgorithmException | InvalidKeySpecException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;
    }
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);
      }
   }
1152119
private final byte[][] decode(byte[] encodedPrivateKey) {
        byte[][] decodedKey = new byte[8][];
        if (encodedPrivateKey.length > (PUBLIC_EXPONENT_LENGTH + PRIME_P_LENGTH + PRIME_Q_LENGTH)) {
            // it is potentially the new encoding mechanism based on R3.5 [with CRT key information added for Domino]
            // determine the length of the CRT key by looking at the first four bytes
            byte[] lengthBytes = new byte[PRIVATE_EXPONENT_LENGTH_FIELD_LENGTH];
            for (int i = 0; i < PRIVATE_EXPONENT_LENGTH_FIELD_LENGTH; i++) {
                lengthBytes[i] = encodedPrivateKey[i];
            }
            privateExponentLength = toInt(lengthBytes);
            decodedKey[PRIVATE_EXPONENT] = new byte[privateExponentLength];
            decodedKey[PUBLIC_EXPONENT] = new byte[PUBLIC_EXPONENT_LENGTH];
            decodedKey[PRIME_P] = new byte[PRIME_P_LENGTH];
            decodedKey[PRIME_Q] = new byte[PRIME_Q_LENGTH];

            System.arraycopy(encodedPrivateKey, PRIVATE_EXPONENT_LENGTH_FIELD_LENGTH, decodedKey[PRIVATE_EXPONENT], 0, privateExponentLength);
            System.arraycopy(encodedPrivateKey, PRIVATE_EXPONENT_LENGTH_FIELD_LENGTH + privateExponentLength, decodedKey[PUBLIC_EXPONENT], 0, PUBLIC_EXPONENT_LENGTH);
            System.arraycopy(encodedPrivateKey, PRIVATE_EXPONENT_LENGTH_FIELD_LENGTH + privateExponentLength + PUBLIC_EXPONENT_LENGTH, decodedKey[PRIME_P], 0, PRIME_P_LENGTH);
            System.arraycopy(encodedPrivateKey, PRIVATE_EXPONENT_LENGTH_FIELD_LENGTH + privateExponentLength + PUBLIC_EXPONENT_LENGTH + PRIME_P_LENGTH, decodedKey[PRIME_Q], 0,
                             PRIME_Q_LENGTH);
        } else {
            // it is a R3.02 key [without CRT key information] 
            decodedKey[PUBLIC_EXPONENT] = new byte[PUBLIC_EXPONENT_LENGTH];
            decodedKey[PRIME_P] = new byte[PRIME_P_LENGTH];
            decodedKey[PRIME_Q] = new byte[PRIME_Q_LENGTH];

            System.arraycopy(encodedPrivateKey, 0, decodedKey[PUBLIC_EXPONENT], 0, PUBLIC_EXPONENT_LENGTH);
            System.arraycopy(encodedPrivateKey, PUBLIC_EXPONENT_LENGTH, decodedKey[PRIME_P], 0, PRIME_P_LENGTH);
            System.arraycopy(encodedPrivateKey, PUBLIC_EXPONENT_LENGTH + PRIME_P_LENGTH, decodedKey[PRIME_Q], 0, PRIME_Q_LENGTH);
        }
        return decodedKey;
    }
730566
public boolean padToByte() {
    boolean padded = false;

    EncodedElement end = EncodedElement.getEnd_S(this);
    int tempVal = end.usableBits;
    if(tempVal % 8 != 0) {
      int toWrite = 8-(tempVal%8);
      end.addInt(0, toWrite);
      /* Assert FOR DEVEL ONLY: */
      assert((this.getTotalBits()+offset) % 8 == 0);
      padded = true;
    }
    return padded;
  }
1320618
def privatekey_to_publickey(private_key_bin: bytes) -> bytes:
    
    if not ishash(private_key_bin):
        raise ValueError('private_key_bin format mismatch. maybe hex encoded?')
    return keys.PrivateKey(private_key_bin).public_key.to_bytes()
688329
public synchronized String get() {
        ConfidentialStore cs = ConfidentialStore.get();
        if (secret == null || cs != lastCS) {
            lastCS = cs;
            try {
                byte[] payload = load();
                if (payload == null) {
                    payload = cs.randomBytes(length / 2);
                    store(payload);
                }
                secret = Util.toHexString(payload).substring(0, length);
            } catch (IOException e) {
                throw new Error("Failed to load the key: " + getId(), e);
            }
        }
        return secret;
    }
330782
public static String toBase64Binary(final PrivateKey privateKey)
	{
		final byte[] encoded = privateKey.getEncoded();
		final String privateKeyAsBase64String = DatatypeConverter.printBase64Binary(encoded);
		return privateKeyAsBase64String;
	}
1077500
private PrivateKey readEcPrivateKey(String fileName) throws InvalidKeySpecException, NoSuchAlgorithmException, IOException, NoSuchProviderException
    {
    	StringBuilder sb = new StringBuilder();
    	BufferedReader br = new BufferedReader(new FileReader(fileName));
    	try {
	    	char[] cbuf = new char[1024];
	    	for (int i=0; i <= 10*1024; i++) {
	    		if (!br.ready())
	    			break;
	    		int len = br.read(cbuf, i*1024, 1024);
	    		sb.append(cbuf, 0, len);
	    	}
	    	if (br.ready()) {
	    		throw new IndexOutOfBoundsException("JWK file larger than 10MB");
	    	}
	    	Type mapType = new TypeToken<Map<String, String>>(){}.getType();
	    	Map<String, String> son = new Gson().fromJson(sb.toString(), mapType);
	    	try {
				@SuppressWarnings({ "unchecked", "rawtypes" })
				EllipticCurveJsonWebKey jwk = new EllipticCurveJsonWebKey((Map<String, Object>)(Map)son);
				Base64Encoder enc = new Base64Encoder();
				ByteArrayOutputStream os = new ByteArrayOutputStream();
	        	enc.encode(jwk.getPrivateKey().getEncoded(), 0, jwk.getPrivateKey().getEncoded().length, os);
				return jwk.getPrivateKey();
			} catch (JoseException e1) {
				e1.printStackTrace();
			}
	        return null;
    	} finally {
    		br.close();
    	}
    }
337218
def private_key_to_address(self, pk):
        
        pub = privtopub(pk)
        pub_byte, priv_byte = get_magic_bytes(self.crypto)

        if priv_byte >= 128:
            priv_byte -= 128 #pybitcointools bug

        return pubtoaddr(pub, pub_byte)