/** * 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; }
public static java.security.Signature sigMeth2SigSignatureInstance(Signature sig, Key key) throws DigiDocException { java.security.Signature instance = null; String sigMeth = null, sigType = null; try { if (sig != null && sig.getSignedInfo() != null && sig.getSignedInfo().getSignatureMethod() != null) sigMeth = sig.getSignedInfo().getSignatureMethod(); sigType = ConfigManager.instance().sigMeth2SigType(sigMeth, true); // allways use cvc ciphers if (m_logger.isDebugEnabled()) m_logger.debug( "Key: " + ((key != null) ? "OK, algorithm: " + key.getAlgorithm() : "NULL") + " method: " + sigMeth + " type: " + sigType); if (sigType == null) throw new DigiDocException( DigiDocException.ERR_SIGNATURE_METHOD, "SignatureMethod not specified!", null); instance = java.security.Signature.getInstance(sigType, ConfigManager.addProvider()); } catch (Exception ex) { m_logger.error("Error constructing signature instance: " + ex); } return instance; }
private static byte[] func_75885_a(int p_75885_0_, Key p_75885_1_, byte p_75885_2_[]) { try { return func_75886_a(p_75885_0_, p_75885_1_.getAlgorithm(), p_75885_1_).doFinal(p_75885_2_); } catch (IllegalBlockSizeException illegalblocksizeexception) { illegalblocksizeexception.printStackTrace(); } catch (BadPaddingException badpaddingexception) { badpaddingexception.printStackTrace(); } System.err.println("Cipher data failed!"); return null; }
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()); }
/** * Translate an RSA key into a SunRsaSign RSA key. If conversion is not possible, throw an * InvalidKeyException. See also JCA doc. */ protected Key engineTranslateKey(Key key) throws InvalidKeyException { if (key == null) { throw new InvalidKeyException("Key must not be null"); } String keyAlg = key.getAlgorithm(); if (keyAlg.equals("RSA") == false) { throw new InvalidKeyException("Not an RSA key: " + keyAlg); } if (key instanceof PublicKey) { return translatePublicKey((PublicKey) key); } else if (key instanceof PrivateKey) { return translatePrivateKey((PrivateKey) key); } else { throw new InvalidKeyException("Neither a public nor a private key"); } }
public static byte[] encryptData(Key key, byte[] toEncrypt) { try { Cipher cipher = Cipher.getInstance(key.getAlgorithm()); cipher.init(Cipher.ENCRYPT_MODE, key); return cipher.doFinal(toEncrypt); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (NoSuchPaddingException e) { e.printStackTrace(); } catch (InvalidKeyException e) { e.printStackTrace(); } catch (BadPaddingException e) { e.printStackTrace(); } catch (IllegalBlockSizeException e) { e.printStackTrace(); } return new byte[0]; }
// see JCE spec protected byte[] engineWrap(Key key) throws InvalidKeyException, IllegalBlockSizeException { String keyAlg = key.getAlgorithm(); P11Key sKey = null; try { // The conversion may fail, e.g. trying to wrap an AES key on // a token that does not support AES, or when the key size is // not within the range supported by the token. sKey = P11SecretKeyFactory.convertKey(token, key, keyAlg); } catch (InvalidKeyException ike) { byte[] toBeWrappedKey = key.getEncoded(); if (toBeWrappedKey == null) { throw new InvalidKeyException("wrap() failed, no encoding available", ike); } // Directly encrypt the key encoding when key conversion failed implInit(Cipher.ENCRYPT_MODE, p11Key); implUpdate(toBeWrappedKey, 0, toBeWrappedKey.length); try { return doFinal(); } catch (BadPaddingException bpe) { // should not occur throw new InvalidKeyException("wrap() failed", bpe); } finally { // Restore original mode implInit(Cipher.WRAP_MODE, p11Key); } } Session s = null; try { s = token.getOpSession(); return token.p11.C_WrapKey(s.id(), new CK_MECHANISM(mechanism), p11Key.keyID, sKey.keyID); } catch (PKCS11Exception e) { throw new InvalidKeyException("wrap() failed", e); } finally { token.releaseSession(s); } }
void implInit( int opmode, Key key, AlgorithmParameterSpec params, SecureRandom random, CipherSpi cipherImpl) throws InvalidKeyException, InvalidAlgorithmParameterException { char[] passwdChars = null; salt = null; iCount = 0; if (key instanceof javax.crypto.interfaces.PBEKey) { javax.crypto.interfaces.PBEKey pbeKey = (javax.crypto.interfaces.PBEKey) key; passwdChars = pbeKey.getPassword(); salt = pbeKey.getSalt(); // maybe null if unspecified iCount = pbeKey.getIterationCount(); // maybe 0 if unspecified } else if (key instanceof SecretKey) { byte[] passwdBytes = key.getEncoded(); if ((passwdBytes == null) || !(key.getAlgorithm().regionMatches(true, 0, "PBE", 0, 3))) { throw new InvalidKeyException("Missing password"); } passwdChars = new char[passwdBytes.length]; for (int i = 0; i < passwdChars.length; i++) { passwdChars[i] = (char) (passwdBytes[i] & 0x7f); } } else { throw new InvalidKeyException("SecretKey of PBE type required"); } if (((opmode == Cipher.DECRYPT_MODE) || (opmode == Cipher.UNWRAP_MODE)) && ((params == null) && ((salt == null) || (iCount == 0)))) { throw new InvalidAlgorithmParameterException("Parameters missing"); } if (params == null) { // generate default for salt and iteration count if necessary if (salt == null) { salt = new byte[DEFAULT_SALT_LENGTH]; if (random != null) { random.nextBytes(salt); } else { SunJCE.getRandom().nextBytes(salt); } } if (iCount == 0) iCount = DEFAULT_COUNT; } else if (!(params instanceof PBEParameterSpec)) { throw new InvalidAlgorithmParameterException("PBEParameterSpec type required"); } else { PBEParameterSpec pbeParams = (PBEParameterSpec) params; // make sure the parameter values are consistent if (salt != null) { if (!Arrays.equals(salt, pbeParams.getSalt())) { throw new InvalidAlgorithmParameterException( "Inconsistent value of salt between key and params"); } } else { salt = pbeParams.getSalt(); } if (iCount != 0) { if (iCount != pbeParams.getIterationCount()) { throw new InvalidAlgorithmParameterException( "Different iteration count between key and params"); } } else { iCount = pbeParams.getIterationCount(); } } // salt is recommended to be ideally as long as the output // of the hash function. However, it may be too strict to // force this; so instead, we'll just require the minimum // salt length to be 8-byte which is what PKCS#5 recommends // and openssl does. if (salt.length < 8) { throw new InvalidAlgorithmParameterException("Salt must be at least 8 bytes long"); } if (iCount <= 0) { throw new InvalidAlgorithmParameterException("IterationCount must be a positive number"); } byte[] derivedKey = derive(passwdChars, salt, iCount, keySize, CIPHER_KEY); SecretKey cipherKey = new SecretKeySpec(derivedKey, algo); if (cipherImpl != null && cipherImpl instanceof ARCFOURCipher) { ((ARCFOURCipher) cipherImpl).engineInit(opmode, cipherKey, random); } else { byte[] derivedIv = derive(passwdChars, salt, iCount, 8, CIPHER_IV); IvParameterSpec ivSpec = new IvParameterSpec(derivedIv, 0, 8); // initialize the underlying cipher cipher.init(opmode, cipherKey, ivSpec, random); } }
protected int engineGetKeySize(Key key) throws InvalidKeyException { byte[] keyBytes = CipherCore.getKeyBytes(key); RC2Crypt.checkKey(key.getAlgorithm(), keyBytes.length); return keyBytes.length << 3; }
/** * Method returns a digital signature. It finds the RSA private key object from the active token * and then signs the given data with this key and RSA mechanism. * * @param digest digest of the data to be signed. * @param token token index * @param passwd users pin code or in case of pkcs12 file password * @param sig Signature object to provide info about desired signature method * @return an array of bytes containing digital signature. * @throws DigiDocException if signing the data fails. */ public byte[] sign(byte[] xml, int token, String passwd, Signature sig) 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: " + ((passwd != null) ? passwd.length() : 0)); Key key = m_keyStore.getKey(alias, passwd.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 nr: " + token, null); String sigMeth = null; if (sig != null && sig.getSignedInfo() != null && sig.getSignedInfo().getSignatureMethod() != null) sigMeth = sig.getSignedInfo().getSignatureMethod(); if (m_logger.isDebugEnabled()) m_logger.debug("Signing\n---\n" + new String(xml) + "\n---\n method: " + sigMeth); java.security.Signature instance = sigMeth2SigSignatureInstance(sig, key); if (m_logger.isDebugEnabled()) m_logger.debug("Signature instance: " + ((instance != null) ? "OK" : "NULL")); instance.initSign((PrivateKey) key); instance.update(xml); byte[] signature = instance.sign(); boolean bEcCvcKey = isCvcEcKey(sig); if (m_logger.isDebugEnabled()) m_logger.debug( "Signature algorithm: " + key.getAlgorithm() + " siglen: " + signature.length + " ec-key: " + bEcCvcKey); if (bEcCvcKey) { int nKeyLen = ((ECPrivateKey) key).getParams().getCurve().getField().getFieldSize(); int nReqLen = ((int) Math.ceil((double) nKeyLen / 8)) * 2; int nSigLen = signature.length; if (m_logger.isDebugEnabled()) m_logger.debug("EC Signature length: " + nSigLen + " required: " + nReqLen); if (nSigLen < nReqLen) { if (m_logger.isDebugEnabled()) m_logger.debug("Padding EC signature length: " + nSigLen + " to required: " + nReqLen); byte[] padsig = new byte[nReqLen]; System.arraycopy(signature, 0, padsig, (nReqLen - nSigLen) / 2, nSigLen / 2); System.arraycopy( signature, nSigLen / 2, padsig, (nReqLen / 2) + (nReqLen - nSigLen) / 2, nSigLen / 2); signature = padsig; } } if (m_logger.isDebugEnabled() && signature != null) m_logger.debug( "Signature len: " + signature.length + "\n---\n sig: " + ConvertUtils.bin2hex(signature)); return signature; } catch (DigiDocException ex) { m_logger.error("DigiDoc Error signing: " + ex); throw ex; } catch (Exception ex) { m_logger.error("Error signing: " + ex); } return null; }