Copied from com.sun.crypto.provider.OAEPParameters.
962681
private static String convertToStandardName(String internalName) {
        if (internalName.equals("SHA")) {
            return "SHA-1";
        } else if (internalName.equals("SHA224")) {
            return "SHA-224";
        } else if (internalName.equals("SHA256")) {
            return "SHA-256";
        } else if (internalName.equals("SHA384")) {
            return "SHA-384";
        } else if (internalName.equals("SHA512")) {
            return "SHA-512";
        } else {
            return internalName;
        }
    }
314573
public KeyPair toEC(boolean includePrivateParameters, Provider provider) {

        if (provider == null) {
            // Our default provider for this class
            provider = Security.getProvider("SunEC");
        }

        if (!JsonWebKeyType.EC.equals(kty) && !JsonWebKeyType.EC_HSM.equals(kty)) {
            throw new IllegalArgumentException("Not an EC key.");
        }

        try {
            KeyPairGenerator kpg = KeyPairGenerator.getInstance("EC", provider);

            ECGenParameterSpec gps = new ECGenParameterSpec(CURVE_TO_SPEC_NAME.get(crv));
            kpg.initialize(gps);

            // Generate dummy keypair to get parameter spec.
            KeyPair apair = kpg.generateKeyPair();
            ECPublicKey apub = (ECPublicKey) apair.getPublic();
            ECParameterSpec aspec = apub.getParams();

            ECPoint ecPoint = new ECPoint(new BigInteger(1, x), new BigInteger(1, y));

            KeyPair realKeyPair;

            if (includePrivateParameters) {
                realKeyPair = new KeyPair(getECPublicKey(ecPoint, aspec, provider),
                        getECPrivateKey(d, aspec, provider));
            } else {
                realKeyPair = new KeyPair(getECPublicKey(ecPoint, aspec, provider), null);
            }

            return realKeyPair;
        } catch (GeneralSecurityException e) {
            throw new IllegalStateException(e);
        }
    }
943577
private PGPEncryptedDataList getPGPEncryptedDataList(InputStream inputStream) throws IOException {

    if (Security.getProvider(BouncyCastleProvider.PROVIDER_NAME) == null) {
      Security.addProvider(new BouncyCastleProvider());
    }
    inputStream = PGPUtil.getDecoderStream(inputStream);

    JcaPGPObjectFactory pgpF = new JcaPGPObjectFactory(inputStream);
    PGPEncryptedDataList enc;
    Object pgpfObject = pgpF.nextObject();

    if (pgpfObject instanceof PGPEncryptedDataList) {
      enc = (PGPEncryptedDataList) pgpfObject;
    } else {
      enc = (PGPEncryptedDataList) pgpF.nextObject();
    }
    return enc;
  }
1342267
private PublicKey getRSAPublicKey(Provider provider) {

        try {
            RSAPublicKeySpec publicKeySpec = getRSAPublicKeySpec();
            KeyFactory factory = provider != null ? KeyFactory.getInstance("RSA", provider)
                    : KeyFactory.getInstance("RSA");

            return factory.generatePublic(publicKeySpec);
        } catch (GeneralSecurityException e) {
            throw new IllegalStateException(e);
        }
    }
