Java 类java.security.Key 实例源码

项目:netty-socketio-demo    文件:LoginCipher.java   
/** 加载key */
public static Key loadKey(String name) {
    try {
        URL url = ResouceUtil.findResource(name, LoginCipher.class);
        InputStream in = url.openStream();
        ObjectInputStream oin = new ObjectInputStream(new BufferedInputStream(in));

        try {
            return (Key) oin.readObject();
        } finally {
            oin.close();
        }
    } catch (Exception e) {
        logger.error("#login_cipher key " + name + " load error! " + e, e);
        return null;
    }
}
项目:ipack    文件:KeyFactorySpi.java   
protected Key engineTranslateKey(
    Key key)
    throws InvalidKeyException
{
    if (key instanceof DHPublicKey)
    {
        return new BCElGamalPublicKey((DHPublicKey)key);
    }
    else if (key instanceof DHPrivateKey)
    {
        return new BCElGamalPrivateKey((DHPrivateKey)key);
    }
    else if (key instanceof ElGamalPublicKey)
    {
        return new BCElGamalPublicKey((ElGamalPublicKey)key);
    }
    else if (key instanceof ElGamalPrivateKey)
    {
        return new BCElGamalPrivateKey((ElGamalPrivateKey)key);
    }

    throw new InvalidKeyException("key type unknown");
}
项目:OpenJSharp    文件:RSACipher.java   
protected byte[] engineWrap(Key key) throws InvalidKeyException,
        IllegalBlockSizeException {
    byte[] encoded = key.getEncoded(); // TODO - unextractable key
    if ((encoded == null) || (encoded.length == 0)) {
        throw new InvalidKeyException("Could not obtain encoded key");
    }
    if (encoded.length > buffer.length) {
        throw new InvalidKeyException("Key is too long for wrapping");
    }
    update(encoded, 0, encoded.length);
    try {
        return doFinal();
    } catch (BadPaddingException e) {
        // should not occur
        throw new InvalidKeyException("Wrapping failed", e);
    }
}
项目:openjdk-jdk10    文件:IntegrityHmac.java   
/**
 * Method engineInitSign
 *
 * @param secretKey
 * @throws XMLSignatureException
 */
protected void engineInitSign(Key secretKey) throws XMLSignatureException {
    if (!(secretKey instanceof SecretKey)) {
        String supplied = secretKey.getClass().getName();
        String needed = SecretKey.class.getName();
        Object exArgs[] = { supplied, needed };

        throw new XMLSignatureException("algorithms.WrongKeyForThisOperation", exArgs);
    }

    try {
        this.macAlgorithm.init(secretKey);
    } catch (InvalidKeyException ex) {
        throw new XMLSignatureException("empty", ex);
    }
}
项目:BaseClient    文件:CryptManager.java   
/**
 * Creates the Cipher Instance.
 */
private static Cipher createTheCipherInstance(int opMode, String transformation, Key key)
{
    try
    {
        Cipher cipher = Cipher.getInstance(transformation);
        cipher.init(opMode, key);
        return cipher;
    }
    catch (InvalidKeyException invalidkeyexception)
    {
        invalidkeyexception.printStackTrace();
    }
    catch (NoSuchAlgorithmException nosuchalgorithmexception)
    {
        nosuchalgorithmexception.printStackTrace();
    }
    catch (NoSuchPaddingException nosuchpaddingexception)
    {
        nosuchpaddingexception.printStackTrace();
    }

    LOGGER.error("Cipher creation failed!");
    return null;
}
项目:openjdk-jdk10    文件:DisabledAlgorithmConstraints.java   
private boolean permitsImpl(Key key) {
    // Verify this constraint is for this public key algorithm
    if (algorithm.compareToIgnoreCase(key.getAlgorithm()) != 0) {
        return true;
    }

    int size = KeyUtil.getKeySize(key);
    if (size == 0) {
        return false;    // we don't allow any key of size 0.
    } else if (size > 0) {
        return !((size < minSize) || (size > maxSize) ||
            (prohibitedSize == size));
    }   // Otherwise, the key size is not accessible. Conservatively,
        // please don't disable such keys.

    return true;
}
项目:ipack    文件:KeyFactorySpi.java   
protected Key engineTranslateKey(
    Key key)
    throws InvalidKeyException
{
    if (key instanceof RSAPublicKey)
    {
        return new BCRSAPublicKey((RSAPublicKey)key);
    }
    else if (key instanceof RSAPrivateCrtKey)
    {
        return new BCRSAPrivateCrtKey((RSAPrivateCrtKey)key);
    }
    else if (key instanceof java.security.interfaces.RSAPrivateKey)
    {
        return new BCRSAPrivateKey((java.security.interfaces.RSAPrivateKey)key);
    }

    throw new InvalidKeyException("key type unknown");
}
项目:jdk8u-jdk    文件:ConstructKeys.java   
static final Key constructKey(byte[] encoding, String keyAlgorithm,
                              int keyType)
    throws InvalidKeyException, NoSuchAlgorithmException {
    Key result = null;
    switch (keyType) {
    case Cipher.SECRET_KEY:
        result = ConstructKeys.constructSecretKey(encoding,
                                                  keyAlgorithm);
        break;
    case Cipher.PRIVATE_KEY:
        result = ConstructKeys.constructPrivateKey(encoding,
                                                   keyAlgorithm);
        break;
    case Cipher.PUBLIC_KEY:
        result = ConstructKeys.constructPublicKey(encoding,
                                                  keyAlgorithm);
        break;
    }
    return result;
}
项目:lams    文件:EvaluableKeyAlgorithmCredentialCriteria.java   
/** {@inheritDoc} */
public Boolean evaluate(Credential target) {
    if (target == null) {
        log.error("Credential target was null");
        return null;
    }
    Key key = getKey(target);
    if (key == null) {
        log.info("Could not evaluate criteria, credential contained no key");
        return null;
    }
    String algorithm = DatatypeHelper.safeTrimOrNullString(key.getAlgorithm());
    if (algorithm == null) {
        log.info("Could not evaluate criteria, key does not specify an algorithm via getAlgorithm()");
        return null;
    }

    Boolean result = keyAlgorithm.equals(algorithm);
    return result;
}
项目:sunbird-utils    文件:DefaultEncryptionServivceImpl.java   
/**
 * this method is used to encrypt the password.
 * 
 * @param value String password
 * @param encryption_key
 * @return encrypted password.
 * @throws NoSuchPaddingException
 * @throws NoSuchAlgorithmException
 * @throws InvalidKeyException
 * @throws BadPaddingException
 * @throws IllegalBlockSizeException
 */
@SuppressWarnings("restriction")
public static String encrypt(String value) throws NoSuchAlgorithmException,
    NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException {
  encryption_key = getSalt();
  Key key = generateKey();
  Cipher c = Cipher.getInstance(ALGORITHM);
  c.init(Cipher.ENCRYPT_MODE, key);

  String valueToEnc = null;
  String eValue = value;
  for (int i = 0; i < ITERATIONS; i++) {
    valueToEnc = encryption_key + eValue;
    byte[] encValue = c.doFinal(valueToEnc.getBytes());
    eValue = new sun.misc.BASE64Encoder().encode(encValue);
  }
  return eValue;
}
项目:lams    文件:SigningUtil.java   
/**
 * Compute the signature or MAC value over the supplied input.
 * 
 * It is up to the caller to ensure that the specified algorithm ID and isMAC flag are consistent with the type of
 * signing key supplied in the signing credential.
 * 
 * @param signingCredential the credential containing the signing key
 * @param jcaAlgorithmID the Java JCA algorithm ID to use
 * @param isMAC flag indicating whether the operation to be performed is a signature or MAC computation
 * @param input the input over which to compute the signature
 * @return the computed signature or MAC value
 * @throws SecurityException throw if the computation process results in an error
 */
