public static BufferedBlockCipher getCipher(boolean forEncryption, Key shared) { BufferedBlockCipher cip = new BufferedBlockCipher(new CFBBlockCipher(new AESFastEngine(), 8)); cip.init( forEncryption, new ParametersWithIV(new KeyParameter(shared.getEncoded()), shared.getEncoded(), 0, 16)); return cip; }
/** * Method decrypts the data with the RSA private key corresponding to this certificate (which was * used to encrypt it). Decryption will be done with keystore * * @param data data to be decrypted. * @param token index of authentication token * @param pin PIN code * @return decrypted data. * @throws DigiDocException for all decryption errors */ public byte[] decrypt(byte[] data, int token, String pin) throws DigiDocException { try { if (m_keyStore == null) throw new DigiDocException( DigiDocException.ERR_NOT_INITED, "Keystore not initialized", null); String alias = getTokenName(token); if (alias == null) throw new DigiDocException( DigiDocException.ERR_TOKEN_LOGIN, "Invalid token nr: " + token, null); // get key if (m_logger.isDebugEnabled()) m_logger.debug( "loading key: " + alias + " passwd-len: " + ((pin != null) ? pin.length() : 0)); Key key = m_keyStore.getKey(alias, pin.toCharArray()); if (m_logger.isDebugEnabled()) m_logger.debug("Key: " + ((key != null) ? "OK, algorithm: " + key.getAlgorithm() : "NULL")); if (key == null) throw new DigiDocException( DigiDocException.ERR_TOKEN_LOGIN, "Invalid password for token: " + alias, null); Cipher cipher = Cipher.getInstance("RSA"); cipher.init(Cipher.DECRYPT_MODE, key); byte[] decdata = cipher.doFinal(data); if (m_logger.isDebugEnabled()) m_logger.debug("Decrypted len: " + ((decdata != null) ? decdata.length : 0)); return decdata; } catch (Exception ex) { m_logger.error("Error decrypting: " + ex); } return null; }
@Override public final IFuzzyValue<Boolean> execute( final IContext p_context, final boolean p_parallel, final List<ITerm> p_argument, final List<ITerm> p_return, final List<ITerm> p_annotation) { final Key l_key = p_argument.get(0).raw(); final EAlgorithm l_algorithm = EAlgorithm.from(l_key.getAlgorithm()); p_argument .subList(1, p_argument.size()) .stream() .map(i -> Base64.getDecoder().decode(i.<String>raw())) .map( i -> { try { return l_algorithm.getDecryptCipher(l_key).doFinal(i); } catch (final NoSuchPaddingException | NoSuchAlgorithmException | InvalidKeyException | BadPaddingException | IllegalBlockSizeException l_exception) { return null; } }) .filter(Objects::nonNull) .map(i -> CRawTerm.from(SerializationUtils.deserialize(i))) .forEach(p_return::add); return CFuzzyValue.from(true); }
protected void engineInit(Key key, AlgorithmParameterSpec params) throws InvalidKeyException, InvalidAlgorithmParameterException { CipherParameters param; if (key == null) { throw new InvalidKeyException("key is null"); } if (key instanceof JCEPBEKey) { JCEPBEKey k = (JCEPBEKey) key; if (k.getParam() != null) { param = k.getParam(); } else if (params instanceof PBEParameterSpec) { param = PBE.Util.makePBEMacParameters(k, params); } else { throw new InvalidAlgorithmParameterException("PBE requires PBE parameters to be set."); } } else if (params instanceof IvParameterSpec) { param = new ParametersWithIV( new KeyParameter(key.getEncoded()), ((IvParameterSpec) params).getIV()); } else if (params == null) { param = new KeyParameter(key.getEncoded()); } else { throw new InvalidAlgorithmParameterException("unknown parameter type."); } macEngine.init(param); }
/** * Decrypts an encrypted symmetric key using the provided encryption materials and returns it as a * SecretKey object. * * @deprecated no longer used and will be removed in the future */ @Deprecated private static SecretKey getDecryptedSymmetricKey( byte[] encryptedSymmetricKeyBytes, EncryptionMaterials materials, Provider cryptoProvider) { Key keyToDoDecryption; if (materials.getKeyPair() != null) { // Do envelope decryption with private key from key pair keyToDoDecryption = materials.getKeyPair().getPrivate(); } else { // Do envelope decryption with symmetric key keyToDoDecryption = materials.getSymmetricKey(); } try { Cipher cipher; if (cryptoProvider != null) { cipher = Cipher.getInstance(keyToDoDecryption.getAlgorithm(), cryptoProvider); } else { cipher = Cipher.getInstance(keyToDoDecryption.getAlgorithm()); } cipher.init(Cipher.DECRYPT_MODE, keyToDoDecryption); byte[] decryptedSymmetricKeyBytes = cipher.doFinal(encryptedSymmetricKeyBytes); return new SecretKeySpec( decryptedSymmetricKeyBytes, JceEncryptionConstants.SYMMETRIC_KEY_ALGORITHM); } catch (Exception e) { throw new AmazonClientException( "Unable to decrypt symmetric key from object metadata : " + e.getMessage(), e); } }
/** * Encrypts a symmetric key using the provided encryption materials and returns it in raw byte * array form. * * @deprecated no longer used and will be removed in the future */ @Deprecated public static byte[] getEncryptedSymmetricKey( SecretKey toBeEncrypted, EncryptionMaterials materials, Provider cryptoProvider) { Key keyToDoEncryption; if (materials.getKeyPair() != null) { // Do envelope encryption with public key from key pair keyToDoEncryption = materials.getKeyPair().getPublic(); } else { // Do envelope encryption with symmetric key keyToDoEncryption = materials.getSymmetricKey(); } try { Cipher cipher; byte[] toBeEncryptedBytes = toBeEncrypted.getEncoded(); if (cryptoProvider != null) { cipher = Cipher.getInstance(keyToDoEncryption.getAlgorithm(), cryptoProvider); } else { cipher = Cipher.getInstance(keyToDoEncryption.getAlgorithm()); // Use default JCE Provider } cipher.init(Cipher.ENCRYPT_MODE, keyToDoEncryption); return cipher.doFinal(toBeEncryptedBytes); } catch (Exception e) { throw new AmazonClientException("Unable to encrypt symmetric key: " + e.getMessage(), e); } }
/** 生成密钥对 */ public static Map<String, String> generateKeyPair() throws Exception { /** RSA算法要求有一个可信任的随机数源 */ SecureRandom sr = new SecureRandom(); /** 为RSA算法创建一个KeyPairGenerator对象 */ KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA"); /** 利用上面的随机数据源初始化这个KeyPairGenerator对象 */ kpg.initialize(KEYSIZE, sr); /** 生成密匙对 */ KeyPair kp = kpg.generateKeyPair(); /** 得到公钥 */ Key publicKey = kp.getPublic(); byte[] publicKeyBytes = publicKey.getEncoded(); String pub = new String(Base64.encodeBase64(publicKeyBytes), ConfigureEncryptAndDecrypt.CHAR_ENCODING); /** 得到私钥 */ Key privateKey = kp.getPrivate(); byte[] privateKeyBytes = privateKey.getEncoded(); String pri = new String(Base64.encodeBase64(privateKeyBytes), ConfigureEncryptAndDecrypt.CHAR_ENCODING); Map<String, String> map = new HashMap<String, String>(); map.put("publicKey", pub); map.put("privateKey", pri); RSAPublicKey rsp = (RSAPublicKey) kp.getPublic(); BigInteger bint = rsp.getModulus(); byte[] b = bint.toByteArray(); byte[] deBase64Value = Base64.encodeBase64(b); String retValue = new String(deBase64Value); map.put("modulus", retValue); return map; }
private static BufferedBlockCipher func_75892_a(boolean par0, Key par1Key) { BufferedBlockCipher var2 = new BufferedBlockCipher(new CFBBlockCipher(new AESFastEngine(), 8)); var2.init( par0, new ParametersWithIV(new KeyParameter(par1Key.getEncoded()), par1Key.getEncoded(), 0, 16)); return var2; }
/** * Converts, if possible, a given key into a key specification. Currently, the following key * specifications are supported: * * <ul> * <li>for McElieceCCA2PublicKey: {@link X509EncodedKeySpec}, {@link McElieceCCA2PublicKeySpec} * <li>for McElieceCCA2PrivateKey: {@link PKCS8EncodedKeySpec}, {@link * McElieceCCA2PrivateKeySpec}. * </ul> * * @param key the key * @param keySpec the key specification * @return the specification of the McEliece CCA2 key * @throws InvalidKeySpecException if the key type or the key specification is not supported. * @see BCMcElieceCCA2PrivateKey * @see McElieceCCA2PrivateKeySpec * @see BCMcElieceCCA2PublicKey * @see McElieceCCA2PublicKeySpec */ public KeySpec getKeySpec(Key key, Class keySpec) throws InvalidKeySpecException { if (key instanceof BCMcElieceCCA2PrivateKey) { if (PKCS8EncodedKeySpec.class.isAssignableFrom(keySpec)) { return new PKCS8EncodedKeySpec(key.getEncoded()); } else if (McElieceCCA2PrivateKeySpec.class.isAssignableFrom(keySpec)) { BCMcElieceCCA2PrivateKey privKey = (BCMcElieceCCA2PrivateKey) key; return new McElieceCCA2PrivateKeySpec( OID, privKey.getN(), privKey.getK(), privKey.getField(), privKey.getGoppaPoly(), privKey.getP(), privKey.getH(), privKey.getQInv()); } } else if (key instanceof BCMcElieceCCA2PublicKey) { if (X509EncodedKeySpec.class.isAssignableFrom(keySpec)) { return new X509EncodedKeySpec(key.getEncoded()); } else if (McElieceCCA2PublicKeySpec.class.isAssignableFrom(keySpec)) { BCMcElieceCCA2PublicKey pubKey = (BCMcElieceCCA2PublicKey) key; return new McElieceCCA2PublicKeySpec(OID, pubKey.getN(), pubKey.getT(), pubKey.getG()); } } else { throw new InvalidKeySpecException("Unsupported key type: " + key.getClass() + "."); } throw new InvalidKeySpecException("Unknown key specification: " + keySpec + "."); }
/** * This method returns a specification for the supplied key. * * <p>The specification will be returned in the form of an object of the type specified by * keySpec. * * @param key - either DSAPrivateKey or DSAPublicKey * @param keySpec - either DSAPrivateKeySpec.class or DSAPublicKeySpec.class * @return either a DSAPrivateKeySpec or a DSAPublicKeySpec * @throws InvalidKeySpecException if "keySpec" is not a specification for DSAPublicKey or * DSAPrivateKey */ protected <T extends KeySpec> T engineGetKeySpec(Key key, Class<T> keySpec) throws InvalidKeySpecException { BigInteger p, q, g, x, y; if (key != null) { if (keySpec == null) { throw new NullPointerException("keySpec == null"); } if (key instanceof DSAPrivateKey) { DSAPrivateKey privateKey = (DSAPrivateKey) key; if (keySpec.equals(DSAPrivateKeySpec.class)) { x = privateKey.getX(); DSAParams params = privateKey.getParams(); p = params.getP(); q = params.getQ(); g = params.getG(); return (T) (new DSAPrivateKeySpec(x, p, q, g)); } if (keySpec.equals(PKCS8EncodedKeySpec.class)) { return (T) (new PKCS8EncodedKeySpec(key.getEncoded())); } throw new InvalidKeySpecException( "'keySpec' is neither DSAPrivateKeySpec nor PKCS8EncodedKeySpec"); } if (key instanceof DSAPublicKey) { DSAPublicKey publicKey = (DSAPublicKey) key; if (keySpec.equals(DSAPublicKeySpec.class)) { y = publicKey.getY(); DSAParams params = publicKey.getParams(); p = params.getP(); q = params.getQ(); g = params.getG(); return (T) (new DSAPublicKeySpec(y, p, q, g)); } if (keySpec.equals(X509EncodedKeySpec.class)) { return (T) (new X509EncodedKeySpec(key.getEncoded())); } throw new InvalidKeySpecException( "'keySpec' is neither DSAPublicKeySpec nor X509EncodedKeySpec"); } } throw new InvalidKeySpecException("'key' is neither DSAPublicKey nor DSAPrivateKey"); }
public static String getPrivateKey(Map<String, Object> keyMap) throws Exception { Key key = (Key) keyMap.get(PRIVATE_KEY); byte[] privateKey = key.getEncoded(); return encryptBASE64(key.getEncoded()); }
public String createKey() throws NoSuchAlgorithmException, NoSuchProviderException { KeyGenerator keygen = KeyGenerator.getInstance("AES", "BC"); keygen.init(256); Key key = keygen.generateKey(); return Base64.encodeBase64String(key.getEncoded()); }
private static BufferedBlockCipher func_75892_a(boolean p_75892_0_, Key p_75892_1_) { BufferedBlockCipher bufferedblockcipher = new BufferedBlockCipher(new CFBBlockCipher(new AESFastEngine(), 8)); bufferedblockcipher.init( p_75892_0_, new ParametersWithIV( new KeyParameter(p_75892_1_.getEncoded()), p_75892_1_.getEncoded(), 0, 16)); return bufferedblockcipher; }
/** * This method returns a specification for the supplied key. * * <p>The specification will be returned in the form of an object of the type specified by * keySpec. * * @param key - either DSAPrivateKey or DSAPublicKey * @param keySpec - either DSAPrivateKeySpec.class or DSAPublicKeySpec.class * @return either a DSAPrivateKeySpec or a DSAPublicKeySpec * @throws InvalidKeySpecException if "keySpec" is not a specification for DSAPublicKey or * DSAPrivateKey */ protected <T extends KeySpec> T engineGetKeySpec(Key key, Class<T> keySpec) throws InvalidKeySpecException { BigInteger p, q, g, x, y; if (key != null) { if (keySpec == null) { throw new NullPointerException(Messages.getString("security.19E")); // $NON-NLS-1$ } if (key instanceof DSAPrivateKey) { DSAPrivateKey privateKey = (DSAPrivateKey) key; if (keySpec.equals(DSAPrivateKeySpec.class)) { x = privateKey.getX(); DSAParams params = privateKey.getParams(); p = params.getP(); q = params.getQ(); g = params.getG(); return (T) (new DSAPrivateKeySpec(x, p, q, g)); } if (keySpec.equals(PKCS8EncodedKeySpec.class)) { return (T) (new PKCS8EncodedKeySpec(key.getEncoded())); } throw new InvalidKeySpecException(Messages.getString("security.19C")); // $NON-NLS-1$ } if (key instanceof DSAPublicKey) { DSAPublicKey publicKey = (DSAPublicKey) key; if (keySpec.equals(DSAPublicKeySpec.class)) { y = publicKey.getY(); DSAParams params = publicKey.getParams(); p = params.getP(); q = params.getQ(); g = params.getG(); return (T) (new DSAPublicKeySpec(y, p, q, g)); } if (keySpec.equals(X509EncodedKeySpec.class)) { return (T) (new X509EncodedKeySpec(key.getEncoded())); } throw new InvalidKeySpecException(Messages.getString("security.19D")); // $NON-NLS-1$ } } throw new InvalidKeySpecException(Messages.getString("security.19F")); // $NON-NLS-1$ }
public static String generateKey(int len) { try { KeyGenerator keyGen = KeyGenerator.getInstance("AES"); keyGen.init(len); Key key = keyGen.generateKey(); // System.out.println(key.getEncoded()); return Strings.toHexString(key.getEncoded()); } catch (Exception e) { return null; } }
/** * 张纪豪添加 * * @param len * @param password * @return */ public static String generateKey(int len, String password) { try { KeyGenerator keyGen = KeyGenerator.getInstance("AES"); keyGen.init(len); keyGen.init(128, new SecureRandom(password.getBytes())); Key key = keyGen.generateKey(); return Strings.toHexString(key.getEncoded()); } catch (Exception e) { return null; } }
public boolean shareAESkey() { try { Envelope message = null, e = null; // Generate AES key KeyGenerator keyGen = KeyGenerator.getInstance("AES"); AESkey = keyGen.generateKey(); keyGen = KeyGenerator.getInstance("HmacSHA1"); HMACkey = keyGen.generateKey(); byte[] keyBytes = AESkey.getEncoded(); byte[] hashBytes = HMACkey.getEncoded(); System.out.println("AES key generated"); System.out.println("HMAC key generated"); System.out.println("Begin Encryption..."); // Encrypt message w/ provided public key Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding"); cipher.init(Cipher.ENCRYPT_MODE, pubKey); byte[] cipherBytes = cipher.doFinal(keyBytes); byte[] cipherBytes1 = cipher.doFinal(hashBytes); System.out.println("Encryption Complete"); message = new Envelope("SKEY"); message.addObject(cipherBytes); // Add AESkey to message message.addObject(cipherBytes1); message.addObject(nonce); nonce++; byte[] messageBytes = Envelope.toByteArray(message); output.writeObject(messageBytes); byte[] inCipherBytes = (byte[]) input.readObject(); // Decrypt response cipher = Cipher.getInstance("AES"); cipher.init(Cipher.DECRYPT_MODE, AESkey); byte[] responseBytes = cipher.doFinal(inCipherBytes); Envelope response = Envelope.getEnvelopefromBytes(responseBytes); // If server indicates success, return the member list if (response.getMessage().equals("OK") && (Integer) response.getObjContents().get(0) == nonce) { return true; } else { return false; } } catch (Exception e) { System.err.println("Error: " + e.getMessage()); e.printStackTrace(System.err); return false; } }
protected <T extends KeySpec> T engineGetKeySpec(Key key, Class<T> keySpec) throws InvalidKeySpecException { try { // convert key to one of our keys // this also verifies that the key is a valid RSA key and ensures // that the encoding is X.509/PKCS#8 for public/private keys key = engineTranslateKey(key); } catch (InvalidKeyException e) { throw new InvalidKeySpecException(e); } if (key instanceof RSAPublicKey) { RSAPublicKey rsaKey = (RSAPublicKey) key; if (rsaPublicKeySpecClass.isAssignableFrom(keySpec)) { return keySpec.cast(new RSAPublicKeySpec(rsaKey.getModulus(), rsaKey.getPublicExponent())); } else if (x509KeySpecClass.isAssignableFrom(keySpec)) { return keySpec.cast(new X509EncodedKeySpec(key.getEncoded())); } else { throw new InvalidKeySpecException( "KeySpec must be RSAPublicKeySpec or " + "X509EncodedKeySpec for RSA public keys"); } } else if (key instanceof RSAPrivateKey) { if (pkcs8KeySpecClass.isAssignableFrom(keySpec)) { return keySpec.cast(new PKCS8EncodedKeySpec(key.getEncoded())); } else if (rsaPrivateCrtKeySpecClass.isAssignableFrom(keySpec)) { if (key instanceof RSAPrivateCrtKey) { RSAPrivateCrtKey crtKey = (RSAPrivateCrtKey) key; return keySpec.cast( new RSAPrivateCrtKeySpec( crtKey.getModulus(), crtKey.getPublicExponent(), crtKey.getPrivateExponent(), crtKey.getPrimeP(), crtKey.getPrimeQ(), crtKey.getPrimeExponentP(), crtKey.getPrimeExponentQ(), crtKey.getCrtCoefficient())); } else { throw new InvalidKeySpecException("RSAPrivateCrtKeySpec can only be used with CRT keys"); } } else if (rsaPrivateKeySpecClass.isAssignableFrom(keySpec)) { RSAPrivateKey rsaKey = (RSAPrivateKey) key; return keySpec.cast( new RSAPrivateKeySpec(rsaKey.getModulus(), rsaKey.getPrivateExponent())); } else { throw new InvalidKeySpecException( "KeySpec must be RSAPrivate(Crt)KeySpec or " + "PKCS8EncodedKeySpec for RSA private keys"); } } else { // should not occur, caught in engineTranslateKey() throw new InvalidKeySpecException("Neither public nor private key"); } }
@Test(timeout = 30000) 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 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(); }
protected void engineInit( int paramInt, Key paramKey, AlgorithmParameterSpec paramAlgorithmParameterSpec, SecureRandom paramSecureRandom) { Object localObject; if ((paramKey instanceof BCPBEKey)) { paramKey = (BCPBEKey) paramKey; if ((paramAlgorithmParameterSpec instanceof PBEParameterSpec)) { localObject = PBE.Util.ˊ(paramKey, paramAlgorithmParameterSpec, this.aXL.iG()); } else if (paramKey.nU() != null) { localObject = paramKey.nU(); } else { throw new InvalidAlgorithmParameterException("PBE requires PBE parameters to be set."); } } else { localObject = new KeyParameter(paramKey.getEncoded()); } paramKey = (Key) localObject; if ((paramAlgorithmParameterSpec instanceof IvParameterSpec)) { paramKey = new ParametersWithIV( (CipherParameters) localObject, ((IvParameterSpec) paramAlgorithmParameterSpec).getIV()); } paramAlgorithmParameterSpec = paramKey; if ((paramKey instanceof KeyParameter)) { paramAlgorithmParameterSpec = paramKey; if (this.aYU != 0) { this.iv = new byte[this.aYU]; paramSecureRandom.nextBytes(this.iv); paramAlgorithmParameterSpec = new ParametersWithIV(paramKey, this.iv); } } paramKey = paramAlgorithmParameterSpec; if (paramSecureRandom != null) { paramKey = new ParametersWithRandom(paramAlgorithmParameterSpec, paramSecureRandom); } switch (paramInt) { default: break; case 3: this.aXL.ˊ(true, paramKey); return; case 4: this.aXL.ˊ(false, paramKey); return; case 1: case 2: throw new IllegalArgumentException("engine only valid for wrapping"); } System.out.println("eeek!"); }
public void load() { try { KeyStore keyStore = KeyStore.getInstance("JCEKS"); keyStore.load(new FileInputStream("output.jceks"), "password".toCharArray()); Key key = keyStore.getKey("secret", "password".toCharArray()); System.out.println(key.toString()); } catch (Exception ex) { ex.printStackTrace(); } }
void assertPrivateKs(File file, String pass, String alias) throws Exception { KeyStore ks = loadKeyStore("jceks", file, alias); List aliases = ListUtil.fromIterator(new EnumerationIterator(ks.aliases())); assertEquals(2, aliases.size()); Certificate cert = ks.getCertificate(alias + ".crt"); assertNotNull(cert); assertEquals("X.509", cert.getType()); assertTrue(ks.isKeyEntry(alias + ".key")); assertTrue(ks.isCertificateEntry(alias + ".crt")); Key key = ks.getKey(alias + ".key", pass.toCharArray()); assertNotNull(key); assertEquals("RSA", key.getAlgorithm()); }
/** * Encrypt the MAC key using the provided shared secret. * * @param macKey MAC key to encrypt * @param sharedSecret shared secret used to encrypt MAC key * @return encrypted MAC Key */ private static SecretKey macKeyEncryption(Key macKey, SecretKey sharedSecret) { try { MessageDigest messageDigest = MessageDigest.getInstance(sharedSecret.getAlgorithm()); byte[] digestedSecret = messageDigest.digest(sharedSecret.getEncoded()); byte[] encrypted = xor(macKey.getEncoded(), digestedSecret); return new SecretKeySpec(encrypted, macKey.getAlgorithm()); } catch (NoSuchAlgorithmException e) { log.error("unable to encrypt MAC key: {}", e.getMessage()); } return null; }
byte[] getPublicKeyEncoded() { try { // generate a key pair SecureRandom random = new SecureRandom(); KeyPairGenerator generator = KeyPairGenerator.getInstance(ASYM_KEY_TYPE); generator.initialize(ASYM_KEY_SIZE, random); _serverKeyPair = generator.generateKeyPair(); Key pubKey = _serverKeyPair.getPublic(); return pubKey.getEncoded(); } catch (Exception e) { e.printStackTrace(); } return null; }
/** * Convert a Key to string encoded as BASE64 * * @param key The key (private or public) * @return A string representation of the key */ public static String getKeyAsString(Key key) { // Get the bytes of the key byte[] keyBytes = key.getEncoded(); // Convert key to BASE64 encoded string BASE64Encoder b64 = new BASE64Encoder(); return b64.encode(keyBytes); }
/** @inheritDoc */ protected void engineInitVerify(Key publicKey) throws XMLSignatureException { if (!(publicKey instanceof PublicKey)) { String supplied = publicKey.getClass().getName(); String needed = PublicKey.class.getName(); Object exArgs[] = {supplied, needed}; throw new XMLSignatureException("algorithms.WrongKeyForThisOperation", exArgs); } try { this.signatureAlgorithm.initVerify((PublicKey) publicKey); } catch (InvalidKeyException ex) { // reinstantiate Signature object to work around bug in JDK // see: http://bugs.sun.com/view_bug.do?bug_id=4953555 Signature sig = this.signatureAlgorithm; try { this.signatureAlgorithm = Signature.getInstance(signatureAlgorithm.getAlgorithm()); } catch (Exception e) { // this shouldn't occur, but if it does, restore previous // Signature if (log.isLoggable(java.util.logging.Level.FINE)) { log.log(java.util.logging.Level.FINE, "Exception when reinstantiating Signature:" + e); } this.signatureAlgorithm = sig; } throw new XMLSignatureException("empty", ex); } }
@Override public String toString() { if (null == _nodeKey) { return "NodeKey for node: " + _nodeName + " Stored at: " + _storedNodeKeyName + " Stored ID: " + DataUtils.printHexBytes(_storedNodeKeyID) + " Key: null" + " Key id: null"; } // not great to print out keys, but nec for debugging return "NodeKey for node: " + _nodeName + " Stored at: " + _storedNodeKeyName + " Stored ID: " + DataUtils.printHexBytes(_storedNodeKeyID) + " Key: " + DataUtils.printHexBytes(_nodeKey.getEncoded()) + " Key id: " + DataUtils.printHexBytes(WrappedKey.wrappingKeyIdentifier(_nodeKey)); }
protected byte[] engineWrap(Key paramKey) { paramKey = paramKey.getEncoded(); if (paramKey == null) { throw new InvalidKeyException("Cannot wrap key, null encoding."); } try { if (this.aXL == null) { paramKey = engineDoFinal(paramKey, 0, paramKey.length); return paramKey; } paramKey = this.aXL.ᐨ(paramKey, 0, paramKey.length); return paramKey; } catch (BadPaddingException paramKey) { throw new IllegalBlockSizeException(paramKey.getMessage()); } }
/** * Returns the key size of the given key object. * * @param key the key object. * @return the key size of the given key object. * @exception InvalidKeyException if <code>key</code> is invalid. */ protected int engineGetKeySize(Key key) throws InvalidKeyException { byte[] encoded = key.getEncoded(); if (encoded.length != 8) { throw new InvalidKeyException("Invalid key length: " + encoded.length + " bytes"); } return 56; }