read RSA private key from a ASN.1 hexadecimal string
@name readPrivateKeyFromASN1HexString
@memberOf RSAKey#
@function
@param {String} keyHex ASN.1 hexadecimal string of PKCS#1 private key.
@since 1.1.1
765355
function _rsapem_readPrivateKeyFromASN1HexString(keyHex) {
  var a = _rsapem_getHexValueArrayOfChildrenFromHex(keyHex);
  this.setPrivateEx(a[1],a[2],a[3],a[4],a[5],a[6],a[7],a[8]);
}
1203895
def rsa_private_key_pkcs8_to_pkcs1(pkcs8_key):
    """"""
    decoded_values = decoder.decode(pkcs8_key, asn1Spec=PKCS8PrivateKey())

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

    return decoded_key["privateKey"]
1178013
public static PrivateKey stringToRSAPrivateKey (String str)
    {
        try {
            BigInteger mod = new BigInteger(str.substring(0, str.indexOf(SPLIT)), 16);
            BigInteger exp = new BigInteger(str.substring(str.indexOf(SPLIT) + 1), 16);
            RSAPrivateKeySpec keySpec = new RSAPrivateKeySpec(mod, exp);
            KeyFactory kf = KeyFactory.getInstance("RSA");
            return kf.generatePrivate(keySpec);
        } catch (NumberFormatException nfe) {
            log.warning("Failed to read key from string.", "str", str, nfe);
        } catch (GeneralSecurityException gse) {
            log.warning("Failed to read key from string.", "str", str, gse);
        }
        return null;
    }
1195835
def DecryptPrivateKey(self, encrypted_private_key):
        
        aes = AES.new(self._master_key, AES.MODE_CBC, self._iv)
        return aes.decrypt(encrypted_private_key)
198378
async function createPrivateKey(size = 2048) {
    let pemKey;

    /* Native implementation */
    if (nativeGenKeyPair) {
        const result = await nativeGenKeyPair('rsa', {
            modulusLength: size,
            publicKeyEncoding: { type: 'spki', format: 'pem' },
            privateKeyEncoding: { type: 'pkcs8', format: 'pem' }
        });

        pemKey = result[1];
    }
    /* Forge implementation */
    else {
        const keyPair = await forgeGenKeyPair({ bits: size });
        pemKey = forge.pki.privateKeyToPem(keyPair.privateKey);
    }

    return Buffer.from(pemKey);
}
950145
private PublicKey getPemPublicKey(final String keyString) throws EncryptionException {
      try {
         final String publicKeyPEM = keyString.replace("-----BEGIN PUBLIC KEY-----", "").replace("-----END PUBLIC KEY-----", "").replaceAll("\\v", "");

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

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

         return kf.generatePublic(spec);
      } catch (NoSuchAlgorithmException | InvalidKeySpecException e) {
         throw new EncryptionException("Unable to obtain public key: ", e);
      }
   }
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();
    	}
    }
676077
@CheckForNull
    public static PrivateKey loadPrivateKey(final String keypem) throws IOException, NoSuchAlgorithmException,
            InvalidKeySpecException {
        try (StringReader certReader = new StringReader(keypem);
             BufferedReader reader = new BufferedReader(certReader)) {
            return loadPrivateKey(reader);
        }
    }
1120117
function rsaOaepEncrypt(cek, key) {
  if (key instanceof Buffer) {
    key = key.toString();
  } else if (typeof key !== 'string') {
    throw new TypeError('Key must be a buffer or a string');
  }
  if (!key.includes('-----BEGIN') ||
      !(key.includes('KEY-----') || key.includes('CERTIFICATE-----'))) {
    throw new TypeError('Key must be a PEM formatted RSA public key');
  }
  let options = {key: key, padding: crypto.constants.RSA_PKCS1_OAEP_PADDING};
  return buf2b64url(crypto.publicEncrypt(options, cek));
}
894165
function getKeys (secret) {
	var hash = crypto.createHash('sha256').update(secret, 'utf8').digest();
	var keypair = naclInstance.crypto_sign_keypair_from_seed(hash);

	return {
		publicKey : Buffer.from(keypair.signPk).toString('hex'),
		privateKey : Buffer.from(keypair.signSk).toString('hex')
	};
}
946228
public static PrivateKey loadPrivateKey(String privateKeyStr) throws Exception {
		try {
			byte[] buffer = base64.decode(privateKeyStr);
			// X509EncodedKeySpec keySpec = new X509EncodedKeySpec(buffer);
			PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(buffer);
			KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
			return (RSAPrivateKey) keyFactory.generatePrivate(keySpec);
		} catch (NoSuchAlgorithmException e) {
			throw new Exception("无此算法");
		} catch (InvalidKeySpecException e) {
			throw new Exception("私钥非法");
		} catch (NullPointerException e) {
			throw new Exception("私钥数据为空");
		}
	}
152441
function pemToRsaSSHKey(pem, comment) {
  assert.equal('string', typeof pem, 'typeof pem');

  // chop off the BEGIN PUBLIC KEY and END PUBLIC KEY portion
  var cleaned = pem.split('\n').slice(1, -2).join('');

  var buf = new Buffer(cleaned, 'base64');

  var der = new asn1.BerReader(buf);

  der.readSequence();
  der.readSequence();

  var oid = der.readOID();
  assert.equal(oid, '1.2.840.113549.1.1.1', 'pem not in RSA format');

  // Null -- XXX this probably isn't good practice
  der.readByte();
  der.readByte();

  // bit string sequence
  der.readSequence(0x03);
  der.readByte();
  der.readSequence();

  // modulus
  assert.equal(der.peek(), asn1.Ber.Integer, 'modulus not an integer');
  der._offset = der.readLength(der.offset + 1);
  var modulus = der._buf.slice(der.offset, der.offset + der.length);
  der._offset += der.length;

  // exponent
  assert.equal(der.peek(), asn1.Ber.Integer, 'exponent not an integer');
  der._offset = der.readLength(der.offset + 1);
  var exponent = der._buf.slice(der.offset, der.offset + der.length);
  der._offset += der.length;

  // now, make the key
  var type = new Buffer('ssh-rsa');
  var buffer = new Buffer(4 + type.length + 4 + modulus.length + 4 + exponent.length);
  var i = 0;
  buffer.writeUInt32BE(type.length, i);     i += 4;
  type.copy(buffer, i);                     i += type.length;
  buffer.writeUInt32BE(exponent.length, i); i += 4;
  exponent.copy(buffer, i);                 i += exponent.length;
  buffer.writeUInt32BE(modulus.length, i);  i += 4;
  modulus.copy(buffer, i);                  i += modulus.length;

  var s = type.toString() + ' ' + buffer.toString('base64') + ' ' + (comment || '');
  return s;
}
63832
private SecretKey generateAESKey(String privateKey, String salt) {
        try {
            byte[] raw = decodeHex(salt);
            KeySpec spec = new PBEKeySpec(privateKey.toCharArray(), raw, iterationCount, keySize);
            SecretKeyFactory factory = SecretKeyFactory.getInstance(PBKDF_2_WITH_HMAC_SHA_1);
            return new SecretKeySpec(factory.generateSecret(spec).getEncoded(), AES_ECB_ALGORITHM);
        } catch (NoSuchAlgorithmException | InvalidKeySpecException e) {
            throw new IllegalStateException(e);
        }
    }
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;
    }
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;
}
483135
function RSASetPrivateEx(N,E,D,P,Q,DP,DQ,C) {
  this.isPrivate = true;
  this.isPublic = false;
  if (N == null) throw "RSASetPrivateEx N == null";
  if (E == null) throw "RSASetPrivateEx E == null";
  if (N.length == 0) throw "RSASetPrivateEx N.length == 0";
  if (E.length == 0) throw "RSASetPrivateEx E.length == 0";

  if (N != null && E != null && N.length > 0 && E.length > 0) {
    this.n = parseBigInt(N,16);
    this.e = parseInt(E,16);
    this.d = parseBigInt(D,16);
    this.p = parseBigInt(P,16);
    this.q = parseBigInt(Q,16);
    this.dmp1 = parseBigInt(DP,16);
    this.dmq1 = parseBigInt(DQ,16);
    this.coeff = parseBigInt(C,16);
  } else {
    throw "Invalid RSA private key in RSASetPrivateEx";
  }
}
344099
function(privateKey, password) {
    // Errors
    if (!privateKey || !password) throw new Error('Missing argument !');
    if (!Helpers.isPrivateKeyValid(privateKey)) throw new Error('Private key is not valid !');
    // Processing
    let pass = derivePassSha(password, 20);
    let r = encrypt(privateKey, convert.hex2ua(pass.priv));
    // Result
    return {
        ciphertext: CryptoJS.enc.Hex.stringify(r.ciphertext),
        iv: convert.ua2hex(r.iv)
    };
}