public static byte[] sign(Credential signingCredential, String jcaAlgorithmID, boolean isMAC, byte[] input)
        throws SecurityException {
    Logger log = getLogger();

    Key signingKey = SecurityHelper.extractSigningKey(signingCredential);
    if (signingKey == null) {
        log.error("No signing key supplied in signing credential for signature computation");
        throw new SecurityException("No signing key supplied in signing credential");
    }

    if (isMAC) {
        return signMAC(signingKey, jcaAlgorithmID, input);
    } else if (signingKey instanceof PrivateKey) {
        return sign((PrivateKey) signingKey, jcaAlgorithmID, input);
    } else {
        log.error("No PrivateKey present in signing credential for signature computation");
        throw new SecurityException("No PrivateKey supplied for signing");
    }
}
项目:mobile-store    文件:CustomKeySigner.java   
/** KeyStore-type agnostic.  This method will sign the zip file, automatically handling JKS or BKS keystores. */
public static void signZip( ZipSigner zipSigner,
                     String keystorePath,
                     char[] keystorePw,
                     String certAlias,
                     char[] certPw,
                     String signatureAlgorithm,
                     String inputZipFilename,
                     String outputZipFilename)
    throws Exception
{
    zipSigner.issueLoadingCertAndKeysProgressEvent();
    KeyStore keystore = KeyStoreFileManager.loadKeyStore( keystorePath, keystorePw);
    Certificate cert = keystore.getCertificate(certAlias);
    X509Certificate publicKey = (X509Certificate)cert;
    Key key = keystore.getKey(certAlias, certPw);
    PrivateKey privateKey = (PrivateKey)key;

    zipSigner.setKeys( "custom", publicKey, privateKey, signatureAlgorithm, null);
    zipSigner.signZip( inputZipFilename, outputZipFilename);
}
项目:shared-ledger-simulator    文件:KeyGenerationTester.java   
public static void main(String[] args){
    KeyPairGenerator kpg = null;
    try{
        kpg = KeyPairGenerator.getInstance("RSA");
    } catch(NoSuchAlgorithmException ex){
        log.error(ex, ex);
        throw new RuntimeException(ex);
    }
    kpg.initialize(1024);
    KeyPair keyPair = kpg.generateKeyPair();
    Key privateKey = keyPair.getPrivate();
    Key publicKey = keyPair.getPublic();

    Base64.Encoder encoder = Base64.getEncoder();
    String privateKeyBase64Str = encoder.encodeToString(privateKey.getEncoded());
    log.info("Private key in Base64 format:\n" + privateKeyBase64Str);//it creates 1623 chars or 1620 chars

    Base64.Decoder decoder = Base64.getDecoder();
    byte[] privateKeyBytes = decoder.decode(privateKeyBase64Str);
    log.info("The private Key is " + privateKeyBytes.length + " bytes long");
    String privateKeyHex = String.format("%040x", new BigInteger(1, privateKeyBytes));
    log.info("The private key in hexadecimal digits:\n" + privateKeyHex);


    String publicKeyBase64Str = encoder.encodeToString(publicKey.getEncoded());
    log.info("Public key in Base64 format:\n" + publicKeyBase64Str);//it creates 392 chars and again 392 chars for 2048 bits
                                                                    //it creates 162 bytes for 1024 bits, an Ethereum address is 20 bytes (40 hexadecimal digits/characters long)
                                                                    //324 hexadecimal characters, and we use the last 40 as the Ethereum address
    byte[] publicKeyBytes = decoder.decode(publicKeyBase64Str);
    log.info("The public Key is " + publicKeyBytes.length + " bytes long");
    String publicKeyHex = String.format("%040x", new BigInteger(1, publicKeyBytes));
    log.info("The public key in hexadecimal digits:\n" + publicKeyHex);
}
项目:users-service    文件:JwtServiceImpl.java   
@Override
public Claims validate(JwtToken token) {
    final Key signingKey = EncryptionUtil.getPublicKey(
        env.getProperty("service.jwt.public"));

    return Jwts.parser()
        .setSigningKey(signingKey)
        .parseClaimsJws(token.getToken())
        .getBody();
}
项目:JungleTree    文件:LoginValidator.java   
private boolean validatePublicKey(JWSObject jwsToken, Key key) {
    JWSVerifier verifier;
    try {
        verifier = VERIFIER_FACTORY.createJWSVerifier(jwsToken.getHeader(), key);
    } catch (JOSEException ex) {
        return false;
    }

    try {
        return jwsToken.verify(verifier);
    } catch (JOSEException e) {
        return false;
    }
}
项目:edge-jwt-sample    文件:JWTGenerator.java   
private Key getJWEKey(String key, String algo) throws Exception {
    if ("A128GCMKW".equals(algo) || "A192GCMKW".equals(algo) || "A256GCMKW".equals(algo)) {
        return new SecretKeySpec(Base64.getDecoder().decode(key), "AES");
    } else if ("A128KW".equals(algo) || "A192KW".equals(algo) || "A256KW".equals(algo)) {
        return new SecretKeySpec(Base64.getDecoder().decode(key), "AES");
    } else if ("RSA_OAEP".equals(algo) || "RSA1_5".equals(algo)) {
        return getDERPublicKeyFromPEM(key);
    }
    // TODO other AES, RSA and EC variants

    return null;
}
项目:RLibrary    文件:RSAUtils.java   
/**
     * <P>
     * 私钥解密
     * </p>
     *
     * @param encryptedData 已加密数据
     * @param privateKey    私钥(BASE64编码)
     * @return
     * @throws Exception
     */
    public static byte[] decryptByPrivateKey(byte[] encryptedData, String privateKey)
            throws Exception {
        byte[] keyBytes = Base64Utils.decode(privateKey);
        PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes);
        KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
        Key privateK = keyFactory.generatePrivate(pkcs8KeySpec);
//        Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
        Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");

        cipher.init(Cipher.DECRYPT_MODE, privateK);
        int inputLen = encryptedData.length;
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        int offSet = 0;
        byte[] cache;
        int i = 0;
        // 对数据分段解密  
        while (inputLen - offSet > 0) {
            if (inputLen - offSet > MAX_DECRYPT_BLOCK) {
                cache = cipher.doFinal(encryptedData, offSet, MAX_DECRYPT_BLOCK);
            } else {
                cache = cipher.doFinal(encryptedData, offSet, inputLen - offSet);
            }
            out.write(cache, 0, cache.length);
            i++;
            offSet = i * MAX_DECRYPT_BLOCK;
        }
        byte[] decryptedData = out.toByteArray();
        out.close();
        return decryptedData;
    }
项目:GitHub    文件:Codec.java   
/**
 * 用私钥解密
 *
 * @param data
 * @param key
 * @return
 * @throws Exception
 */
public static byte[] decryptByPrivateKey(byte[] data, String key)
        throws Exception {
    byte[] keyBytes = BASE64.decode(key);   // 对密钥解密

    PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes);   // 取得私钥
    KeyFactory keyFactory = KeyFactory.getInstance(Algorithm.RSA.getType());
    Key privateKey = keyFactory.generatePrivate(pkcs8KeySpec);

    // 对数据解密
    Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
    cipher.init(Cipher.DECRYPT_MODE, privateKey);

    return cipher.doFinal(data);
}
项目:edge-jwt-sample    文件:JWTUtil.java   
private static String jweDecrypt(Key key, String jwt) throws Exception {
    JsonWebEncryption jwe = new JsonWebEncryption();
    jwe.setAlgorithmConstraints(
        new AlgorithmConstraints(
            ConstraintType.WHITELIST, 
            KeyManagementAlgorithmIdentifiers.RSA_OAEP));
    jwe.setContentEncryptionAlgorithmConstraints(
        new AlgorithmConstraints(
            ConstraintType.WHITELIST, 
            ContentEncryptionAlgorithmIdentifiers.AES_256_CBC_HMAC_SHA_512));
    jwe.setCompactSerialization(jwt);
    jwe.setKey(key);
    return jwe.getPlaintextString();
}
项目:ipack    文件:JceGenericKey.java   
/**
 * Attempt to simplify the key representation if possible.
 *
 * @param key a provider based key
 * @return the byte encoding if one exists, key object otherwise.
 */