743262
byte[] DERToJOSE(byte[] derSignature) throws SignatureException {
        // DER Structure: http://crypto.stackexchange.com/a/1797
        boolean derEncoded = derSignature[0] == 0x30 && derSignature.length != ecNumberSize * 2;
        if (!derEncoded) {
            throw new SignatureException("Invalid DER signature format.");
        }

        final byte[] joseSignature = new byte[ecNumberSize * 2];

        //Skip 0x30
        int offset = 1;
        if (derSignature[1] == (byte) 0x81) {
            //Skip sign
            offset++;
        }

        //Convert to unsigned. Should match DER length - offset
        int encodedLength = derSignature[offset++] & 0xff;
        if (encodedLength != derSignature.length - offset) {
            throw new SignatureException("Invalid DER signature format.");
        }

        //Skip 0x02
        offset++;

        //Obtain R number length (Includes padding) and skip it
        int rLength = derSignature[offset++];
        if (rLength > ecNumberSize + 1) {
            throw new SignatureException("Invalid DER signature format.");
        }
        int rPadding = ecNumberSize - rLength;
        //Retrieve R number
        System.arraycopy(derSignature, offset + Math.max(-rPadding, 0), joseSignature, Math.max(rPadding, 0), rLength + Math.min(rPadding, 0));

        //Skip R number and 0x02
        offset += rLength + 1;

        //Obtain S number length. (Includes padding)
        int sLength = derSignature[offset++];
        if (sLength > ecNumberSize + 1) {
            throw new SignatureException("Invalid DER signature format.");
        }
        int sPadding = ecNumberSize - sLength;
        //Retrieve R number
        System.arraycopy(derSignature, offset + Math.max(-sPadding, 0), joseSignature, ecNumberSize + Math.max(sPadding, 0), sLength + Math.min(sPadding, 0));

        return joseSignature;
    }
1074721
@Override
  public String cipherSuite()
  {
    if (! (_s instanceof SSLSocket)) {
      return super.cipherSuite();
    }

    SSLSocket sslSocket = (SSLSocket) _s;
    
    SSLSession sslSession = sslSocket.getSession();
    
    if (sslSession != null) {
      return sslSession.getCipherSuite();
    }
    else {
      return null;
    }
  }
1201277
@Override
	public byte[] decrypt(byte[] data, KeyType keyType) throws CryptoException {
		if (KeyType.PrivateKey != keyType) {
			throw new IllegalArgumentException("Decrypt is only support by private key");
		}
		ckeckKey(keyType);

		lock.lock();
		final SM2Engine engine = getEngine();
		try {
			engine.init(false, getCipherParameters(keyType));
			return engine.processBlock(data, 0, data.length);
		} finally {
			lock.unlock();
		}
	}
411165
private byte[] ecdsaSignToBytes(ECPrivateKey privateKey, byte[] data) throws CryptoException {
        if (data == null) {
            throw new CryptoException("Data that to be signed is null.");
        }
        if (data.length == 0) {
            throw new CryptoException("Data to be signed was empty.");
        }

        try {
            X9ECParameters params = ECNamedCurveTable.getByName(curveName);
            BigInteger curveN = params.getN();

            Signature sig = SECURITY_PROVIDER == null ? Signature.getInstance(DEFAULT_SIGNATURE_ALGORITHM) :
                    Signature.getInstance(DEFAULT_SIGNATURE_ALGORITHM, SECURITY_PROVIDER);
            sig.initSign(privateKey);
            sig.update(data);
            byte[] signature = sig.sign();

            BigInteger[] sigs = decodeECDSASignature(signature);

            sigs = preventMalleability(sigs, curveN);

            try (ByteArrayOutputStream s = new ByteArrayOutputStream()) {

                DERSequenceGenerator seq = new DERSequenceGenerator(s);
                seq.addObject(new ASN1Integer(sigs[0]));
                seq.addObject(new ASN1Integer(sigs[1]));
                seq.close();
                return s.toByteArray();
            }

        } catch (Exception e) {
            throw new CryptoException("Could not sign the message using private key", e);
        }

    }
501231
private PrivateKey getRSAPrivateKey(Provider provider) {

        try {
            RSAPrivateKeySpec privateKeySpec = getRSAPrivateKeySpec();
            KeyFactory factory = provider != null ? KeyFactory.getInstance("RSA", provider)
                    : KeyFactory.getInstance("RSA");

            return factory.generatePrivate(privateKeySpec);
        } catch (GeneralSecurityException e) {
            throw new IllegalStateException(e);
        }
    }
