本文整理汇总了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();
}
}
示例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;
}
示例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();
}
示例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);
}
示例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));
}
示例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);
}
示例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);
}
示例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");
}
示例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;
}
示例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;
}
示例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;
}
示例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;
}
示例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);
}
示例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);
}
示例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;
}