private static Object getRepresentation(Key key)
{
    byte[] keyBytes = key.getEncoded();

    if (keyBytes != null)
    {
        return keyBytes;
    }

    return key;
}
项目:googles-monorepo-demo    文件:MacHashFunctionTest.java   
public void testNulls() {
  NullPointerTester tester = new NullPointerTester()
      .setDefault(String.class, "HmacMD5")
      .setDefault(Key.class, MD5_KEY);
  tester.testAllPublicConstructors(MacHashFunction.class);
  tester.testAllPublicInstanceMethods(new MacHashFunction("HmacMD5", MD5_KEY, "toString"));
}
项目:hadoop    文件:KeyStoreTestUtil.java   
public static void createKeyStore(String filename,
    String password, String alias,
    Key privateKey, Certificate cert)
    throws GeneralSecurityException, IOException {
  KeyStore ks = createEmptyKeyStore();
  ks.setKeyEntry(alias, privateKey, password.toCharArray(),
      new Certificate[]{cert});
  saveKeyStore(ks, filename, password);
}
项目:ibm-cos-sdk-java    文件:S3KeyWrapScheme.java   
/**
 * @param kek
 *            the key encrypting key, which is either an AES key or a public
 *            key
 */
String getKeyWrapAlgorithm(Key kek) {
    String algorithm = kek.getAlgorithm();
    if (S3CryptoScheme.AES.equals(algorithm)) {
        return AESWrap;
    }
    if (S3CryptoScheme.RSA.equals(algorithm)) {
        if (CryptoRuntime.isRsaKeyWrapAvailable())
            return RSA_ECB_OAEPWithSHA256AndMGF1Padding;
    }
    return null;
}
项目:ipack    文件:McEliecePKCSCipherSpi.java   
protected void initCipherDecrypt(Key key, AlgorithmParameterSpec params)
    throws InvalidKeyException, InvalidAlgorithmParameterException
{
    CipherParameters param;
    param = McElieceKeysToParams.generatePrivateKeyParameter((PrivateKey)key);

    digest.reset();
    cipher.init(false, param);
    this.maxPlainTextSize = cipher.maxPlainTextSize;
    this.cipherTextSize = cipher.cipherTextSize;
}
项目:ipack    文件:CipherSpi.java   
protected void engineInit(
    int                 opmode,
    Key                 key,
    AlgorithmParameters params,
    SecureRandom        random) 