1166775
@Benchmark
    @OperationsPerInvocation(20)
    public void benchmarkJdkProxy(Blackhole blackHole) {
        blackHole.consume(jdkProxyInstance.method(booleanValue));
        blackHole.consume(jdkProxyInstance.method(byteValue));
        blackHole.consume(jdkProxyInstance.method(shortValue));
        blackHole.consume(jdkProxyInstance.method(intValue));
        blackHole.consume(jdkProxyInstance.method(charValue));
        blackHole.consume(jdkProxyInstance.method(intValue));
        blackHole.consume(jdkProxyInstance.method(longValue));
        blackHole.consume(jdkProxyInstance.method(floatValue));
        blackHole.consume(jdkProxyInstance.method(doubleValue));
        blackHole.consume(jdkProxyInstance.method(stringValue));
        blackHole.consume(jdkProxyInstance.method(booleanValue, booleanValue, booleanValue));
        blackHole.consume(jdkProxyInstance.method(byteValue, byteValue, byteValue));
        blackHole.consume(jdkProxyInstance.method(shortValue, shortValue, shortValue));
        blackHole.consume(jdkProxyInstance.method(intValue, intValue, intValue));
        blackHole.consume(jdkProxyInstance.method(charValue, charValue, charValue));
        blackHole.consume(jdkProxyInstance.method(intValue, intValue, intValue));
        blackHole.consume(jdkProxyInstance.method(longValue, longValue, longValue));
        blackHole.consume(jdkProxyInstance.method(floatValue, floatValue, floatValue));
        blackHole.consume(jdkProxyInstance.method(doubleValue, doubleValue, doubleValue));
        blackHole.consume(jdkProxyInstance.method(stringValue, stringValue, stringValue));
    }
1021520
def rfc6979_ecdsa_nonce(hash, privkey)
      raise ArgumentError, "Hash must be 32 bytes long" if hash.bytesize != 32
      raise ArgumentError, "Private key must be 32 bytes long" if privkey.bytesize != 32

      autorelease do |pool|
        order = self.group_order

        # Step 3.2.a. hash = H(message). Already performed by the caller.

        # Step 3.2.b. V = 0x01 0x01 0x01 ... 0x01 (32 bytes equal 0x01)
        v = "\x01".b*32

        # Step 3.2.c. K = 0x00 0x00 0x00 ... 0x00 (32 bytes equal 0x00)
        k = "\x00".b*32

        # Step 3.2.d. K = HMAC-SHA256(key: K, data: V || 0x00 || int2octets(privkey) || bits2octets(hash))
        h1 = pool.new_bn(hash)
        BN_div(nil, h1, h1, order, pool.bn_ctx) # h1 = h1 % order
        h1data = data_from_bn(h1, min_length: 32)
        k = BTC.hmac_sha256(key: k, data: v + "\x00".b + privkey + h1data)

        # Step 3.2.e. V = HMAC-SHA256(key: K, data: V)
        v = BTC.hmac_sha256(key: k, data: v)

        # Step 3.2.f. K = HMAC-SHA256(key: K, data: V || 0x01 || int2octets(privkey) || bits2octets(hash))
        k = BTC.hmac_sha256(key: k, data: v + "\x01".b + privkey + h1data)

        # Step 3.2.g. V = HMAC-SHA256(key: K, data: V)
        v = BTC.hmac_sha256(key: k, data: v)

        # Step 3.2.h.
        zero32 = "\x00".b*32
        10000.times do
          t = BTC.hmac_sha256(key: k, data: v)
          tn = pool.new_bn(t)
          if BN_cmp(tn, order) < 0
            nonce = data_from_bn(tn, min_length: 32)
            if nonce != zero32
              return nonce
            end
          end
          # Note: the probability of not succeeding at the first try is about 2^-127.
          k = BTC.hmac_sha256(key: k, data: v + zero32)
          v = BTC.hmac_sha256(key: k, data: v)
        end
        # we generated 10000 numbers, none of them is good -> fail.
        raise "Cannot find any good ECDSA nonce after 10000 iterations of RFC6979."
      end
    end
