构建RSA密钥对

@param keySize keySize（必须大于等于512）
@return RSA密钥对
195124
public static KeyHolder buildRSAKey(int keySize) {
        try {
            KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA");
            generator.initialize(keySize);
            KeyPair keyPair = generator.generateKeyPair();
            PrivateKey privateKey = keyPair.getPrivate();
            PublicKey publicKey = keyPair.getPublic();
            return new KeyHolder(privateKey, publicKey);
        } catch (NoSuchAlgorithmException e) {
            throw new SecureException("当前系统没有提供生成RSA密钥对的算法", e);
        }
    }
1226896
protected static function doGenerateKeys($keySize = 2048)
    {
        if (!static::isPhpSecInstalled()) {
            return false;
        }
        $rsa = new Crypt_RSA();
        $rsa->setPrivateKeyFormat(Crypt_RSA::PRIVATE_FORMAT_PKCS1);
        $rsa->setPublicKeyFormat(Crypt_RSA::PUBLIC_FORMAT_PKCS1);
        defined('CRYPT_RSA_EXPONENT') || define('CRYPT_RSA_EXPONENT', 65537);
        defined('CRYPT_RSA_SMALLEST_PRIME') || define('CRYPT_RSA_SMALLEST_PRIME', 64);
        return $rsa->createKey($keySize);
    }
700990
public static CipherUtil buildInstance(byte[] privateKey, byte[] publicKey) {
        PrivateKey priKey = KeyTools.getPrivateKeyFromPKCS8(Algorithms.RSA.name(),
            new ByteArrayInputStream(privateKey));
        PublicKey pubKey = KeyTools.getPublicKeyFromX509(Algorithms.RSA.name(),
            new ByteArrayInputStream(publicKey));
        return buildInstance(priKey, pubKey);
    }
773528
public static byte[] getKey(Integer length) {
        if (!AESUtil.SHORT.equals(length) && !AESUtil.MIDDLE.equals(length) && !AESUtil.LONG.equals(length)) {
            throw new RuntimeException("指定的KeySize不正确");
        }
        SecretKey key = null;
        try {
            KeyGenerator keyGen = KeyGenerator.getInstance("AES");
            keyGen.init(length);
            key = keyGen.generateKey();
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        }
        return key.getEncoded();
    }
69231
function pkcs1pad2(s, n) {
        if (n < s.length + 11) { // TODO: fix for utf-8
            console.error("Message too long for RSA");
            return null;
        }
        var ba = new Array();
        var i = s.length - 1;
        while (i >= 0 && n > 0) {
            var c = s.charCodeAt(i--);
            if (c < 128) { // encode using utf-8
                ba[--n] = c;
            }
            else if ((c > 127) && (c < 2048)) {
                ba[--n] = (c & 63) | 128;
                ba[--n] = (c >> 6) | 192;
            }
            else {
                ba[--n] = (c & 63) | 128;
                ba[--n] = ((c >> 6) & 63) | 128;
                ba[--n] = (c >> 12) | 224;
            }
        }
        ba[--n] = 0;
        var rng = new SecureRandom();
        var x = new Array();
        while (n > 2) { // random non-zero pad
            x[0] = 0;
            while (x[0] == 0) rng.nextBytes(x);
            ba[--n] = x[0];
        }
        ba[--n] = 2;
        ba[--n] = 0;
        return new BigInteger(ba);
    }
771038
def encrypt_with_import_key(self, plain):
        

        n, e = TemplateProcessor.read_serialized_rsa_pub_key(self.import_key['key'])
        n_bit_size = long_bit_size(n)
        bs = 0
        if n_bit_size > 1024-10 and n_bit_size < 1024+10:
            bs = 128
        elif n_bit_size > 2048-10 and n_bit_size < 2048+10:
            bs = 256
        else:
            raise CryptoError('Unknown RSA modulus size: %d', n_bit_size)

        padded = PKCS15.pad(plain, bs=bs, bt=2)
        return rsa_enc(padded, n, e)