throws InvalidKeyException, InvalidAlgorithmParameterException
{
    throw new InvalidAlgorithmParameterException("can't handle parameters in ElGamal");
}
项目:poppynotes    文件:NoteEncryptionServiceImpl.java   
private Key createKey(String key, String principalName) {
    byte[] keyBytes = decodeBase64(key);
    byte[] principalBytes = getPrincipalWithoutEmailTail(principalName).getBytes(UTF_8);

    if(principalBytes.length > MAX_KEY_SIZE_BYTES){
        principalBytes = ArrayUtils.subarray(principalBytes, 0, MAX_KEY_SIZE_BYTES);
    }
    keyBytes = concatenateByteArrays(keyBytes,principalBytes);
    return new SecretKeySpec(keyBytes, 0, keyBytes.length, ENCRYPTION_ALGORITHM);
}
项目:RoboInsta    文件:InstagramHashing.java   
public static String generateHash(String key, String string) {
    SecretKeySpec object = new SecretKeySpec(key.getBytes(), "HmacSHA256");
    try {
        Mac mac = Mac.getInstance("HmacSHA256");
        mac.init((Key) object);
        byte[] byteArray = mac.doFinal(string.getBytes("UTF-8"));
        return new String(new Hex().encode(byteArray), "ISO-8859-1");
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}
项目:openjdk-jdk10    文件:NativeRSACipher.java   
@Override
protected synchronized void engineInit(int opmode, Key key, AlgorithmParameters params,
        SecureRandom random)
        throws InvalidKeyException, InvalidAlgorithmParameterException {
    if (params != null) {
        throw new InvalidAlgorithmParameterException("No Parameters can be specified");
    }
    engineInit(opmode, key, (AlgorithmParameterSpec) null, random);
}
项目:openjdk-jdk10    文件:Main.java   
private void checkWeak(String label, String sigAlg, Key key) {

        if (sigAlg != null && !DISABLED_CHECK.permits(
                SIG_PRIMITIVE_SET, sigAlg, null)) {
            weakWarnings.add(String.format(
                    rb.getString("whose.sigalg.risk"), label, sigAlg));
        }
        if (key != null && !DISABLED_CHECK.permits(SIG_PRIMITIVE_SET, key)) {
            weakWarnings.add(String.format(
                    rb.getString("whose.key.risk"),
                    label,
                    String.format(rb.getString("key.bit"),
                            KeyUtil.getKeySize(key), key.getAlgorithm())));
        }
    }
项目:ditb    文件:Context.java   
public Context setKey(Key key) {
  Preconditions.checkNotNull(cipher, "Context does not have a cipher");
  // validate the key length
  byte[] encoded = key.getEncoded();
  if (encoded.length != cipher.getKeyLength()) {
    throw new RuntimeException("Illegal key length, have=" + encoded.length +
      ", want=" + cipher.getKeyLength());
  }
  this.key = key;
  this.keyHash = MD5Hash.getMD5AsHex(encoded);
  return this;
}
项目:ipack    文件:KeyFactorySpi.java   
protected Key engineTranslateKey(
    Key key)
    throws InvalidKeyException
{
    if (key instanceof DSAPublicKey)
    {
        return new BCDSAPublicKey((DSAPublicKey)key);
    }
    else if (key instanceof DSAPrivateKey)
    {
        return new BCDSAPrivateKey((DSAPrivateKey)key);
    }

    throw new InvalidKeyException("key type unknown");
}
项目:xitk    文件:ConvertKeystoreCmd.java   
@Override
protected Object execute0() throws Exception {
    File realInFile = new File(IoUtil.expandFilepath(inFile));
    File realOutFile = new File(IoUtil.expandFilepath(outFile));

    if (CompareUtil.equalsObject(realInFile, realOutFile)) {
        throw new IllegalCmdParamException("in and out cannot be the same");
    }

    KeyStore inKs = KeyStore.getInstance(inType);
    KeyStore outKs = KeyStore.getInstance(outType);
    outKs.load(null);

    char[] inPassword = readPasswordIfNotSet("password of the source keystore", inPwd);
    FileInputStream inStream = new FileInputStream(realInFile);
    try {
        inKs.load(inStream, inPassword);
    } finally {
        inStream.close();
    }

    char[] outPassword = readPasswordIfNotSet("password of the destination keystore", outPwd);
    Enumeration<String> aliases = inKs.aliases();
    while (aliases.hasMoreElements()) {
        String alias = aliases.nextElement();
        if (inKs.isKeyEntry(alias)) {
            Certificate[] certs = inKs.getCertificateChain(alias);
            Key key = inKs.getKey(alias, inPassword);
            outKs.setKeyEntry(alias, key, outPassword, certs);
        } else {
            Certificate cert = inKs.getCertificate(alias);
            outKs.setCertificateEntry(alias, cert);
        }
    }

    ByteArrayOutputStream bout = new ByteArrayOutputStream(4096);
    outKs.store(bout, outPassword);
    saveVerbose("saved destination keystore to file", realOutFile, bout.toByteArray());
    return null;
}
项目:neoscada    文件:XMLSignatureWidgetFactory.java   
private void sign ( final Key key, final Certificate cert )
{
    try
    {
        performSign ( key, cert );
    }
    catch ( final Exception e )
    {
        final IStatus status = StatusHelper.convertStatus ( Activator.PLUGIN_ID, e );
        StatusManager.getManager ().handle ( status );
        ErrorDialog.openError ( this.text.getShell (), "Error", "Error signing", status );
    }
}
项目:ipack    文件:RainbowKeyFactorySpi.java   
/**
 * Translates a key into a form known by the FlexiProvider. Currently the
 * following key types are supported: RainbowPrivateKey, RainbowPublicKey.
 *
 * @param key the key
 * @return a key of a known key type
 * @throws InvalidKeyException if the key is not supported.
 */
public final Key engineTranslateKey(Key key)
    throws InvalidKeyException
{
    if (key instanceof BCRainbowPrivateKey || key instanceof BCRainbowPublicKey)
    {
        return key;
    }

    throw new InvalidKeyException("Unsupported key type");
}
项目:jeesupport    文件:CryptoTest.java   
public void testRSA() {
    System.out.println( "-- RSA ---------------------" );
    try {
        Map< String , Key > key_map = RSAUtils.s_genkeys_map();

        byte[] pub_key = RSAUtils.s_public_key_byte( key_map );
        byte[] pri_key = RSAUtils.s_private_key_byte( key_map );

        String pub_key_str = B64Utils.s_encode( pub_key );
        System.out.println( "  公钥              : [" + new String( pub_key ) + "]" );
        System.out.println( "  公钥BASE64: [" + pub_key_str + "]" );
        System.out.println( "  私钥: [" + new String( pri_key ) + "]"  );
        System.out.println( "  私钥BASE64: [" + B64Utils.s_encode( pub_key ) + "]" );

        String txt = "DABA-C5D2-05C127B8-77D330BCB674F506";
        System.out.println( "  内容:[" + txt + "]" );
        byte[] byt_e = RSAUtils.s_encrypt_private( pri_key , txt.getBytes() );
        byte[] byt_d = RSAUtils.s_decrypt_public( B64Utils.s_decode( pub_key_str ) , byt_e );
        System.out.println( "私钥加密,公钥解密: [" + new String( byt_d ) + "]");

        byt_e = RSAUtils.s_encrypt_public( pub_key , txt.getBytes() );
        byt_d = RSAUtils.s_decrypt_private( pri_key , byt_e );
        System.out.println( "公钥加密,私钥解密: [" + new String( byt_d ) + "]" );
    } catch ( Exception e ) {
        System.out.println( "私钥或者内容错误!" );
    }
    System.out.println( "-- RSA ---------------------" );
}
项目:lams    文件:EvaluableKeyAlgorithmCredentialCriteria.java   
/**
 * Get the key contained within the credential.
 * 
 * @param credential the credential containing a key
 * @return the key from the credential
 */
private Key getKey(Credential credential) {
    if (credential.getPublicKey() != null) {
        return credential.getPublicKey();
    } else if (credential.getSecretKey() != null) {
        return credential.getSecretKey();
    } else if (credential.getPrivateKey() != null) {
        // There should have been a corresponding public key, but just in case...
        return credential.getPrivateKey();
    } else {
        return null;
    }

}
项目:javaide    文件:ZipSigner.java   
public void signZip(URL keystoreURL,
                    String keystoreType,
                    char[] keystorePw,
                    String certAlias,
                    char[] certPw,
                    String signatureAlgorithm,
                    String inputZipFilename,
                    String outputZipFilename)
        throws ClassNotFoundException, IllegalAccessException, InstantiationException,
        IOException, GeneralSecurityException {
    InputStream keystoreStream = null;


    try {
        KeyStore keystore = null;
        if (keystoreType == null) keystoreType = KeyStore.getDefaultType();
        keystore = KeyStore.getInstance(keystoreType);

        keystoreStream = keystoreURL.openStream();
        keystore.load(keystoreStream, keystorePw);
        Certificate cert = keystore.getCertificate(certAlias);
        X509Certificate publicKey = (X509Certificate) cert;
        Key key = keystore.getKey(certAlias, certPw);
        PrivateKey privateKey = (PrivateKey) key;

        setKeys("custom", publicKey, privateKey, signatureAlgorithm, null);

        signZip(inputZipFilename, outputZipFilename);
    } finally {
        if (keystoreStream != null) keystoreStream.close();
    }
}
项目:openjdk-jdk10    文件:KeyWrapper.java   
private static void doTest(String provider, String algo) throws Exception {
    SecretKey key;
    SecretKey keyToWrap;

    // init a secret Key
    KeyGenerator kg = KeyGenerator.getInstance(AES, PROVIDER);
    kg.init(KEY_LENGTH);
    key = kg.generateKey();
    keyToWrap = kg.generateKey();

    // initialization
    Cipher cipher = Cipher.getInstance(algo, provider);
    cipher.init(Cipher.WRAP_MODE, key);
    AlgorithmParameters params = cipher.getParameters();

    // wrap the key
    byte[] keyWrapper = cipher.wrap(keyToWrap);
    try {
        // check if we can't wrap it again with the same key/IV
        keyWrapper = cipher.wrap(keyToWrap);
        throw new RuntimeException(
                "FAILED: expected IllegalStateException hasn't "
                        + "been thrown ");
    } catch (IllegalStateException ise) {
        System.out.println(ise.getMessage());
        System.out.println("Expected exception");
    }

    // unwrap the key
    cipher.init(Cipher.UNWRAP_MODE, key, params);
    cipher.unwrap(keyWrapper, algo, Cipher.SECRET_KEY);

    // check if we can unwrap second time
    Key unwrapKey = cipher.unwrap(keyWrapper, algo, Cipher.SECRET_KEY);

    if (!Arrays.equals(keyToWrap.getEncoded(), unwrapKey.getEncoded())) {
        throw new RuntimeException(
                "FAILED: original and unwrapped keys are not equal");
    }
}
项目:springboot-training    文件:RSACoder.java   
/**
 * 解密<br>
 * 用公钥解密
 * 
 * @param data
 * @param key
 * @return
 * @throws Exception
 */
public static byte[] decryptByPublicKey(byte[] data, String key) {
    try {
        // 对密钥解密
        byte[] keyBytes = decryptBASE64(key);

        // 取得公钥
        X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(keyBytes);
        KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
        Key publicKey = keyFactory.generatePublic(x509KeySpec);

        // 对数据解密
        // Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
        Cipher cipher = Cipher.getInstance(RSA_java);
        cipher.init(Cipher.DECRYPT_MODE, publicKey);

        byte[] result = {};
        for (int i = 0; i < data.length; i += 128) {
            byte[] split = splitBytes(data, i, 128);
            byte[] doFinal = cipher.doFinal(split);
            result = appBytes(result, doFinal);
        }

        return result;
    } catch (Exception e) {
        throw new ZhhrUtilException("用公钥解密出错" + e.getMessage());
    }
}
项目:OpenJSharp    文件:SignatureECDSA.java   
/** @inheritDoc */
protected void engineInitVerify(Key publicKey) throws XMLSignatureException {

    if (!(publicKey instanceof PublicKey)) {
        String supplied = publicKey.getClass().getName();
        String needed = PublicKey.class.getName();
        Object exArgs[] = { supplied, needed };

        throw new XMLSignatureException("algorithms.WrongKeyForThisOperation", exArgs);
    }

    try {
        this.signatureAlgorithm.initVerify((PublicKey) publicKey);
    } catch (InvalidKeyException ex) {
        // reinstantiate Signature object to work around bug in JDK
        // see: http://bugs.sun.com/view_bug.do?bug_id=4953555
        Signature sig = this.signatureAlgorithm;
        try {
            this.signatureAlgorithm = Signature.getInstance(signatureAlgorithm.getAlgorithm());
        } catch (Exception e) {
            // this shouldn't occur, but if it does, restore previous
            // Signature
            if (log.isLoggable(java.util.logging.Level.FINE)) {
                log.log(java.util.logging.Level.FINE, "Exception when reinstantiating Signature:" + e);
            }
            this.signatureAlgorithm = sig;
        }
        throw new XMLSignatureException("empty", ex);
    }
}