本文整理了Java中java.security.Key
类的一些代码示例,展示了Key
类的具体用法。这些代码示例主要来源于Github
/Stackoverflow
/Maven
等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。Key
类的具体详情如下:
包路径:java.security.Key
类名称:Key
[英]Key is the common interface for all keys.
[中]键是所有键的公共接口。
代码示例来源:origin: stackoverflow.com
KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
keyPairGenerator.initialize(1024);
KeyPair keyPair = keyPairGenerator.genKeyPair();
byte[] encodedprivkey = keyPair.getPrivate().getEncoded();
SecureRandom random = new SecureRandom();
byte[] salt = new byte[8];
random.nextBytes(salt);
pbeCipher.init(Cipher.ENCRYPT_MODE, pbeKey, pbeParamSpec);
byte[] ciphertext = pbeCipher.doFinal(encodedprivkey);
代码示例来源:origin: aws/aws-sdk-java
if (materials.getKeyPair() != null) {
kek = materials.getKeyPair().getPrivate();
if (kek == null) {
throw new SdkClientException("Key encrypting key not available");
.getInstance(keyWrapAlgo) : Cipher.getInstance(
keyWrapAlgo, securityProvider);
cipher.init(Cipher.UNWRAP_MODE, kek);
return (SecretKey) cipher.unwrap(cekSecured, keyWrapAlgo,
Cipher.SECRET_KEY);
cipher = Cipher.getInstance(kek.getAlgorithm(),
securityProvider);
} else {
cipher = Cipher.getInstance(kek.getAlgorithm());
cipher.init(Cipher.DECRYPT_MODE, kek);
代码示例来源:origin: wildfly/wildfly
RawKey(Key original) {
algorithm = original.getAlgorithm();
format = original.getFormat();
final byte[] encoded = original.getEncoded();
this.encoded = encoded == null ? null : encoded.clone();
}
代码示例来源:origin: google/guava
private static String hmacToString(String methodName, Key key) {
return String.format(
"Hashing.%s(Key[algorithm=%s, format=%s])",
methodName, key.getAlgorithm(), key.getFormat());
}
代码示例来源:origin: SonarSource/sonarqube
@Test
public void loadSecretKeyFromFile_trim_content() throws Exception {
URL resource = getClass().getResource("/org/sonar/api/config/AesCipherTest/non_trimmed_secret_key.txt");
String path = new File(resource.toURI()).getCanonicalPath();
AesCipher cipher = new AesCipher(null);
Key secretKey = cipher.loadSecretFileFromFile(path);
assertThat(secretKey.getAlgorithm()).isEqualTo("AES");
assertThat(secretKey.getEncoded().length).isGreaterThan(10);
}
代码示例来源:origin: stackoverflow.com
byte[] data = "test".getBytes("UTF8");
KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
kpg.initialize(512);
KeyPair keyPair = kpg.genKeyPair();
byte[] pk = keyPair.getPublic().getEncoded();
X509EncodedKeySpec spec = new X509EncodedKeySpec(pk);
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
PublicKey pubKey = keyFactory.generatePublic(spec);
Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
cipher.init(Cipher.ENCRYPT_MODE, pubKey);
byte[] encrypted = cipher.doFinal(data);
byte[] priv = keyPair.getPrivate().getEncoded();
PKCS8EncodedKeySpec spec2 = new PKCS8EncodedKeySpec(priv);
PrivateKey privKey = keyFactory.generatePrivate(spec2);
cipher.init(Cipher.DECRYPT_MODE, privKey);
byte[] plain = cipher.doFinal(encrypted);
System.out.println(new String(plain, "UTF8")); //=> "test"
代码示例来源:origin: stackoverflow.com
KeyPairGenerator gen = KeyPairGenerator.getInstance("RSA");
KeyPair pair = gen.generateKeyPair();
FileOutputStream ospvt = new FileOutputStream("pvt.der");
try {
ospvt.write(pair.getPrivate().getEncoded());
ospvt.flush();
} finally {
ospvt.close();
}
FileOutputStream ospub = new FileOutputStream("pub.der");
try {
ospub.write(pair.getPublic().getEncoded());
ospub.flush();
} finally {
ospub.close();
}
代码示例来源:origin: stackoverflow.com
KeyPairGenerator keyGen = KeyPairGenerator.getInstance("DSA");
keyGen.initialize(1024, new SecureRandom());
KeyPair pair = keyGen.generateKeyPair();
PrivateKey priv = pair.getPrivate();
dsa.initSign(priv);
PublicKey pub = pair.getPublic();
byte[] encoded = pub.getEncoded();
PublicKey fromEncoded = KeyFactory.getInstance("DSA", "SUN").generatePublic(new X509EncodedKeySpec(encoded));
dsa.initVerify(fromEncoded);
代码示例来源:origin: aws/aws-sdk-java
if (materials.getKeyPair() != null) {
kek = materials.getKeyPair().getPublic();
} else {
if (keyWrapAlgo != null) {
Cipher cipher = provider == null ? Cipher
.getInstance(keyWrapAlgo) : Cipher.getInstance(
keyWrapAlgo, provider);
cipher.init(Cipher.WRAP_MODE, kek, srand);
return new SecuredCEK(cipher.wrap(cek), keyWrapAlgo, matdesc);
String algo = kek.getAlgorithm();
if (provider != null) {
cipher = Cipher.getInstance(algo, provider);
代码示例来源:origin: stackoverflow.com
KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
kpg.initialize(2048);
KeyPair keyPair = kpg.generateKeyPair();
PublicKey pub = keyPair.getPublic();
PrivateKey prv = keyPair.getPrivate();
byte[] pubBytes = pub.getEncoded();
byte[] prvBytes = prv.getEncoded();
// now save pubBytes or prvBytes
// to recover the key
KeyFactory kf = KeyFactory.getInstance("RSA");
PrivateKey prv_recovered = kf.generatePrivate(new PKCS8EncodedKeySpec(prvBytes));
PublicKey pub_recovered = kf.generatePublic(new X509EncodedKeySpec(pubBytes));
System.out.println("Private Key: \n" + prv_recovered.toString());
System.out.println("Public Key: \n" + pub_recovered.toString());
代码示例来源:origin: stackoverflow.com
DHParameterSpec dhSkipParamSpec = new DHParameterSpec(skip1024Modulus, skip1024Base);
KeyPairGenerator aliceKpairGen = KeyPairGenerator.getInstance("DH", "BC");
aliceKpairGen.initialize(dhSkipParamSpec);
KeyPair aliceKpair = aliceKpairGen.generateKeyPair();
byte[] alicePubKeyEnc = aliceKpair.getPublic().getEncoded();
aliceKeyAgree = KeyAgreement.getInstance("DH", "BC");
aliceKeyAgree.init(aliceKpair.getPrivate());
//... obtaining Bob's Public Key
aliceKeyFac = KeyFactory.getInstance("DH", "BC");
X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(bobPubKeyEnc);
bobPubKey = aliceKeyFac.generatePublic(x509KeySpec);
aliceKeyAgree.doPhase(bobPubKey, true);
SecretKey aliceAesKey = aliceKeyAgree.generateSecret("AES");
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding", "BC");
cipher.init(Cipher.ENCRYPT_MODE, aliceAesKey);
byte[] cipherText = cipher.doFinal(plaintext.getBytes());
代码示例来源:origin: apache/hbase
@Test
public void testWALKeyWrapping() throws Exception {
// set up the key provider for testing to resolve a key for our test subject
Configuration conf = new Configuration(); // we don't need HBaseConfiguration for this
conf.set(HConstants.CRYPTO_KEYPROVIDER_CONF_KEY, KeyProviderForTesting.class.getName());
// generate a test key
byte[] keyBytes = new byte[AES.KEY_LENGTH];
new SecureRandom().nextBytes(keyBytes);
String algorithm = conf.get(HConstants.CRYPTO_WAL_ALGORITHM_CONF_KEY, HConstants.CIPHER_AES);
Key key = new SecretKeySpec(keyBytes, algorithm);
// wrap the test key
byte[] wrappedKeyBytes = EncryptionUtil.wrapKey(conf, "hbase", key);
assertNotNull(wrappedKeyBytes);
// unwrap
Key unwrappedKey = EncryptionUtil.unwrapWALKey(conf, "hbase", wrappedKeyBytes);
assertNotNull(unwrappedKey);
// only secretkeyspec supported for now
assertTrue(unwrappedKey instanceof SecretKeySpec);
// did we get back what we wrapped?
assertTrue("Unwrapped key bytes do not match original",
Bytes.equals(keyBytes, unwrappedKey.getEncoded()));
}
代码示例来源:origin: apache/ignite
/** {@inheritDoc} */
@Override public byte[] decrypt(byte[] data, Serializable key) {
assert key instanceof KeystoreEncryptionKey;
ensureStarted();
try {
SecretKeySpec keySpec = new SecretKeySpec(((KeystoreEncryptionKey)key).key().getEncoded(), CIPHER_ALGO);
Cipher cipher = aesWithPadding.get();
cipher.init(DECRYPT_MODE, keySpec, new IvParameterSpec(data, 0, cipher.getBlockSize()));
return cipher.doFinal(data, cipher.getBlockSize(), data.length - cipher.getBlockSize());
}
catch (InvalidAlgorithmParameterException | InvalidKeyException | IllegalBlockSizeException |
BadPaddingException e) {
throw new IgniteSpiException(e);
}
}
代码示例来源:origin: stackoverflow.com
KeyGenerator kgenerator = KeyGenerator.getInstance("AES");
SecureRandom random = new SecureRandom();
kgenerator.init(128, random);
Key aeskey = kgenerator.generateKey();
KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
kpg.initialize(1024, random);
KeyPair kpa = kpg.genKeyPair();
PublicKey pubKey = kpa.getPublic();
PrivateKey privKey = kpa.getPrivate();
// Encrypt the generated Symmetric AES Key using RSA cipher
Cipher rsaCipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
rsaCipher.init(Cipher.WRAP_MODE, pubKey);
byte[] encryptedSymmKey = rsaCipher.wrap(aeskey);
// RSA Decryption of Encrypted Symmetric AES key
rsaCipher.init(Cipher.UNWRAP_MODE, privKey);
Key decryptedKey = rsaCipher.unwrap(encryptedSymmKey, "AES", Cipher.SECRET_KEY);
System.out.println("Decrypted Key Length: " + decryptedKey.getEncoded().length * 8); // -> 128
代码示例来源:origin: stackoverflow.com
@Test
public void testKeyConversion() throws GeneralSecurityException {
/* Generate random key pair */
KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
AlgorithmParameterSpec spec = new RSAKeyGenParameterSpec(1024, RSAKeyGenParameterSpec.F4);
keyPairGenerator.initialize(spec, new SecureRandom());
KeyPair keyPair = keyPairGenerator.generateKeyPair();
/* Encode private key as PKCS#8 base64 string */
byte[] privKeyBytes = keyPair.getPrivate().getEncoded();
String privKeyStr = DatatypeConverter.printBase64Binary(privKeyBytes);
/* Decode private key as PKCS#8 base64 string */
byte[] privKeyBytes2 = DatatypeConverter.parseBase64Binary(privKeyStr);
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
PKCS8EncodedKeySpec privSpec = new PKCS8EncodedKeySpec(privKeyBytes2);
PrivateKey privateKey = keyFactory.generatePrivate(privSpec);
/* Ensure key is the same */
byte[] privKeyBytes3 = privateKey.getEncoded();
assertEquals(
DatatypeConverter.printHexBinary(privKeyBytes),
DatatypeConverter.printHexBinary(privKeyBytes3));
}
代码示例来源:origin: wildfly/wildfly
/** Encrypts the current secret key with the requester's public key (the requester will decrypt it with its private key) */
protected byte[] encryptSecretKey(Key secret_key, PublicKey public_key) throws Exception {
Cipher tmp;
if (provider != null && !provider.trim().isEmpty())
tmp=Cipher.getInstance(asym_algorithm, provider);
else
tmp=Cipher.getInstance(asym_algorithm);
tmp.init(Cipher.ENCRYPT_MODE, public_key);
// encrypt current secret key
return tmp.doFinal(secret_key.getEncoded());
}
代码示例来源:origin: GlowstoneMC/Glowstone
/**
* Generates an X509 formatted key used in authentication.
*
* @param base The key to use to generate a public key from its key spec.
* @return The X509 formatted key.
*/
public static Key generateX509Key(Key base) {
Key key = null;
try {
X509EncodedKeySpec encodedKeySpec = new X509EncodedKeySpec(base.getEncoded());
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
key = keyFactory.generatePublic(encodedKeySpec);
} catch (Exception ex) {
GlowServer.logger.log(Level.SEVERE, "Unable to generate X509 encoded key", ex);
}
return key;
}
}
代码示例来源:origin: plutext/docx4j
int keySizeInBytes = key.getEncoded().length;
if (padding == null) padding = "NoPadding";
if (Cipher.getMaxAllowedKeyLength(cipherAlgorithm.jceId) < keySizeInBytes*8) {
throw new EncryptedDocumentException("Export Restrictions in place - please install JCE Unlimited Strength Jurisdiction Policy files");
cipher = Cipher.getInstance(cipherAlgorithm.jceId);
} else if (cipherAlgorithm.needsBouncyCastle) {
registerBouncyCastle();
cipher = Cipher.getInstance(cipherAlgorithm.jceId + "/" + chain.jceId + "/" + padding, "BC");
} else {
cipher = Cipher.getInstance(cipherAlgorithm.jceId + "/" + chain.jceId + "/" + padding);
AlgorithmParameterSpec aps;
if (cipherAlgorithm == CipherAlgorithm.rc2) {
aps = new RC2ParameterSpec(key.getEncoded().length*8, vec);
} else {
aps = new IvParameterSpec(vec);
cipher.init(cipherMode, key, aps);
代码示例来源:origin: stackoverflow.com
public static String generateKeyPair() {
try {
KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA", "BC");
kpg.initialize(2048, new SecureRandom());
KeyPair pair = kpg.generateKeyPair();
PKCS8EncodedKeySpec keyspec = new PKCS8EncodedKeySpec(pair.getPrivate().getEncoded());
StringBuilder sb = new StringBuilder();
sb.append("-----BEGIN PRIVATE KEY-----");
sb.append(new String(Base64.encode(keyspec.getEncoded())));
sb.append("-----END PRIVATE KEY-----");
return new String(Base64.encode(sb.toString().getBytes()));
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (NoSuchProviderException e) {
e.printStackTrace();
}
return null;
}
代码示例来源:origin: robovm/robovm
return (T) (new PKCS8EncodedKeySpec(key.getEncoded()));
throw new InvalidKeySpecException("'keySpec' is neither DSAPrivateKeySpec nor PKCS8EncodedKeySpec");
return (T) (new X509EncodedKeySpec(key.getEncoded()));
throw new InvalidKeySpecException("'keySpec' is neither DSAPublicKeySpec nor X509EncodedKeySpec");
throw new InvalidKeySpecException("'key' is neither DSAPublicKey nor DSAPrivateKey");
内容来源于网络,如有侵权,请联系作者删除!