本文整理汇总了Java中javax.crypto.Cipher类的典型用法代码示例。如果您正苦于以下问题:Java Cipher类的具体用法?Java Cipher怎么用?Java Cipher使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
Cipher类属于javax.crypto包,在下文中一共展示了Cipher类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: encryptData
import javax.crypto.Cipher; //导入依赖的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: getDefaultAlg
import javax.crypto.Cipher; //导入依赖的package包/类
/**
* Returns the algorithm supported for input mechanism.
* @param mech Mechanism name
* @param alg Algorithm name
* @return Algorithm name
*/
private static String getDefaultAlg(String mech, String alg)
throws NoSuchAlgorithmException {
if (alg == null) {
switch (mech) {
case "Hash_DRBG":
case "HMAC_DRBG":
return "SHA-256";
case "CTR_DRBG":
return (Cipher.getMaxAllowedKeyLength("AES") < 256)
? "AES-128" : "AES-256";
default:
throw new RuntimeException("Mechanism not supported");
}
}
return alg;
}
示例3: SafeApacheCamelCipherPair
import javax.crypto.Cipher; //导入依赖的package包/类
public SafeApacheCamelCipherPair(String transformation)
throws GeneralSecurityException {
this.transformation = transformation;
int d = transformation.indexOf('/');
String cipherName;
if (d > 0) {
cipherName = transformation.substring(0, d);
} else {
cipherName = transformation;
}
KeyGenerator keygen = KeyGenerator.getInstance(cipherName);
keygen.init(new SecureRandom());
Key key = keygen.generateKey();
this.enccipher = Cipher.getInstance(transformation);
this.deccipher = Cipher.getInstance(transformation);
this.enccipher.init(1, key);
byte[] ivp = this.enccipher.getIV();
this.deccipher.init(2, key, ivp == null ? null : new IvParameterSpec(ivp));
}
示例4: constructKey
import javax.crypto.Cipher; //导入依赖的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;
}
示例5: AesDecrypt
import javax.crypto.Cipher; //导入依赖的package包/类
/**
* aes解密-128位
*/
public static String AesDecrypt(String encryptContent, String password) {
try {
KeyGenerator keyGen = KeyGenerator.getInstance("AES");
SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG");
secureRandom.setSeed(password.getBytes());
keyGen.init(128, secureRandom);
SecretKey secretKey = keyGen.generateKey();
byte[] enCodeFormat = secretKey.getEncoded();
SecretKeySpec key = new SecretKeySpec(enCodeFormat, "AES");
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.DECRYPT_MODE, key);
return new String(cipher.doFinal(hex2Bytes(encryptContent)));
} catch (Exception e) {
logger.error("AesDecrypt exception", e);
return null;
}
}
示例6: decrypt
import javax.crypto.Cipher; //导入依赖的package包/类
protected String decrypt(final String value, final String hashedKey) {
if (value == null) {
return null;
}
try {
final Cipher cipher = getCipherObject();
final byte[] ivCiphertext = decode(value.getBytes());
final int ivSize = byte2int(Arrays.copyOfRange(ivCiphertext, 0, INTEGER_LEN));
final byte[] ivValue = Arrays.copyOfRange(ivCiphertext, INTEGER_LEN, (INTEGER_LEN + ivSize));
final byte[] ciphertext = Arrays.copyOfRange(ivCiphertext, INTEGER_LEN + ivSize, ivCiphertext.length);
final IvParameterSpec ivSpec = new IvParameterSpec(ivValue);
cipher.init(Cipher.DECRYPT_MODE, this.key, ivSpec);
final byte[] plaintext = cipher.doFinal(ciphertext);
return new String(plaintext);
} catch (final Exception e) {
throw new RuntimeException(e);
}
}
示例7: encrypt
import javax.crypto.Cipher; //导入依赖的package包/类
public static void encrypt(String message) throws Exception {
byte[] iv = new byte[16];
new SecureRandom().nextBytes(iv);
//IV
IvParameterSpec ivSpec = new IvParameterSpec(iv);
//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));
}
示例8: engineInit
import javax.crypto.Cipher; //导入依赖的package包/类
/**
* Initialises this cipher with key and a source of randomness
*/
protected void engineInit(int mode, Key key, SecureRandom random)
throws InvalidKeyException {
if (mode == Cipher.ENCRYPT_MODE)
if (!(key instanceof PaillierPublicKey))
throw new InvalidKeyException(
"I didn't get a PaillierPublicKey. ");
else if (mode == Cipher.DECRYPT_MODE)
if (!(key instanceof PaillierPrivateKey))
throw new InvalidKeyException(
"I didn't get a PaillierPrivateKey. ");
else
throw new IllegalArgumentException("Bad mode: " + mode);
stateMode = mode;
keyPaillier = key;
SECURE_RANDOM = random;
int modulusLength = ((PaillierKey) key).getN().bitLength();
calculateBlockSizes(modulusLength);
}
示例9: encrypt
import javax.crypto.Cipher; //导入依赖的package包/类
/**
* Implementation of DES encryption
*/
public static String encrypt(String method, byte[] key, byte[] vector, byte[] message) throws Exception {
// generate Key
byte[] keyBytes = generateKey(key, KEY_LEGHT);
SecretKeySpec keySpec = new SecretKeySpec(keyBytes, method);
// generate Initialization Vector
byte[] keyBytesIv = generateVector(vector, VECTOR_LEGHT);
IvParameterSpec ivSpec = new IvParameterSpec(keyBytesIv);
Cipher cipher = Cipher.getInstance(method);
if(hasInitVector(method)){
cipher.init(Cipher.ENCRYPT_MODE, keySpec, ivSpec);
} else {
cipher.init(Cipher.ENCRYPT_MODE, keySpec);
}
byte[] cipherText = cipher.doFinal(message);
return Base64.encodeToString(cipherText, Base64.DEFAULT);
}
示例10: main
import javax.crypto.Cipher; //导入依赖的package包/类
public static void main(String[] args) throws Exception {
try {
byte master[] = {
0, 1, 2, 3, 4
};
SecretKey key = new SecretKeySpec(master, "DES");
Cipher cipher = Cipher.getInstance("DES/ECB/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, key);
throw new RuntimeException("InvalidKeyException not thrown");
} catch (java.security.InvalidKeyException ike) {
ike.printStackTrace();
if (ike.getMessage() != null) {
out.println("Status -- Passed");
} else {
throw new RuntimeException("Error message is not expected when"
+ " InvalidKeyException is thrown");
}
}
}
示例11: readPrivateKey
import javax.crypto.Cipher; //导入依赖的package包/类
private static PKCS8EncodedKeySpec readPrivateKey(File keyFile, Optional<String> keyPassword)
throws IOException, GeneralSecurityException
{
String content = Files.toString(keyFile, US_ASCII);
Matcher matcher = KEY_PATTERN.matcher(content);
if (!matcher.find()) {
throw new KeyStoreException("found no private key: " + keyFile);
}
byte[] encodedKey = base64Decode(matcher.group(1));
if (!keyPassword.isPresent()) {
return new PKCS8EncodedKeySpec(encodedKey);
}
EncryptedPrivateKeyInfo encryptedPrivateKeyInfo = new EncryptedPrivateKeyInfo(encodedKey);
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(encryptedPrivateKeyInfo.getAlgName());
SecretKey secretKey = keyFactory.generateSecret(new PBEKeySpec(keyPassword.get().toCharArray()));
Cipher cipher = Cipher.getInstance(encryptedPrivateKeyInfo.getAlgName());
cipher.init(DECRYPT_MODE, secretKey, encryptedPrivateKeyInfo.getAlgParameters());
return encryptedPrivateKeyInfo.getKeySpec(cipher);
}
示例12: getValueDecryptor
import javax.crypto.Cipher; //导入依赖的package包/类
public InputDecryptor getValueDecryptor(AlgorithmIdentifier keyEncryptionAlgorithm, final AlgorithmIdentifier contentEncryptionAlgorithm, byte[] encryptedContentEncryptionKey)
throws CRMFException
{
Key secretKey = extractSecretKey(keyEncryptionAlgorithm, contentEncryptionAlgorithm, encryptedContentEncryptionKey);
final Cipher dataCipher = helper.createContentCipher(secretKey, contentEncryptionAlgorithm);
return new InputDecryptor()
{
public AlgorithmIdentifier getAlgorithmIdentifier()
{
return contentEncryptionAlgorithm;
}
public InputStream getInputStream(InputStream dataIn)
{
return new CipherInputStream(dataIn, dataCipher);
}
};
}
示例13: encode
import javax.crypto.Cipher; //导入依赖的package包/类
/**
* DES算法,加密
*
* @param data
* 待加密字符串
* @param key
* 加密私钥,长度不能够小于8位
* @return 加密后的字节数组,一般结合Base64编码使用
* @throws Exception
*/
public static String encode(String key, String data) {
if (data == null)
return null;
try {
DESKeySpec dks = new DESKeySpec(key.getBytes());
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
// key的长度不能够小于8位字节
Key secretKey = keyFactory.generateSecret(dks);
Cipher cipher = Cipher.getInstance(ALGORITHM_DES);
IvParameterSpec iv = new IvParameterSpec("12345678".getBytes());
AlgorithmParameterSpec paramSpec = iv;
cipher.init(Cipher.ENCRYPT_MODE, secretKey, paramSpec);
byte[] bytes = cipher.doFinal(data.getBytes());
return byte2String(bytes);
} catch (Exception e) {
e.printStackTrace();
return data;
}
}
示例14: createTheCipherInstance
import javax.crypto.Cipher; //导入依赖的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;
}
示例15: encrypt
import javax.crypto.Cipher; //导入依赖的package包/类
/**
* Implementation of PBE encryption
*/
public static String encrypt(Method method, byte[] key, KeySize keySize, byte[] vector, byte[] message) throws Exception{
// generate Key
byte[] keyBytes = generateKey(key, keySize.getSize());
SecretKeySpec keySpec = new SecretKeySpec(keyBytes , method.getMethod());
// generate Initialization Vector
byte[] keyBytesIv = generateVector(vector, VECTOR_LEGHT);
IvParameterSpec ivSpec = new IvParameterSpec(keyBytesIv);
Cipher cipher = Cipher.getInstance(method.getMethod());
if(hasInitVector(method.getMethod())){
cipher.init(Cipher.ENCRYPT_MODE, keySpec, ivSpec);
} else {
cipher.init(Cipher.ENCRYPT_MODE, keySpec);
}
byte[] cipherText = cipher.doFinal(message);
return Base64.encodeToString(cipherText, Base64.DEFAULT);
}