List of usage examples for org.bouncycastle.util.encoders Base64 encode
public static byte[] encode(byte[] data)
From source file:com.eucalyptus.auth.euare.persist.DatabaseAccountProxy.java
License:Open Source License
@Override public ServerCertificate addServerCertificate(String certName, String certBody, String certChain, String certPath, String pk) throws AuthException { synchronized (getLock()) { if (!ServerCertificateEntity.isCertificateNameValid(certName)) throw new AuthException(AuthException.INVALID_SERVER_CERT_NAME); if (!ServerCertificateEntity.isCertificatePathValid(certPath)) throw new AuthException(AuthException.INVALID_SERVER_CERT_PATH); try {/*from ww w . ja va 2 s . com*/ ServerCertificates.verifyCertificate(certBody, pk, certChain); } catch (final AuthException ex) { throw ex; } catch (final Exception ex) { throw new AuthException(AuthException.SERVER_CERT_INVALID_FORMAT); } String encPk = null; String sessionKey = null; try { // generate symmetric key final MessageDigest digest = Digest.SHA256.get(); final byte[] salt = new byte[32]; Crypto.getSecureRandomSupplier().get().nextBytes(salt); //digest.update( this.lookupAdmin().getPassword().getBytes( Charsets.UTF_8 ) ); digest.update(salt); final SecretKey symmKey = new SecretKeySpec(digest.digest(), "AES"); // encrypt the server pk Cipher cipher = Ciphers.AES_GCM.get(); final byte[] iv = new byte[32]; Crypto.getSecureRandomSupplier().get().nextBytes(iv); cipher.init(Cipher.ENCRYPT_MODE, symmKey, new IvParameterSpec(iv), Crypto.getSecureRandomSupplier().get()); final byte[] cipherText = cipher.doFinal(pk.getBytes()); encPk = new String(Base64.encode(Arrays.concatenate(iv, cipherText))); final PublicKey euarePublicKey = SystemCredentials.lookup(Euare.class).getCertificate() .getPublicKey(); cipher = Ciphers.RSA_PKCS1.get(); cipher.init(Cipher.WRAP_MODE, euarePublicKey, Crypto.getSecureRandomSupplier().get()); byte[] wrappedKeyBytes = cipher.wrap(symmKey); sessionKey = new String(Base64.encode(wrappedKeyBytes)); } catch (final Exception e) { LOG.error("Failed to encrypt key", e); throw Exceptions.toUndeclared(e); } try { final ServerCertificate found = lookupServerCertificate(certName); if (found != null) throw new AuthException(AuthException.SERVER_CERT_ALREADY_EXISTS); } catch (final NoSuchElementException ex) { ; } catch (final AuthException ex) { if (!AuthException.SERVER_CERT_NO_SUCH_ENTITY.equals(ex.getMessage())) throw ex; } catch (final Exception ex) { throw ex; } final String certId = Identifiers.generateIdentifier("ASC"); ServerCertificateEntity entity = null; try (final TransactionResource db = Entities.transactionFor(ServerCertificateEntity.class)) { final UserFullName accountAdmin = UserFullName.getInstance(this.lookupAdmin()); entity = new ServerCertificateEntity(accountAdmin, certName); entity.setCertBody(certBody); entity.setCertChain(certChain); entity.setCertPath(certPath); entity.setPrivateKey(encPk); entity.setSessionKey(sessionKey); entity.setCertId(certId); Entities.persist(entity); db.commit(); } catch (final Exception ex) { LOG.error("Failed to persist server certificate entity", ex); throw Exceptions.toUndeclared(ex); } return ServerCertificates.ToServerCertificate.INSTANCE.apply(entity); } }
From source file:com.eucalyptus.blockstorage.HttpTransfer.java
License:Open Source License
/** * Calculates and sets the Authorization header value for the request using the EucaRSA-V2 signing algorithm * Algorithm Overview:// w ww .j av a2 s . co m * * 1. Generate the canonical Request * a.) CanonicalRequest = * HTTPRequestMethod + '\n' + * CanonicalURI + '\n' + * CanonicalQueryString + '\n' + * CanonicalHeaders + '\n' + * SignedHeaders * b.) Where CanonicalURI = * c.) Where CanonicalQueryString = * d.) Where CanonicalHeaders = sorted (by lowercased header name) ';' delimited list of <lowercase(headername)>:<value> items * e.) Where SignedHeaders = sorted, ';' delimited list of headers in CanonicalHeaders * * 2. Signature = RSA(privkey, SHA256(CanonicalRequest)) * * 3. Add an Authorization HTTP header to the request that contains the following strings, separated by spaces: * EUCA2-RSA-SHA256 * The lower-case hexadecimal encoding of the component's X.509 certificate's md5 fingerprint * The SignedHeaders list calculated in Task 1 * The Base64 encoding of the Signature calculated in Task 2 * * @param httpBaseRequest -- the request, the 'Authorization' header will be added to the request */ public static void signEucaInternal(HttpMethodBase httpBaseRequest) { StringBuilder canonicalRequest = new StringBuilder(); String canonicalURI = null; String verb = httpBaseRequest.getName(); canonicalURI = httpBaseRequest.getPath(); String canonicalQuery = calcCanonicalQuery(httpBaseRequest); String[] processedHeaders = getCanonicalAndSignedHeaders(httpBaseRequest); String canonicalHeaders = processedHeaders[0]; String signedHeaders = processedHeaders[1]; canonicalRequest.append(verb).append('\n'); canonicalRequest.append(canonicalURI).append('\n'); canonicalRequest.append(canonicalQuery).append('\n'); canonicalRequest.append(canonicalHeaders).append('\n'); canonicalRequest.append(signedHeaders); StringBuilder authHeader = new StringBuilder(EUCA2_AUTH_ID); String signature = null; String fingerprint = null; try { Credentials ccCreds = SystemCredentials.lookup(Storage.class); PrivateKey ccPrivateKey = ccCreds.getPrivateKey(); fingerprint = ccCreds.getCertFingerprint(); Signature sign = Signature.getInstance("SHA256withRSA"); sign.initSign(ccPrivateKey); LOG.debug("Signing canonical request: " + canonicalRequest.toString()); sign.update(canonicalRequest.toString().getBytes()); byte[] sig = sign.sign(); signature = new String(Base64.encode(sig)); } catch (Exception ex) { LOG.error("Signing error while signing request", ex); } authHeader.append(" ").append(fingerprint.toLowerCase()).append(" ").append(signedHeaders.toString()) .append(" ").append(signature); httpBaseRequest.addRequestHeader(EUCA2_AUTH_HEADER_NAME, authHeader.toString()); }
From source file:com.eucalyptus.blockstorage.util.BlockStorageUtil.java
License:Open Source License
public static String encryptNodeTargetPassword(String password, Partition partition) throws EucalyptusCloudException { try {//from w w w . j av a 2s .c om if (partition == null) { throw new EucalyptusCloudException("Invalid partition specified. Got null"); } else { PublicKey ncPublicKey = partition.getNodeCertificate().getPublicKey(); Cipher cipher = Ciphers.RSA_PKCS1.get(); cipher.init(Cipher.ENCRYPT_MODE, ncPublicKey); return new String(Base64.encode(cipher.doFinal(password.getBytes()))); } } catch (Exception e) { LOG.error("Unable to encrypt storage target password: " + e.getMessage(), e); throw new EucalyptusCloudException("Unable to encrypt storage target password: " + e.getMessage(), e); } }
From source file:com.eucalyptus.blockstorage.util.BlockStorageUtil.java
License:Open Source License
public static String encryptSCTargetPassword(String password) throws EucalyptusCloudException { PublicKey scPublicKey = SystemCredentials.lookup(Storage.class).getKeyPair().getPublic(); Cipher cipher;//from w w w.ja v a2 s . co m try { cipher = Ciphers.RSA_PKCS1.get(); cipher.init(Cipher.ENCRYPT_MODE, scPublicKey); return new String(Base64.encode(cipher.doFinal(password.getBytes()))); } catch (Exception e) { LOG.error("Unable to encrypted storage target password"); throw new EucalyptusCloudException(e.getMessage(), e); } }
From source file:com.eucalyptus.blockstorage.util.BlockStorageUtil.java
License:Open Source License
public static String encryptForNode(String data, Partition partition) throws EucalyptusCloudException { try {/* w w w. jav a 2 s . co m*/ if (partition == null) { throw new EucalyptusCloudException("Invalid partition specified. Got null"); } else { PublicKey ncPublicKey = partition.getNodeCertificate().getPublicKey(); Cipher cipher = Ciphers.RSA_PKCS1.get(); cipher.init(Cipher.ENCRYPT_MODE, ncPublicKey); return new String(Base64.encode(cipher.doFinal(data.getBytes()))); } } catch (Exception e) { LOG.error("Unable to encrypt data: " + e.getMessage(), e); throw new EucalyptusCloudException("Unable to encrypt data: " + e.getMessage(), e); } }
From source file:com.eucalyptus.blockstorage.util.BlockStorageUtil.java
License:Open Source License
public static String encryptForCloud(String data) throws EucalyptusCloudException { try {/* w w w.j a va 2 s.c o m*/ PublicKey clcPublicKey = SystemCredentials.lookup(Eucalyptus.class).getCertificate().getPublicKey(); Cipher cipher = Ciphers.RSA_PKCS1.get(); cipher.init(Cipher.ENCRYPT_MODE, clcPublicKey); return new String(Base64.encode(cipher.doFinal(data.getBytes()))); } catch (Exception e) { LOG.error("Unable to encrypt data: " + e.getMessage(), e); throw new EucalyptusCloudException("Unable to encrypt data: " + e.getMessage(), e); } }
From source file:com.eucalyptus.bootstrap.DatabaseInfo.java
License:Open Source License
public void setAppendOnlyPassword(final String password) { try {/*from w w w .j av a 2 s .c om*/ final X509Certificate cloudCert = SystemCredentials.lookup(Eucalyptus.class).getCertificate(); final Cipher cipher = Ciphers.RSA_PKCS1.get(); cipher.init(Cipher.ENCRYPT_MODE, cloudCert.getPublicKey(), Crypto.getSecureRandomSupplier().get()); byte[] bencPassword = cipher.doFinal(password.getBytes()); final String encryptedPassword = new String(Base64.encode(bencPassword)); this.appendOnlyPassword = encryptedPassword; } catch (final Exception ex) { LOG.error("Failed to encrypt the database password"); } }
From source file:com.eucalyptus.cloud.run.ClusterAllocator.java
License:Open Source License
private void setupCredentialMessages() { try {/*from w w w .ja v a 2 s . co m*/ final User owner = Accounts.lookupUserById(this.allocInfo.getOwnerFullName().getUserId()); if (!owner.isSystemAdmin()) return; } catch (final AuthException ex) { return; } // determine if credential setup is requested if (allocInfo.getUserData() == null || allocInfo.getUserData().length < VmInstances.VmSpecialUserData.EUCAKEY_CRED_SETUP.toString() .length()) return; String userData = new String(allocInfo.getUserData(), 0, VmInstances.VmSpecialUserData.EUCAKEY_CRED_SETUP.toString().length()); if (!userData.startsWith(VmInstances.VmSpecialUserData.EUCAKEY_CRED_SETUP.toString())) return; userData = new String(allocInfo.getUserData()); String payload = null; if (userData.length() > VmInstances.VmSpecialUserData.EUCAKEY_CRED_SETUP.toString().length()) { payload = userData.substring(VmInstances.VmSpecialUserData.EUCAKEY_CRED_SETUP.toString().length()) .trim(); } this.allocInfo.setUserDataAsString(payload); // create rsa keypair try { final KeyPair kp = Certs.generateKeyPair(); final X509Certificate kpCert = Certs.generateCertificate(kp, String.format("Certificate-for-%s/%s", this.allocInfo.getOwnerFullName().getAccountName(), this.allocInfo.getOwnerFullName().getUserName())); // call iam:signCertificate with the pub key final String b64PubKey = B64.standard.encString(PEMFiles.getBytes(kpCert)); final ServiceConfiguration euare = Topology.lookup(Euare.class); final SignCertificateType req = new SignCertificateType(); req.setCertificate(b64PubKey); final SignCertificateResponseType resp = AsyncRequests.sendSync(euare, req); final String token = resp.getSignCertificateResult().getSignature(); //in Base64 // use NODECERT to encrypt the pk // generate symmetric key final MessageDigest digest = Digest.SHA256.get(); final byte[] salt = new byte[32]; Crypto.getSecureRandomSupplier().get().nextBytes(salt); digest.update(salt); final SecretKey symmKey = new SecretKeySpec(digest.digest(), "AES"); // encrypt the server pk Cipher cipher = Ciphers.AES_GCM.get(); final byte[] iv = new byte[12]; Crypto.getSecureRandomSupplier().get().nextBytes(iv); cipher.init(Cipher.ENCRYPT_MODE, symmKey, new IvParameterSpec(iv)); final byte[] cipherText = cipher.doFinal(Base64.encode(PEMFiles.getBytes(kp.getPrivate()))); final String encPrivKey = new String(Base64.encode(Arrays.concatenate(iv, cipherText))); // encrypt the token from EUARE cipher = Ciphers.AES_GCM.get(); cipher.init(Cipher.ENCRYPT_MODE, symmKey, new IvParameterSpec(iv)); final byte[] byteToken = cipher.doFinal(token.getBytes()); final String encToken = new String(Base64.encode(Arrays.concatenate(iv, byteToken))); // encrypt the symmetric key X509Certificate nodeCert = this.allocInfo.getPartition().getNodeCertificate(); cipher = Ciphers.RSA_PKCS1.get(); cipher.init(Cipher.ENCRYPT_MODE, nodeCert.getPublicKey()); byte[] symmkey = cipher.doFinal(symmKey.getEncoded()); final String encSymmKey = new String(Base64.encode(symmkey)); X509Certificate euareCert = SystemCredentials.lookup(Euare.class).getCertificate(); final String b64EuarePubkey = B64.standard.encString(PEMFiles.getBytes(euareCert)); // EUARE's pubkey, VM's pubkey, token from EUARE(ENCRYPTED), SYM_KEY(ENCRYPTED), VM_KEY(ENCRYPTED) // each field all in B64 final String credential = String.format("%s\n%s\n%s\n%s\n%s", b64EuarePubkey, b64PubKey, encToken, // iam token encSymmKey, encPrivKey); this.allocInfo.setCredential(credential); } catch (final Exception ex) { LOG.error("failed to setup instance credential", ex); } }
From source file:com.eucalyptus.cloud.VmRunType.java
License:Open Source License
void setUserData(final String userData) { if (userData == null) { this.userData = new String(Base64.encode(new byte[] {})); } else {/* w w w. j a va 2 s. co m*/ this.userData = userData; } }
From source file:com.eucalyptus.cluster.VmInstance.java
License:Open Source License
public String getConsoleOutputString() { return new String(Base64.encode(this.consoleOutput.toString().getBytes())); }