當前位置: 首頁>>代碼示例>>Java>>正文


Java Key類代碼示例

本文整理匯總了Java中java.security.Key的典型用法代碼示例。如果您正苦於以下問題:Java Key類的具體用法?Java Key怎麽用?Java Key使用的例子?那麽, 這裏精選的類代碼示例或許可以為您提供幫助。


Key類屬於java.security包,在下文中一共展示了Key類的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的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


注:本文中的java.security.Key類示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。