下面列出了java.security.Key#getEncoded ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@Test
public void simple() throws GeneralSecurityException {
DirectKmsMaterialProvider prov = new DirectKmsMaterialProvider(kms, keyId);
EncryptionMaterials eMat = prov.getEncryptionMaterials(ctx);
SecretKey encryptionKey = eMat.getEncryptionKey();
assertNotNull(encryptionKey);
Key signingKey = eMat.getSigningKey();
assertNotNull(signingKey);
DecryptionMaterials dMat = prov.getDecryptionMaterials(ctx(eMat));
assertEquals(encryptionKey, dMat.getDecryptionKey());
assertEquals(signingKey, dMat.getVerificationKey());
String expectedEncAlg = encryptionKey.getAlgorithm() + "/"
+ (encryptionKey.getEncoded().length * 8);
String expectedSigAlg = signingKey.getAlgorithm() + "/"
+ (signingKey.getEncoded().length * 8);
Map<String, String> kmsCtx = kms.getSingleEc();
assertEquals(expectedEncAlg,
kmsCtx.get("*" + WrappedRawMaterials.CONTENT_KEY_ALGORITHM + "*"));
assertEquals(expectedSigAlg, kmsCtx.get("*amzn-ddb-sig-alg*"));
}
/**
* Wrap a key.
*
* @param key the key to be wrapped.
*
* @return the wrapped key.
*
* @exception IllegalBlockSizeException if this cipher is a block
* cipher, no padding has been requested, and the length of the
* encoding of the key to be wrapped is not a
* multiple of the block size.
*
* @exception InvalidKeyException if it is impossible or unsafe to
* wrap the key with this cipher (e.g., a hardware protected key is
* being passed to a software only cipher).
*/
protected final byte[] engineWrap(Key key)
throws IllegalBlockSizeException, InvalidKeyException
{
byte[] result = null;
try {
byte[] encodedKey = key.getEncoded();
if ((encodedKey == null) || (encodedKey.length == 0)) {
throw new InvalidKeyException("Cannot get an encoding of " +
"the key to be wrapped");
}
result = engineDoFinal(encodedKey, 0, encodedKey.length);
} catch (BadPaddingException e) {
// Should never happen
}
return result;
}
private void encodeKey(
Key key,
DataOutputStream dOut)
throws IOException
{
byte[] enc = key.getEncoded();
if (key instanceof PrivateKey)
{
dOut.write(KEY_PRIVATE);
}
else if (key instanceof PublicKey)
{
dOut.write(KEY_PUBLIC);
}
else
{
dOut.write(KEY_SECRET);
}
dOut.writeUTF(key.getFormat());
dOut.writeUTF(key.getAlgorithm());
dOut.writeInt(enc.length);
dOut.write(enc);
}
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);
}
}
/**
* Wrap a key.
*
* @param key the key to be wrapped.
*
* @return the wrapped key.
*
* @exception IllegalBlockSizeException if this cipher is a block
* cipher, no padding has been requested, and the length of the
* encoding of the key to be wrapped is not a
* multiple of the block size.
*
* @exception InvalidKeyException if it is impossible or unsafe to
* wrap the key with this cipher (e.g., a hardware protected key is
* being passed to a software only cipher).
*/
protected final byte[] engineWrap(Key key)
throws IllegalBlockSizeException, InvalidKeyException
{
byte[] result = null;
try {
byte[] encodedKey = key.getEncoded();
if ((encodedKey == null) || (encodedKey.length == 0)) {
throw new InvalidKeyException("Cannot get an encoding of " +
"the key to be wrapped");
}
result = engineDoFinal(encodedKey, 0, encodedKey.length);
} catch (BadPaddingException e) {
// Should never happen
}
return result;
}
/**
* Wrap a key.
*
* @param key the key to be wrapped.
*
* @return the wrapped key.
*
* @exception IllegalBlockSizeException if this cipher is a block
* cipher, no padding has been requested, and the length of the
* encoding of the key to be wrapped is not a
* multiple of the block size.
*
* @exception InvalidKeyException if it is impossible or unsafe to
* wrap the key with this cipher (e.g., a hardware protected key is
* being passed to a software only cipher).
*/
protected final byte[] engineWrap(Key key)
throws IllegalBlockSizeException, InvalidKeyException
{
byte[] result = null;
try {
byte[] encodedKey = key.getEncoded();
if ((encodedKey == null) || (encodedKey.length == 0)) {
throw new InvalidKeyException("Cannot get an encoding of " +
"the key to be wrapped");
}
result = engineDoFinal(encodedKey, 0, encodedKey.length);
} catch (BadPaddingException e) {
// Should never happen
}
return result;
}
public static void validateAesWrappingKey(Key managementKey, String joseAlg, int expectedKeyByteLength) throws InvalidKeyException
{
KeyValidationSupport.notNull(managementKey);
String alg = managementKey.getAlgorithm();
if (!AesKey.ALGORITHM.equals(alg))
{
throw new InvalidKeyException("Invalid key for JWE " + joseAlg + ", expected an "
+ AesKey.ALGORITHM+ " key but an " + alg + " key was provided.");
}
if (managementKey.getEncoded() != null)
{
int managementKeyByteLength = managementKey.getEncoded().length;
if (managementKeyByteLength != expectedKeyByteLength)
{
throw new InvalidKeyException("Invalid key for JWE " + joseAlg + ", expected a "
+ ByteUtil.bitLength(expectedKeyByteLength)+ " bit key but a "
+ ByteUtil.bitLength(managementKeyByteLength) + " bit key was provided.");
}
}
}
@Override
public void encodeJwe(JWE jwe) throws IOException, GeneralSecurityException {
byte[] contentBytes = jwe.getContent();
byte[] initializationVector = JWEUtils.generateSecret(16);
Key aesKey = jwe.getKeyStorage().getCEKKey(JWEKeyStorage.KeyUse.ENCRYPTION, false);
if (aesKey == null) {
throw new IllegalArgumentException("AES CEK key not present");
}
Key hmacShaKey = jwe.getKeyStorage().getCEKKey(JWEKeyStorage.KeyUse.SIGNATURE, false);
if (hmacShaKey == null) {
throw new IllegalArgumentException("HMAC CEK key not present");
}
int expectedAesKeyLength = getExpectedAesKeyLength();
if (expectedAesKeyLength != aesKey.getEncoded().length) {
throw new IllegalStateException("Length of aes key should be " + expectedAesKeyLength +", but was " + aesKey.getEncoded().length);
}
byte[] cipherBytes = encryptBytes(contentBytes, initializationVector, aesKey);
byte[] aad = jwe.getBase64Header().getBytes(StandardCharsets.UTF_8);
byte[] authenticationTag = computeAuthenticationTag(aad, initializationVector, cipherBytes, hmacShaKey);
jwe.setEncryptedContentInfo(initializationVector, cipherBytes, authenticationTag);
}
protected KeySpec engineGetKeySpec(Key key, Class keySpec)
throws InvalidKeySpecException
{
if (keySpec.isAssignableFrom(PKCS8EncodedKeySpec.class) && key.getFormat().equals("PKCS#8"))
{
return new PKCS8EncodedKeySpec(key.getEncoded());
}
else if (keySpec.isAssignableFrom(X509EncodedKeySpec.class) && key.getFormat().equals("X.509"))
{
return new X509EncodedKeySpec(key.getEncoded());
}
throw new InvalidKeySpecException("not implemented yet " + key + " " + keySpec);
}
public static byte[] genarateRandomKey() {
KeyGenerator keygen = null;
try {
keygen = KeyGenerator.getInstance(ConfigureEncryptAndDecrypt.AES_ALGORITHM);
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException(" genarateRandomKey fail!", e);
}
SecureRandom random = new SecureRandom();
keygen.init(random);
Key key = keygen.generateKey();
return key.getEncoded();
}
@Test
public void testKeyStoreKeyProviderWithPassword() throws Exception {
KeyProvider provider = new KeyStoreKeyProvider();
provider.init("jceks://" + storeFile.toURI().getPath() + "?password=" + PASSWORD);
Key key = provider.getKey(ALIAS);
assertNotNull(key);
byte[] keyBytes = key.getEncoded();
assertEquals(keyBytes.length, KEY.length);
for (int i = 0; i < KEY.length; i++) {
assertEquals(keyBytes[i], KEY[i]);
}
}
public EncryptRSA() throws Exception {
SecureRandom sr = new SecureRandom();
KeyPairGenerator kpg = KeyPairGenerator.getInstance(algorithm);
kpg.initialize(key_size, sr);
KeyPair kp = kpg.generateKeyPair();
Key keyPublic = kp.getPublic();
publicKey = keyPublic.getEncoded();
Key keyPrivate = kp.getPrivate();
privateKey = keyPrivate.getEncoded();
}
@Override
public void verifyAndDecodeJwe(JWE jwe) throws IOException, GeneralSecurityException {
Key aesKey = jwe.getKeyStorage().getCEKKey(JWEKeyStorage.KeyUse.ENCRYPTION, false);
if (aesKey == null) {
throw new IllegalArgumentException("AES CEK key not present");
}
Key hmacShaKey = jwe.getKeyStorage().getCEKKey(JWEKeyStorage.KeyUse.SIGNATURE, false);
if (hmacShaKey == null) {
throw new IllegalArgumentException("HMAC CEK key not present");
}
int expectedAesKeyLength = getExpectedAesKeyLength();
if (expectedAesKeyLength != aesKey.getEncoded().length) {
throw new IllegalStateException("Length of aes key should be " + expectedAesKeyLength +", but was " + aesKey.getEncoded().length);
}
byte[] aad = jwe.getBase64Header().getBytes(StandardCharsets.UTF_8);
byte[] authenticationTag = computeAuthenticationTag(aad, jwe.getInitializationVector(), jwe.getEncryptedContent(), hmacShaKey);
byte[] expectedAuthTag = jwe.getAuthenticationTag();
boolean digitsEqual = MessageDigest.isEqual(expectedAuthTag, authenticationTag);
if (!digitsEqual) {
throw new IllegalArgumentException("Signature validations failed");
}
byte[] contentBytes = decryptBytes(jwe.getEncryptedContent(), jwe.getInitializationVector(), aesKey);
jwe.content(contentBytes);
}
/**
* Protect a key by encrypting it with the secret key of the given subject.
* The configuration must be set up correctly for key alias resolution.
* @param conf configuration
* @param subject subject key alias
* @param key the key
* @return the encrypted key bytes
*/
public static byte[] wrapKey(Configuration conf, String subject, Key key)
throws IOException {
// Wrap the key with the configured encryption algorithm.
String algorithm =
conf.get(HConstants.CRYPTO_KEY_ALGORITHM_CONF_KEY, HConstants.CIPHER_AES);
Cipher cipher = Encryption.getCipher(conf, algorithm);
if (cipher == null) {
throw new RuntimeException("Cipher '" + algorithm + "' not available");
}
EncryptionProtos.WrappedKey.Builder builder = EncryptionProtos.WrappedKey.newBuilder();
builder.setAlgorithm(key.getAlgorithm());
byte[] iv = null;
if (cipher.getIvLength() > 0) {
iv = new byte[cipher.getIvLength()];
RNG.nextBytes(iv);
builder.setIv(UnsafeByteOperations.unsafeWrap(iv));
}
byte[] keyBytes = key.getEncoded();
builder.setLength(keyBytes.length);
builder.setHash(UnsafeByteOperations.unsafeWrap(Encryption.hash128(keyBytes)));
ByteArrayOutputStream out = new ByteArrayOutputStream();
Encryption.encryptWithSubjectKey(out, new ByteArrayInputStream(keyBytes), subject,
conf, cipher, iv);
builder.setData(UnsafeByteOperations.unsafeWrap(out.toByteArray()));
// Build and return the protobuf message
out.reset();
builder.build().writeDelimitedTo(out);
return out.toByteArray();
}
public PemFile(Key key, String desc) {
this.pemObject = new PemObject(desc, key.getEncoded());
}
protected int engineGetKeySize(
Key key)
{
return key.getEncoded().length;
}
public PemFile (Key key, String description) {
this.pemObject = new PemObject(description, key.getEncoded());
}
protected void engineInit(
int opmode,
Key key,
AlgorithmParameterSpec params,
SecureRandom random)
throws InvalidKeyException, InvalidAlgorithmParameterException
{
CipherParameters param;
if (key instanceof BCPBEKey)
{
BCPBEKey k = (BCPBEKey)key;
if (params instanceof PBEParameterSpec)
{
param = PBE.Util.makePBEParameters(k, params, wrapEngine.getAlgorithmName());
}
else if (k.getParam() != null)
{
param = k.getParam();
}
else
{
throw new InvalidAlgorithmParameterException("PBE requires PBE parameters to be set.");
}
}
else
{
param = new KeyParameter(key.getEncoded());
}
if (params instanceof IvParameterSpec)
{
IvParameterSpec iv = (IvParameterSpec) params;
param = new ParametersWithIV(param, iv.getIV());
}
if (param instanceof KeyParameter && ivSize != 0)
{
iv = new byte[ivSize];
random.nextBytes(iv);
param = new ParametersWithIV(param, iv);
}
if (random != null)
{
param = new ParametersWithRandom(param, random);
}
switch (opmode)
{
case Cipher.WRAP_MODE:
wrapEngine.init(true, param);
break;
case Cipher.UNWRAP_MODE:
wrapEngine.init(false, param);
break;
case Cipher.ENCRYPT_MODE:
case Cipher.DECRYPT_MODE:
throw new IllegalArgumentException("engine only valid for wrapping");
default:
System.out.println("eeek!");
}
}
/**
* 取得公钥
*
* @param keyMap
* 密钥Map
*
* @return byte[] 公钥
*
* @throws Exception
*/
public static byte[] getPublicKey(Map<String, Object> keyMap) {
Key key = (Key) keyMap.get(PUBLIC_KEY);
return key.getEncoded();
}
/**
* 取得公钥
* @param keyMap 密钥map
* @return byte[] 公钥
* */
public static byte[] getPublicKey(Map<String,Object> keyMap) throws Exception{
Key key=(Key) keyMap.get(PUBLIC_KEY);
return key.getEncoded();
}