764554
@Override
	public byte[] encrypt(byte[] data, KeyType keyType) throws CryptoException {
		if (KeyType.PublicKey != keyType) {
			throw new IllegalArgumentException("Encrypt is only support by public key");
		}
		ckeckKey(keyType);

		lock.lock();
		final SM2Engine engine = getEngine();
		try {
			engine.init(true, new ParametersWithRandom(getCipherParameters(keyType)));
			return engine.processBlock(data, 0, data.length);
		} finally {
			lock.unlock();
		}
	}
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));
}
1098264
public com.google.privacy.dlp.v2.UnwrappedCryptoKeyOrBuilder getUnwrappedOrBuilder() {
    if (sourceCase_ == 2) {
      return (com.google.privacy.dlp.v2.UnwrappedCryptoKey) source_;
    }
    return com.google.privacy.dlp.v2.UnwrappedCryptoKey.getDefaultInstance();
  }
281569
private SM2 initCipherParams() {
		try {
			if (null != this.publicKey) {
				this.publicKeyParams = (ECPublicKeyParameters) ECUtil.generatePublicKeyParameter(this.publicKey);
			}
			if (null != privateKey) {
				this.privateKeyParams = (ECPrivateKeyParameters) ECUtil.generatePrivateKeyParameter(this.privateKey);
			}
		} catch (InvalidKeyException e) {
			throw new CryptoException(e);
		}

		return this;
	}
71484
public static void main(String[] args)
	{
		try
		{
			if (args.length == 0)
			{

				System.err.println("Usage java " + Cryption.class.getName()
				+ " <text>");
				return;

			}

			final String decryptedPassword;

			if (args[0].equals("-d"))
			{
				if (args.length > 2)
				{
					StringBuilder p = new StringBuilder();
					for (int i = 1; i < args.length; i++)
					{
						if (i > 1)
							p.append(' ');

						p.append(args[i]);
					}

					decryptedPassword = p.toString();
				}
				else
				{
					decryptedPassword = args[1];
				}

				System.out.println(getCanonical().decryptText(decryptedPassword));
			}
			else
				System.out.println(CRYPTION_PREFIX
				+ getCanonical().encryptText(args[0]));

		}
		catch (Exception e)
		{

			e.printStackTrace();
		}

	}
113209
public void derEncode (OutputStream out) throws IOException {
        DerOutputStream bytes = new DerOutputStream();
        DerOutputStream tmp = new DerOutputStream();

        bytes.putOID(algid);
        // Setup params from algParams since no DER encoding is given
        if (constructedFromDer == false) {
            if (algParams != null) {
                params = new DerValue(algParams.getEncoded());
            } else {
                params = null;
            }
        }
        if (params == null) {
            // Changes backed out for compatibility with Solaris

            // Several AlgorithmId should omit the whole parameter part when
            // it's NULL. They are ---
            // rfc3370 2.1: Implementations SHOULD generate SHA-1
            // AlgorithmIdentifiers with absent parameters.
            // rfc3447 C1: When id-sha1, id-sha256, id-sha384 and id-sha512
            // are used in an AlgorithmIdentifier the parameters (which are
            // optional) SHOULD be omitted.
            // rfc3279 2.3.2: The id-dsa algorithm syntax includes optional
            // domain parameters... When omitted, the parameters component
            // MUST be omitted entirely
            // rfc3370 3.1: When the id-dsa-with-sha1 algorithm identifier
            // is used, the AlgorithmIdentifier parameters field MUST be absent.
            /*if (
                algid.equals((Object)SHA_oid) ||
                algid.equals((Object)SHA256_oid) ||
                algid.equals((Object)SHA384_oid) ||
                algid.equals((Object)SHA512_oid) ||
                algid.equals((Object)DSA_oid) ||
                algid.equals((Object)sha1WithDSA_oid)) {
                ; // no parameter part encoded
            } else {
                bytes.putNull();
            }*/
            bytes.putNull();
        } else {
            bytes.putDerValue(params);
        }
        tmp.write(DerValue.tag_Sequence, bytes);
        out.write(tmp.toByteArray());
    }