831852
public static byte[] normalizeKey(byte[] keyData) {
        if (keyData == null) {
            return RSG.generate(16).getBytes(StandardCharsets.UTF_8);
        } else {
            return normalizeKey(new String(keyData, StandardCharsets.UTF_8))
                    .getBytes(StandardCharsets.UTF_8);
        }
    }
337130
public Integer getKeySize() {
		
		if(keySize == null){
			
			switch (algorithm) {
			case DES:
				keySize = DEFAULT_DES_KEY_SIZE;
				break;

			default:
				keySize = DEFAULT_AES_KEY_SIZE;
				break;
			}
			
		}
		
		return keySize;
		
	}
150116
public static Cipher getRSACipher (int mode, Key key)
    {
        try {
            Cipher cipher = Cipher.getInstance("RSA");
            cipher.init(mode, key);
            return cipher;
        } catch (GeneralSecurityException gse) {
            log.warning("Failed to create cipher", gse);
        }
        return null;
    }
954333
private KeyPair createKeyPair() throws NoSuchAlgorithmException {
		final KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
		final SecureRandom random  = SecureRandom.getInstance("SHA1PRNG");
		random.setSeed(Long.toString(System.currentTimeMillis()).getBytes());
		keyGen.initialize(2048, random);
		final KeyPair keypair = keyGen.generateKeyPair();
		return keypair;
	}
894875
public static PublicKey createPublicKey(byte[] publicKey) {
    if (publicKey == null) {
      return null;
    }
    
    try {
      KeyFactory fac = KeyFactory.getInstance("RSA");
      EncodedKeySpec spec = new X509EncodedKeySpec(publicKey);
      return fac.generatePublic(spec);
    }
    catch (NoSuchAlgorithmException e) {
      throw new IllegalStateException(e);
    }
    catch (InvalidKeySpecException e) {
      throw new IllegalStateException(e);
    }
  }
344171
function Key( options ) {

  if( !(this instanceof Key) )
    return new Key( options )

  this.version = null
  this.type = 'rsa-sha256'
  this.flags = null
  this.granularity = null
  this.hash = null
  this.notes = null
  this.service = null
  this.key = null

  var self = this

  if( options != null ) {
    Object.keys( options ).forEach( function( k, v ) {
      if( Key.fields.indexOf( k ) !== -1 ) {
        self[ k ] = options[ k ]
      }
    })
  }

}
1261368
public static function createRSAKey(int $size, array $values = []): JWK
    {
        if (0 !== $size % 8) {
            throw new InvalidArgumentException('Invalid key size.');
        }

        if (512 > $size) {
            throw new InvalidArgumentException('Key length is too short. It needs to be at least 512 bits.');
        }

        $key = openssl_pkey_new([
            'private_key_bits' => $size,
            'private_key_type' => OPENSSL_KEYTYPE_RSA,
        ]);
        $details = openssl_pkey_get_details($key);
        \openssl_free_key($key);
        $rsa = RSAKey::createFromKeyDetails($details['rsa']);
        $values = \array_merge(
            $values,
            $rsa->toArray()
        );

        return new JWK($values);
    }
882190
private static function validateKey($key, $size)
    {
        $length = strlen($key);

        if ($length < $size) {
            $key = str_pad($key, $size, $key);
        } elseif ($length > $size) {
            $key = substr($key, 0, $size);
        }

        return $key;
    }
971821
public static KeyPair generateKeyPair(String algorithm, int keySize) {
        KeyPairGenerator keyPairGenerator;
        try {
            keyPairGenerator = KeyPairGenerator.getInstance(algorithm);
        } catch (NoSuchAlgorithmException e) {
            throw new IllegalArgumentException(e);
        }
        keyPairGenerator.initialize(keySize);
        return keyPairGenerator.generateKeyPair();
    }
234445
public function getKeySize() {
        return mcrypt_get_key_size($this->supportedAlgos[$this->algo], $this->supportedModes[$this->mode]);
    }
234674
@ShellMethod(key = "generate-key", value = "Generate signing/encryption crypto keys for CAS settings")
    public void generateKey(@ShellOption(value = {"key-size"},
        defaultValue = "256", help = "Key size") final int keySize) {
        LOGGER.info(EncodingUtils.generateJsonWebKey(keySize));
    }