• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

Java Key类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Java中java.security.Key的典型用法代码示例。如果您正苦于以下问题:Java Key类的具体用法?Java Key怎么用?Java Key使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。



Key类属于java.security包,在下文中一共展示了Key类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Java代码示例。

示例1: constructKey

import java.security.Key; //导入依赖的package包/类
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;
}
 
开发者ID:lambdalab-mirror,项目名称:jdk8u-jdk,代码行数:21,代码来源:ConstructKeys.java


示例2: signZip

import java.security.Key; //导入依赖的package包/类
/** 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);
}
 
开发者ID:uhuru-mobile,项目名称:mobile-store,代码行数:22,代码来源:CustomKeySigner.java


示例3: loadKey

import java.security.Key; //导入依赖的package包/类
/** 加载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;
    }
}
 
开发者ID:bridgeli,项目名称:netty-socketio-demo,代码行数:18,代码来源:LoginCipher.java


示例4: engineTranslateKey

import java.security.Key; //导入依赖的package包/类
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");
}
 
开发者ID:Appdome,项目名称:ipack,代码行数:24,代码来源:KeyFactorySpi.java


示例5: engineWrap

import java.security.Key; //导入依赖的package包/类
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);
    }
}
 
开发者ID:SunburstApps,项目名称:OpenJSharp,代码行数:18,代码来源:RSACipher.java


示例6: engineInitSign

import java.security.Key; //导入依赖的package包/类
/**
 * 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);
    }
}
 
开发者ID:AdoptOpenJDK,项目名称:openjdk-jdk10,代码行数:22,代码来源:IntegrityHmac.java


示例7: createTheCipherInstance

import java.security.Key; //导入依赖的package包/类
/**
 * 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;
}
 
开发者ID:SkidJava,项目名称:BaseClient,代码行数:28,代码来源:CryptManager.java


示例8: permitsImpl

import java.security.Key; //导入依赖的package包/类
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;
}
 
开发者ID:AdoptOpenJDK,项目名称:openjdk-jdk10,代码行数:18,代码来源:DisabledAlgorithmConstraints.java


示例9: engineTranslateKey

import java.security.Key; //导入依赖的package包/类
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");
}
 
开发者ID:Appdome,项目名称:ipack,代码行数:20,代码来源:KeyFactorySpi.java


示例10: evaluate

import java.security.Key; //导入依赖的package包/类
/** {@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;
}
 
开发者ID:lamsfoundation,项目名称:lams,代码行数:21,代码来源:EvaluableKeyAlgorithmCredentialCriteria.java


示例11: encrypt

import java.security.Key; //导入依赖的package包/类
/**
 * 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;
}
 
开发者ID:project-sunbird,项目名称:sunbird-utils,代码行数:30,代码来源:DefaultEncryptionServivceImpl.java


示例12: sign

import java.security.Key; //导入依赖的package包/类
/**
 * 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");
    }
}
 
开发者ID:lamsfoundation,项目名称:lams,代码行数:33,代码来源:SigningUtil.java


示例13: main

import java.security.Key; //导入依赖的package包/类
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);
}
 
开发者ID:VictorGil,项目名称:shared-ledger-simulator,代码行数:34,代码来源:KeyGenerationTester.java


示例14: validate

import java.security.Key; //导入依赖的package包/类
@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();
}
 
开发者ID:membaza,项目名称:users-service,代码行数:11,代码来源:JwtServiceImpl.java


示例15: validatePublicKey

import java.security.Key; //导入依赖的package包/类
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;
    }
}
 
开发者ID:JungleTree,项目名称:JungleTree,代码行数:15,代码来源:LoginValidator.java


示例16: getJWEKey

import java.security.Key; //导入依赖的package包/类
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;
}
 
开发者ID:gahana,项目名称:edge-jwt-sample,代码行数:13,代码来源:JWTGenerator.java


示例17: decryptByPrivateKey

import java.security.Key; //导入依赖的package包/类
/**
     * <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;
    }
 
开发者ID:angcyo,项目名称:RLibrary,代码行数:41,代码来源:RSAUtils.java


示例18: decryptByPrivateKey

import java.security.Key; //导入依赖的package包/类
/**
 * 用私钥解密
 *
 * @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);
}
 
开发者ID:weiwenqiang,项目名称:GitHub,代码行数:23,代码来源:Codec.java


示例19: jweDecrypt

import java.security.Key; //导入依赖的package包/类
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();
}
 
开发者ID:gahana,项目名称:edge-jwt-sample,代码行数:15,代码来源:JWTUtil.java


示例20: getRepresentation

import java.security.Key; //导入依赖的package包/类
/**
 * 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;
}
 
开发者ID:Appdome,项目名称:ipack,代码行数:18,代码来源:JceGenericKey.java



注:本文中的java.security.Key类示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Java CardView类代码示例发布时间:2022-05-20
下一篇:
Java DataOutput类代码示例发布时间:2022-05-20
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap