当前位置: 首页>>代码示例>>Java>>正文


Java SecretKey类代码示例

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


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

示例1: encryptData

import javax.crypto.SecretKey; //导入依赖的package包/类
@Override
public void encryptData(String plaintext) {
   System.out.println("-------Encrypting data using AES algorithm-------");
   try {
       KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");
       keyGenerator.init(128);
       SecretKey secretKey = keyGenerator.generateKey();
       byte[] plaintTextByteArray = plaintext.getBytes("UTF8");

       Cipher cipher = Cipher.getInstance("AES");
       cipher.init(Cipher.ENCRYPT_MODE, secretKey);
       byte[] cipherText = cipher.doFinal(plaintTextByteArray);

       System.out.println("Original data: " + plaintext);
       System.out.println("Encrypted data:");
       for (int i = 0; i < cipherText.length; i++) {
           System.out.print(cipherText[i] + " ");

       }
   }
       catch(Exception ex){
           ex.printStackTrace();
       }
   }
 
开发者ID:zhang-jh,项目名称:GOF,代码行数:25,代码来源:AesEncryptionStrategy.java

示例2: encrypt

import javax.crypto.SecretKey; //导入依赖的package包/类
/**
* 加密
* @param datasource byte[]
* @param password String
* @return byte[]
*/
public static String encrypt(String datasource, String password) {
	try {
		if(StringUtils.trimToNull(datasource) == null){
			return null;
		}
		SecureRandom random = new SecureRandom();
		DESKeySpec desKey = new DESKeySpec(password.getBytes());
		// 创建一个密匙工厂,然后用它把DESKeySpec转换成
		SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
		SecretKey securekey = keyFactory.generateSecret(desKey);
		// Cipher对象实际完成加密操作
		Cipher cipher = Cipher.getInstance("DES");
		// 用密匙初始化Cipher对象
		cipher.init(Cipher.ENCRYPT_MODE, securekey, random);
		// 现在,获取数据并加密
		// 正式执行加密操作
		 return new BASE64Encoder().encode(cipher.doFinal(datasource.getBytes()));
		
	} catch (Throwable e) {
		e.printStackTrace();
	}
	return null;
}
 
开发者ID:noseparte,项目名称:Spring-Boot-Server,代码行数:30,代码来源:DES.java

示例3: init

import javax.crypto.SecretKey; //导入依赖的package包/类
/**
 * Initializes the Mac with the given secret key and algorithm parameters.
 *
 * @param key the secret key.
 * @param params the algorithm parameters.
 *
 * @exception InvalidKeyException if the given key is inappropriate for
 * initializing this MAC.
 * @exception InvalidAlgorithmParameterException if the given algorithm
 * parameters are inappropriate for this MAC.
 */
void init(Key key, AlgorithmParameterSpec params)
        throws InvalidKeyException, InvalidAlgorithmParameterException {

    if (params != null) {
        throw new InvalidAlgorithmParameterException
            ("SslMac does not use parameters");
    }

    if (!(key instanceof SecretKey)) {
        throw new InvalidKeyException("Secret key expected");
    }

    secret = key.getEncoded();
    if (secret == null || secret.length == 0) {
        throw new InvalidKeyException("Missing key data");
    }

    reset();
}
 
开发者ID:SunburstApps,项目名称:OpenJSharp,代码行数:31,代码来源:SslMacCore.java

示例4: encrypt

import javax.crypto.SecretKey; //导入依赖的package包/类
/**
 * Encrypt the message with the given key.
 * 
 * @param message
 *            Ciphered message.
 * @param secretKey
 *            The secret key.
 * @return the original message.
 */
protected String encrypt(final String message, final String secretKey) throws Exception { // NOSONAR
	// SSO digest algorithm used for password. This
	final MessageDigest md = MessageDigest.getInstance(getDigest());
	final byte[] digestOfPassword = md.digest(secretKey.getBytes(StandardCharsets.UTF_8));
	final byte[] keyBytes = Arrays.copyOf(digestOfPassword, 24);

	// Cipher implementation.
	final String algo = get("sso.crypt", DEFAULT_IMPL);

	final SecretKey key = new SecretKeySpec(keyBytes, algo);
	final Cipher cipher = Cipher.getInstance(algo);
	cipher.init(Cipher.ENCRYPT_MODE, key);
	final byte[] plainTextBytes = message.getBytes(StandardCharsets.UTF_8);
	final byte[] buf = cipher.doFinal(plainTextBytes);
	final byte[] base64Bytes = Base64.encodeBase64(buf);
	return new String(base64Bytes, StandardCharsets.UTF_8);
}
 
开发者ID:ligoj,项目名称:plugin-sso-salt,代码行数:27,代码来源:SaltedAuthenticationResource.java

示例5: encryptIvNotInitialize2

import javax.crypto.SecretKey; //导入依赖的package包/类
public static void encryptIvNotInitialize2(String message) throws Exception {

        //IV
        IvParameterSpec ivSpec = new IvParameterSpec(new byte[] {1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16});  //Oups. Static

        //Key
        KeyGenerator generator = KeyGenerator.getInstance("AES");
        generator.init(128);
        SecretKey secretKey = generator.generateKey();

        //Encrypt
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding", "BC");
        cipher.init(Cipher.ENCRYPT_MODE, secretKey, ivSpec);
        cipher.update(message.getBytes());

        byte[] data = cipher.doFinal();
        System.out.println(HexUtil.toString(data));
    }
 
开发者ID:blackarbiter,项目名称:Android_Code_Arbiter,代码行数:19,代码来源:ConstantIv.java

示例6: equals

import javax.crypto.SecretKey; //导入依赖的package包/类
/**
 * Tests for equality between the specified object and this
 * object. Two SecretKeySpec objects are considered equal if
 * they are both SecretKey instances which have the
 * same case-insensitive algorithm name and key encoding.
 *
 * @param obj the object to test for equality with this object.
 *
 * @return true if the objects are considered equal, false if
 * <code>obj</code> is null or otherwise.
 */
public boolean equals(Object obj) {
    if (this == obj)
        return true;

    if (!(obj instanceof SecretKey))
        return false;

    String thatAlg = ((SecretKey)obj).getAlgorithm();
    if (!(thatAlg.equalsIgnoreCase(this.algorithm))) {
        if ((!(thatAlg.equalsIgnoreCase("DESede"))
             || !(this.algorithm.equalsIgnoreCase("TripleDES")))
            && (!(thatAlg.equalsIgnoreCase("TripleDES"))
                || !(this.algorithm.equalsIgnoreCase("DESede"))))
        return false;
    }

    byte[] thatKey = ((SecretKey)obj).getEncoded();

    return MessageDigest.isEqual(this.key, thatKey);
}
 
开发者ID:AdoptOpenJDK,项目名称:openjdk-jdk10,代码行数:32,代码来源:SecretKeySpec.java

示例7: updateDigest

import javax.crypto.SecretKey; //导入依赖的package包/类
private static void updateDigest(MessageDigest md,
        byte[] pad1, byte[] pad2,
        SecretKey masterSecret) {
    // Digest the key bytes if available.
    // Otherwise (sensitive key), try digesting the key directly.
    // That is currently only implemented in SunPKCS11 using a private
    // reflection API, so we avoid that if possible.
    byte[] keyBytes = "RAW".equals(masterSecret.getFormat())
                    ? masterSecret.getEncoded() : null;
    if (keyBytes != null) {
        md.update(keyBytes);
    } else {
        digestKey(md, masterSecret);
    }
    md.update(pad1);
    byte[] temp = md.digest();

    if (keyBytes != null) {
        md.update(keyBytes);
    } else {
        digestKey(md, masterSecret);
    }
    md.update(pad2);
    md.update(temp);
}
 
开发者ID:lambdalab-mirror,项目名称:jdk8u-jdk,代码行数:26,代码来源:HandshakeMessage.java

示例8: initFingerprintManager

import javax.crypto.SecretKey; //导入依赖的package包/类
private void initFingerprintManager() throws Throwable {
    mFpManager = (FingerprintManager) mContext.getSystemService(Context.FINGERPRINT_SERVICE);
    if (!mFpManager.isHardwareDetected())
        throw new IllegalStateException("Fingerprint hardware not present");

    KeyStore keyStore = KeyStore.getInstance("AndroidKeyStore");
    KeyGenerator keyGenerator = KeyGenerator.getInstance(
            KeyProperties.KEY_ALGORITHM_AES, "AndroidKeyStore");
    keyStore.load(null);
    keyGenerator.init(new KeyGenParameterSpec.Builder(
            KEY_NAME, KeyProperties.PURPOSE_ENCRYPT | KeyProperties.PURPOSE_DECRYPT)
            .setBlockModes(KeyProperties.BLOCK_MODE_CBC)
            .setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_PKCS7)
            .build());
    keyGenerator.generateKey();

    Cipher cipher = Cipher.getInstance(
            KeyProperties.KEY_ALGORITHM_AES + "/" +
            KeyProperties.BLOCK_MODE_CBC + "/" +
            KeyProperties.ENCRYPTION_PADDING_PKCS7);
    SecretKey key = (SecretKey) keyStore.getKey(KEY_NAME, null);
    cipher.init(Cipher.ENCRYPT_MODE, key);

    mFpHandler = new FingerprintHandler(cipher);

    if (DEBUG) log("Fingeprint manager initialized");
}
 
开发者ID:WrBug,项目名称:GravityBox,代码行数:28,代码来源:FingerprintLauncher.java

示例9: decrypt

import javax.crypto.SecretKey; //导入依赖的package包/类
/**
 * DES
 * @param src
 * @param password
 * @return
 */
public static byte[] decrypt(byte []src, String password) {
    try {
        // DES算法要求有一个可信任的随机数源
        SecureRandom random = new SecureRandom();
        // 创建一个DESKeySpec对象
        DESKeySpec desKey = new DESKeySpec(password.getBytes());
        // 创建一个密匙工厂
        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
        // 将DESKeySpec对象转换成SecretKey对象
        SecretKey securekey = keyFactory.generateSecret(desKey);
        // Cipher对象实际完成解密操作
        Cipher cipher = Cipher.getInstance("DES");
        // 用密匙初始化Cipher对象
        cipher.init(Cipher.DECRYPT_MODE, securekey, random);
        // 真正开始解密操作
        return cipher.doFinal(src);
    } catch (Throwable e) {
        e.printStackTrace();
    }

    return null;
}
 
开发者ID:TIIEHenry,项目名称:TIIEHenry-Android-SDK,代码行数:29,代码来源:DESUtils.java

示例10: engineLookupAndResolveSecretKey

import javax.crypto.SecretKey; //导入依赖的package包/类
/** {@inheritDoc}. */
public SecretKey engineLookupAndResolveSecretKey(Element element, String baseURI, StorageResolver storage)
    throws KeyResolverException {

    if (log.isLoggable(java.util.logging.Level.FINE)) {
        log.log(java.util.logging.Level.FINE, "Can I resolve " + element.getTagName());
    }

    if (!engineCanResolve(element, baseURI, storage)) {
        return null;
    }

    try {
        KeyInfo referent = resolveReferentKeyInfo(element, baseURI, storage);
        if (referent != null) {
            return referent.getSecretKey();
        }
    } catch (XMLSecurityException e) {
        if (log.isLoggable(java.util.logging.Level.FINE)) {
            log.log(java.util.logging.Level.FINE, "XMLSecurityException", e);
        }
    }

    return null;
}
 
开发者ID:AdoptOpenJDK,项目名称:openjdk-jdk10,代码行数:26,代码来源:KeyInfoReferenceResolver.java

示例11: equals

import javax.crypto.SecretKey; //导入依赖的package包/类
public boolean equals(Object obj) {
    if (this == obj)
        return true;

    if (!(obj instanceof SecretKey))
        return false;

    String thatAlg = ((SecretKey)obj).getAlgorithm();
    if (!(thatAlg.equalsIgnoreCase("DESede"))
        && !(thatAlg.equalsIgnoreCase("TripleDES")))
        return false;

    byte[] thatKey = ((SecretKey)obj).getEncoded();
    boolean ret = MessageDigest.isEqual(this.key, thatKey);
    java.util.Arrays.fill(thatKey, (byte)0x00);
    return ret;
}
 
开发者ID:AdoptOpenJDK,项目名称:openjdk-jdk10,代码行数:18,代码来源:DESedeKey.java

示例12: encryptContractCertPrivateKey

import javax.crypto.SecretKey; //导入依赖的package包/类
/**
    * Encrypts the private key of the contract certificate which is to be sent to the EVCC. First, the
    * shared secret based on the ECDH parameters is calculated, then the symmetric session key with which
    * the private key of the contract certificate is to be encrypted.
    * 
    * @param certificateECPublicKey The public key of either the OEM provisioning certificate (in case of 
    * 								 CertificateInstallation) or the to be updated contract certificate
    * 								 (in case of CertificateUpdate)
    * @param ecKeyPair The EC keypair
    * @param contractCertPrivateKey The private key of the contract certificate
    * @return The encrypted private key of the to be installed contract certificate
    */
public static ContractSignatureEncryptedPrivateKeyType encryptContractCertPrivateKey(
		ECPublicKey certificateECPublicKey, 
		KeyPair ecKeyPair,
		ECPrivateKey contractCertPrivateKey) {
	// Generate the shared secret by using the public key of either OEMProvCert or ContractCert
	byte[] sharedSecret = generateSharedSecret((ECPrivateKey) ecKeyPair.getPrivate(), certificateECPublicKey);
	
	if (sharedSecret == null) {
		getLogger().error("Shared secret could not be generated");
		return null;
	}
	
	// The session key is generated using the computed shared secret
	SecretKey sessionKey = generateSessionKey(sharedSecret);
	
	// Finally, the private key of the contract certificate is encrypted using the session key
	ContractSignatureEncryptedPrivateKeyType encryptedContractCertPrivateKey = 
			getContractSignatureEncryptedPrivateKey(sessionKey, contractCertPrivateKey);
	
	return encryptedContractCertPrivateKey;
}
 
开发者ID:V2GClarity,项目名称:RISE-V2G,代码行数:34,代码来源:SecurityUtils.java

示例13: encrypt

import javax.crypto.SecretKey; //导入依赖的package包/类
/**
 * DES加密
 * 
 * @param src
 * @param key
 * @return
 * @throws Exception
 */
public static byte[] encrypt(byte[] src, byte[] key) throws Exception {
    // DES算法要求有一个可信任的随机数源
    SecureRandom sr = new SecureRandom();
    // 从原始密匙数据创建DESKeySpec对象
    DESKeySpec dks = new DESKeySpec(key);
    // 创建一个密匙工厂,然后用它把DESKeySpec转换成一个SecretKey对象
    SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(DES);
    SecretKey securekey = keyFactory.generateSecret(dks);
    // Cipher对象实际完成加密操作
    Cipher cipher = Cipher.getInstance(DES);
    // 用密匙初始化Cipher对象
    cipher.init(Cipher.ENCRYPT_MODE, securekey, sr);
    // 现在,获取数据并加密
    // 正式执行加密操作
    return cipher.doFinal(src);
}
 
开发者ID:wp521,项目名称:MyFire,代码行数:25,代码来源:DESBase64Util.java

示例14: decrypt

import javax.crypto.SecretKey; //导入依赖的package包/类
/**
 * DES解密
 * 
 * @param src
 * @param key
 * @return
 * @throws Exception
 */
public static byte[] decrypt(byte[] src, byte[] key) throws Exception {
    // DES算法要求有一个可信任的随机数源
    SecureRandom sr = new SecureRandom();
    // 从原始密匙数据创建一个DESKeySpec对象
    DESKeySpec dks = new DESKeySpec(key);
    // 创建一个密匙工厂,然后用它把DESKeySpec对象转换成
    // 一个SecretKey对象
    SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(DES);
    SecretKey securekey = keyFactory.generateSecret(dks);
    // Cipher对象实际完成解密操作
    Cipher cipher = Cipher.getInstance(DES);
    // 用密匙初始化Cipher对象
    cipher.init(Cipher.DECRYPT_MODE, securekey, sr);
    // 现在,获取数据并解密
    // 正式执行解密操作
    return cipher.doFinal(src);
}
 
开发者ID:wp521,项目名称:MyFire,代码行数:26,代码来源:DESBase64Util.java

示例15: translateSpoiledKey

import javax.crypto.SecretKey; //导入依赖的package包/类
/**
 * The test case scenario implemented in the method: - create my own secret
 * Key2 as an instance of a class implements PBEKey - spoil the key (set
 * iteration count to 0, for example) - try to translate key -
 * InvalidKeyException is expected.
 *
 * @return true if InvalidKeyException occurred; false - otherwise.
 * @throws NoSuchAlgorithmException
 * @throws InvalidKeySpecException
 */
public boolean translateSpoiledKey() throws NoSuchAlgorithmException,
        InvalidKeySpecException {
    // derive the key
    SecretKey key1 = getMyOwnSecretKey();

    // spoil the key
    ((MyPBKDF2SecretKey) key1).spoil();

    // translate key
    SecretKeyFactory skf = SecretKeyFactory.getInstance(algoToTest);
    try {
        SecretKey key2 = skf.translateKey(key1);
    } catch (InvalidKeyException ike) {
        // this is expected
        return true;
    }

    return false;
}
 
开发者ID:lambdalab-mirror,项目名称:jdk8u-jdk,代码行数:30,代码来源:PBKDF2Translate.java


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