java中sha256加解密方法
- 格式:docx
- 大小:3.89 KB
- 文档页数:4
java 密码加密解密方法在Java中,密码的加密和解密可以通过多种方式实现。
其中,常用的方法包括使用MessageDigest类进行加密,以及使用对称加密和非对称加密算法进行加密和解密。
一种常见的密码加密方法是使用MessageDigest类进行加密。
这可以通过以下步骤实现:首先,将密码转换为字节数组。
然后,使用MessageDigest类的getInstance方法获取特定的加密算法实例,例如SHA-256或MD5。
接下来,使用update方法将密码的字节数组传递给MessageDigest实例。
最后,使用digest方法获得加密后的字节数组,并将其转换为十六进制字符串或其他格式存储在数据库或其他地方。
另一种常见的方法是使用对称加密算法,例如AES或DES。
这些算法使用相同的密钥进行加密和解密。
在Java中,可以使用javax.crypto包中的类来实现对称加密。
通常,需要生成一个密钥并将其存储在安全的地方,然后使用该密钥对密码进行加密和解密。
此外,还可以使用非对称加密算法,例如RSA。
这种方法使用公钥对数据进行加密,然后使用私钥进行解密。
在Java中,可以使用java.security包中的类来实现非对称加密。
无论使用哪种方法,都需要注意密码安全的问题。
例如,密钥的安全存储和管理,以及密码传输过程中的安全性。
另外,还需要考虑密码的哈希加盐等技术来增加密码的安全性。
总之,在Java中实现密码的加密和解密有多种方法,开发人员可以根据实际需求和安全要求选择合适的加密算法和实现方式。
希望这些信息能够帮助你更好地理解Java中密码加密解密的方法。
java file类获取sha256的方法摘要:1.介绍SHA256算法的作用和应用场景2.讲解如何使用Java编写SHA256算法3.给出示例代码及解释正文:随着互联网技术的发展,数据安全越来越受到重视。
在众多加密算法中,SHA256(Secure Hash Algorithm 256)因其高安全性、高性能和短输出等特点被广泛应用。
本文将介绍如何使用Java编写SHA256算法,以期帮助读者更好地保护数据安全。
1.SHA256算法简介SHA256是一种密码散列算法,由美国国家安全局(NSA)设计。
它对输入数据进行加密处理后,输出一个16字节(128位)的固定长度值。
SHA256具有抗篡改性、高速度和易于实现等优点,适用于数据完整性校验、数字签名、文件加密等领域。
2.Java实现SHA256算法在Java中,我们可以使用内置的加密库来实现SHA256算法。
以下是一个简单的示例:```javaimport java.security.MessageDigest;import java.security.NoSuchAlgorithmException;import java.nio.charset.StandardCharsets;import java.math.BigInteger;public class SHA256Example {public static void main(String[] args) {String input = "Hello, World!";String hash = getSHA256Hash(input);System.out.println("SHA256 Hash: " + hash);}public static String getSHA256Hash(String input) {try {// 创建MessageDigest实例,指定使用SHA256算法MessageDigest md =MessageDigest.getInstance("SHA-256");// 对输入字符串进行加密byte[] messageDigest =md.digest(input.getBytes(StandardCharsets.UTF_8));// 将加密后的字节数组转换为十六进制字符串BigInteger no = new BigInteger(1, messageDigest);String hashtext = no.toString(16);// 补全32位长度while (hashtext.length() < 32) {hashtext = "0" + hashtext;}return hashtext;} catch (NoSuchAlgorithmException e) {throw new RuntimeException(e);}}}```在上面的示例中,我们首先导入了所需的库,然后创建了一个名为`getSHA256Hash`的方法。
密码学 java密码学是通过使用数学算法将信息转换为不可读格式(称为密文)来保护信息的机密性、完整性和真实性的实践。
在 Java 中,你可以使用`java.security`包来实现基本的加密、解密和安全哈希操作。
以下是一个简单的示例,展示了如何在 Java 中使用密码学来加密和解密信息:```javaimport java.security.MessageDigest;import java.security.NoSuchAlgorithmException;import java.security.spec.AlgorithmParameterSpec;import java.security.spec.KeySpec;import java.util.Base64;import javax.crypto.Cipher;import javax.crypto.spec.IvParameterSpec;import javax.crypto.spec.SecretKeySpec;public class CryptoUtils {public static void main(String[] args) {String message = "Hello, World!";String encryptedMessage = encryptMessage(message);String decryptedMessage = decryptMessage(encryptedMessage);System.out.println("原始消息: " + message);System.out.println("加密后的消息: " + encryptedMessage);System.out.println("解密后的消息: " + decryptedMessage);}public static String encryptMessage(String message) {try {// 生成密钥byte[] keyBytes = md.digest(message.getBytes());// 初始化加密器Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");SecretKeySpec secretKeySpec = new SecretKeySpec(keyBytes, "AES");IvParameterSpec ivParameterSpec = new IvParameterSpec(keyBytes);cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec, ivParameterSpec);// 加密消息byte[] encryptedBytes = cipher.doFinal(message.getBytes());// 将加密后的字节数组转换为 Base64 字符串String encryptedMessage = Base64.getEncoder().encodeToString(encryptedBytes);return encryptedMessage;} catch (NoSuchAlgorithmException | NoSuchPaddingException e) {e.printStackTrace();} catch (InvalidKeyException e) {e.printStackTrace();} catch (IllegalBlockSizeException | BadPaddingException e) {e.printStackTrace();}return null;}public static String decryptMessage(String encryptedMessage) {try {// 将 Base64 字符串转换为字节数组byte[] encryptedBytes = Base64.getDecoder().decode(encryptedMessage);// 生成密钥byte[] keyBytes = md.digest(encryptedMessage.getBytes());// 初始化解密器Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");SecretKeySpec secretKeySpec = new SecretKeySpec(keyBytes, "AES");IvParameterSpec ivParameterSpec = new IvParameterSpec(keyBytes);cipher.init(Cipher.DECRYPT_MODE, secretKeySpec, ivParameterSpec);// 解密消息byte[] decryptedBytes = cipher.doFinal(encryptedBytes);// 将解密后的字节数组转换为字符串String decryptedMessage = new String(decryptedBytes);return decryptedMessage;} catch (NoSuchAlgorithmException | NoSuchPaddingException e) {e.printStackTrace();} catch (InvalidKeyException e) {e.printStackTrace();} catch (IllegalBlockSizeException | BadPaddingException e) {e.printStackTrace();}return null;}}```这个示例中,我们使用`SHA-256`算法生成密钥,并使用`AES`算法对消息进行加密和解密。
PBKDF2 (Password-Based Key Derivation Function 2) 是一种用于从密码生成加密密钥的方法。
PBKDF2 通常与HMAC (Hash-based Message Authentication Code) 和SHA-256 (Secure Hash Algorithm 256) 一起使用,以提供强大的密钥派生功能。
以下是在Java 中使用javax.crypto.SecretKeyFactory和javax.crypto.spec.PBKDF2ParameterSpec实现PBKDF2WithHmacSHA256 的示例代码:java复制代码import javax.crypto.SecretKey;import javax.crypto.SecretKeyFactory;import javax.crypto.spec.PBKDF2ParameterSpec;import javax.crypto.spec.SecretKeySpec;import java.security.NoSuchAlgorithmException;import java.security.spec.InvalidKeySpecException;import java.security.spec.KeySpec;import java.util.Base64;public class PBKDF2WithHmacSHA256 {public static SecretKey generateKey(String password, byte[] salt, int iterations, int keySize)throws NoSuchAlgorithmException, InvalidKeySpecException {// 创建 PBKDF2 参数规范PBKDF2ParameterSpec spec = new PBKDF2ParameterSpec(password.toCharArray(), salt, iterations, keySize);// 创建密钥工厂SecretKeyFactory f = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256");// 生成密钥return f.generateSecret(new PBEKeySpec(password.toCharArray(), salt, iterations, keySize));}public static void main(String[] args)throws NoSuchAlgorithmException,InvalidKeySpecException {String password = "myPassword";byte[] salt = "mySalt".getBytes();int iterations = 65536;int keySize = 256;SecretKey key = generateKey(password, salt, iterations, keySize);// 将密钥转换为 Base64 字符串String keyString = Base64.getEncoder().encodeToString(key.getEncoded());System.out.println("Derived Key: " + keyString);}}这段代码首先定义了一个generateKey方法,它接受密码、盐值、迭代次数和密钥大小作为输入,并返回派生出的密钥。
java使⽤AES-256-ECB(PKCS7Padding)解密——微信⽀付退款通知接⼝。
1.场景 在做微信⽀付退款通知接⼝时,微信对通知的内容做了加密,并且指定⽤ AES256 解密,官⽅指定的解密⽅式如下:2.导包<!-- https:///artifact/org.bouncycastle/bcprov-jdk15on --><dependency><groupId>org.bouncycastle</groupId><artifactId>bcprov-jdk15on</artifactId><version>1.60</version></dependency><!-- https:///artifact/org.jasypt/jasypt --><dependency><groupId>org.jasypt</groupId><artifactId>jasypt</artifactId><version>1.9.3</version></dependency>3.解密 说明:⽅法中参数 reqInfo 就是退款结果通知接⼝中的 req_info 字段值private String descrypt(String reqInfo) throws NoSuchPaddingException, NoSuchAlgorithmException, NoSuchProviderException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException { byte[] reqInfoB = Base64.decodeBase64(reqInfo);String key_ = DigestUtils.md5Hex(WXPayConfig.getInstance().getKey()).toLowerCase();if (Security.getProvider("BC") == null){Security.addProvider(new BouncyCastleProvider());}Cipher cipher = Cipher.getInstance("AES/ECB/PKCS7Padding", "BC");SecretKeySpec secretKeySpec = new SecretKeySpec(key_.getBytes(), "AES");cipher.init(Cipher.DECRYPT_MODE, secretKeySpec);return new String(cipher.doFinal(reqInfoB));}4.结果5.上述过程之后在win本地运⾏没问题了,但是放到 linux 之后报错如下: java.security.InvalidKeyException: Illegal key size or default parameters 最终还是按⽹友的⽅法解决:替换jre包:local_policy.jar,US_export_policy.jar 5.1.下载 需要注意的是:替换的jar包版本需要与jre版本⼀致,各个版本包连接 jdk8: jdk7: jdk6: jdk5: 5.2.替换路径 %JAVE_HOME%\jre\lib\security6.参考 解密⽅式: 报错解决(报错内容“No such provider: BC”): 替换包参考:。
⼏种加密算法的java实现包括MD5、RSA、SHA256 SHA加密:package com;import java.security.MessageDigest;import java.security.NoSuchAlgorithmException;/*** 对外提供getSHA(String str)⽅法* @author randyjia**/public class SHA {public static String Encrypt(String strSrc, String encName) {MessageDigest md = null;StringBuilder sb = new StringBuilder();byte[] bt = strSrc.getBytes();try {md = MessageDigest.getInstance(encName);byte[] result = md.digest(bt);for (byte b : result) {sb.append(String.format("%02x", b));}} catch (NoSuchAlgorithmException e) {return null;}return sb.toString();}public static void main(String args[]){String s = SHA.Encrypt("12345", "SHA-256");System.out.println(s);}}RSA加密:package com;import java.io.*;import java.security.*;import javax.crypto.*;import java.security.spec.X509EncodedKeySpec;import java.security.spec.PKCS8EncodedKeySpec;import sun.misc.*;public class Rsa_test {private KeyPairGenerator kpg = null;private KeyPair kp = null;private PublicKey public_key = null;private PrivateKey private_key = null;public Rsa_test(int in, String address) throws NoSuchAlgorithmException,FileNotFoundException, IOException{kpg = KeyPairGenerator.getInstance("RSA");kpg.initialize(in);kp = kpg.genKeyPair();public_key = kp.getPublic();private_key = kp.getPrivate();sun.misc.BASE64Encoder b64 = new sun.misc.BASE64Encoder();String pkStr = b64.encode(public_key.getEncoded());String prStr = b64.encode(private_key.getEncoded());System.out.print("pkStr length:" +pkStr.length()+" "+pkStr);FileWriter fw=new FileWriter(address + "/private_key.dat");fw.write(prStr);fw.close();FileWriter fw2 = new FileWriter(address + "/public_key.dat");fw2.write(pkStr);fw2.close();}private static String encrypt(String source) throws Exception{FileReader fr = new FileReader("E://public_key.dat");BufferedReader br=new BufferedReader(fr);String getPbKey = "";while(true){String aLine = br.readLine();if(aLine==null)break;getPbKey += aLine;}System.out.println( "myBuilderStr : length: " + getPbKey.length() +" "+getPbKey ); BASE64Decoder b64d = new BASE64Decoder();byte [] keyByte = b64d.decodeBuffer(getPbKey);X509EncodedKeySpec x509ek = new X509EncodedKeySpec(keyByte); KeyFactory keyFactory = KeyFactory.getInstance("RSA");PublicKey publicKey = keyFactory.generatePublic(x509ek);Cipher cipher = Cipher.getInstance("RSA");cipher.init(Cipher.ENCRYPT_MODE,publicKey);byte[] sbt = source.getBytes();byte [] epByte = cipher.doFinal(sbt);BASE64Encoder encoder = new BASE64Encoder();String epStr = encoder.encode(epByte);return epStr;}public static String decrypt(String cryptograph) throws Exception{FileReader fr = new FileReader("E://private_key.dat");BufferedReader br=new BufferedReader(fr);String getPvKey = "";while(true){String aLine = br.readLine();if(aLine==null)break;getPvKey += aLine;}BASE64Decoder b64d = new BASE64Decoder();byte [] keyByte = b64d.decodeBuffer(getPvKey);PKCS8EncodedKeySpec s8ek = new PKCS8EncodedKeySpec(keyByte); KeyFactory keyFactory = KeyFactory.getInstance("RSA");PrivateKey privateKey = keyFactory.generatePrivate(s8ek);Cipher cipher = Cipher.getInstance("RSA");cipher.init(Cipher.DECRYPT_MODE, privateKey);BASE64Decoder decoder = new BASE64Decoder();byte[] b1 = decoder.decodeBuffer(cryptograph);byte[] b = cipher.doFinal(b1);return new String(b);}/*public static void main(String[] args) {try {new Rsa_test(1024, "E:/");System.out.println("");String getEptStr = encrypt("wuchao");System.out.println("getEptStr:"+getEptStr);String drpStr = decrypt(getEptStr);System.out.println("drpStr:"+drpStr);}catch (IOException ex) {ex.printStackTrace();}catch (NoSuchAlgorithmException ex) {ex.printStackTrace();}catch(Exception ex){ex.printStackTrace();}}*/}MD5加密:package com;import java.security.MessageDigest;public class Md5 {public final static String MD5(String s) {char hexDigits[]={'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'}; try {byte[] btInput = s.getBytes();MessageDigest mdInst = MessageDigest.getInstance("MD5"); mdInst.update(btInput);byte[] md = mdInst.digest();int j = md.length;char str[] = new char[j * 2];int k = 0;for (int i = 0; i < j; i++) {byte byte0 = md[i];str[k++] = hexDigits[byte0 >>> 4 & 0xf];str[k++] = hexDigits[byte0 & 0xf];}return new String(str);} catch (Exception e) {e.printStackTrace();return null;}}public static void main(String[] args) {// TODO Auto-generated method stubSystem.out.println(Md5.MD5("20121221asfasfasfa")); System.out.println(Md5.MD5("����"));}}。
BASE64,MD5,SHA,HMAC加密與解密算法(java) 1package com.ice.webos.util.security;23import java.io.UnsupportedEncodingException;4import java.math.BigInteger;5import java.security.Key;6import java.security.MessageDigest;7import java.security.SecureRandom;89import javax.crypto.Cipher;10import javax.crypto.KeyGenerator;11import javax.crypto.Mac;12import javax.crypto.SecretKey;13import javax.crypto.SecretKeyFactory;14import javax.crypto.spec.DESKeySpec;15import javax.crypto.spec.SecretKeySpec;1617import sun.misc.BASE64Decoder;18import sun.misc.BASE64Encoder;1920/**21 * <ul>22 * <li>BASE64的加密解密是双向的,可以求反解。
</li>23 * <li>MD5、SHA以及HMAC是单向加密,任何数据加密后只会产⽣唯⼀的⼀个加密串,通常⽤来校验数据在传输过程中是否被修改。
</li>24 * <li>HMAC算法有⼀个密钥,增强了数据传输过程中的安全性,强化了算法外的不可控因素。
</li>25 * <li>DES DES-Data Encryption Standard,即数据加密算法。
JavaScriptSHA-256加密算法详细代码本⽂实例为⼤家分享了JavaScript SHA-256加密算法,供⼤家参考,具体内容如下/** A JavaScript implementation of the Secure Hash Algorithm, SHA-256, as defined* in FIPS 180-2* Version 2.2 Copyright Angel Marin, Paul Johnston 2000 - 2009.* Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet* Distributed under the BSD License* See /crypt/md5 for details.* Also /projects/jssha2/*//** Configurable variables. You may need to tweak these to be compatible with* the server-side, but the defaults work in most cases.*/var hexcase = 0; /* hex output format. 0 - lowercase; 1 - uppercase */var b64pad = ""; /* base-64 pad character. "=" for strict RFC compliance *//** These are the functions you'll usually want to call* They take string arguments and return either hex or base-64 encoded strings*/function hex_sha256(s) { return rstr2hex(rstr_sha256(str2rstr_utf8(s))); }function b64_sha256(s) { return rstr2b64(rstr_sha256(str2rstr_utf8(s))); }function any_sha256(s, e) { return rstr2any(rstr_sha256(str2rstr_utf8(s)), e); }function hex_hmac_sha256(k, d){ return rstr2hex(rstr_hmac_sha256(str2rstr_utf8(k), str2rstr_utf8(d))); }function b64_hmac_sha256(k, d){ return rstr2b64(rstr_hmac_sha256(str2rstr_utf8(k), str2rstr_utf8(d))); }function any_hmac_sha256(k, d, e){ return rstr2any(rstr_hmac_sha256(str2rstr_utf8(k), str2rstr_utf8(d)), e); }/** Perform a simple self-test to see if the VM is working*/function sha256_vm_test(){return hex_sha256("abc").toLowerCase() =="ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad";}/** Calculate the sha256 of a raw string*/function rstr_sha256(s){return binb2rstr(binb_sha256(rstr2binb(s), s.length * 8));}/** Calculate the HMAC-sha256 of a key and some data (raw strings)*/function rstr_hmac_sha256(key, data){var bkey = rstr2binb(key);if(bkey.length > 16) bkey = binb_sha256(bkey, key.length * 8);var ipad = Array(16), opad = Array(16);for(var i = 0; i < 16; i++){ipad[i] = bkey[i] ^ 0x36363636;opad[i] = bkey[i] ^ 0x5C5C5C5C;}var hash = binb_sha256(ipad.concat(rstr2binb(data)), 512 + data.length * 8);return binb2rstr(binb_sha256(opad.concat(hash), 512 + 256));}/** Convert a raw string to a hex string*/function rstr2hex(input){try { hexcase } catch(e) { hexcase=0; }var hex_tab = hexcase ? "0123456789ABCDEF" : "0123456789abcdef";var output = "";var x;for(var i = 0; i < input.length; i++){x = input.charCodeAt(i);output += hex_tab.charAt((x >>> 4) & 0x0F)+ hex_tab.charAt( x & 0x0F);}return output;}/** Convert a raw string to a base-64 string*/function rstr2b64(input){try { b64pad } catch(e) { b64pad=''; }var tab = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; var output = "";var len = input.length;for(var i = 0; i < len; i += 3){var triplet = (input.charCodeAt(i) << 16)| (i + 1 < len ? input.charCodeAt(i+1) << 8 : 0)| (i + 2 < len ? input.charCodeAt(i+2) : 0);for(var j = 0; j < 4; j++){if(i * 8 + j * 6 > input.length * 8) output += b64pad;else output += tab.charAt((triplet >>> 6*(3-j)) & 0x3F);}}return output;}/** Convert a raw string to an arbitrary string encoding*/function rstr2any(input, encoding){var divisor = encoding.length;var remainders = Array();var i, q, x, quotient;/* Convert to an array of 16-bit big-endian values, forming the dividend */var dividend = Array(Math.ceil(input.length / 2));for(i = 0; i < dividend.length; i++){dividend[i] = (input.charCodeAt(i * 2) << 8) | input.charCodeAt(i * 2 + 1);}/** Repeatedly perform a long division. The binary array forms the dividend,* the length of the encoding is the divisor. Once computed, the quotient* forms the dividend for the next step. We stop when the dividend is zero.* All remainders are stored for later use.*/while(dividend.length > 0){quotient = Array();x = 0;for(i = 0; i < dividend.length; i++){x = (x << 16) + dividend[i];q = Math.floor(x / divisor);x -= q * divisor;if(quotient.length > 0 || q > 0)quotient[quotient.length] = q;}remainders[remainders.length] = x;dividend = quotient;}/* Convert the remainders to the output string */var output = "";for(i = remainders.length - 1; i >= 0; i--)output += encoding.charAt(remainders[i]);/* Append leading zero equivalents */var full_length = Math.ceil(input.length * 8 /(Math.log(encoding.length) / Math.log(2)))for(i = output.length; i < full_length; i++)output = encoding[0] + output;return output;}/** Encode a string as utf-8.* For efficiency, this assumes the input is valid utf-16.*/function str2rstr_utf8(input){var output = "";var i = -1;var x, y;while(++i < input.length){/* Decode utf-16 surrogate pairs */x = input.charCodeAt(i);y = i + 1 < input.length ? input.charCodeAt(i + 1) : 0;if(0xD800 <= x && x <= 0xDBFF && 0xDC00 <= y && y <= 0xDFFF) {x = 0x10000 + ((x & 0x03FF) << 10) + (y & 0x03FF);i++;}/* Encode output as utf-8 */if(x <= 0x7F)output += String.fromCharCode(x);else if(x <= 0x7FF)output += String.fromCharCode(0xC0 | ((x >>> 6 ) & 0x1F),0x80 | ( x & 0x3F));else if(x <= 0xFFFF)output += String.fromCharCode(0xE0 | ((x >>> 12) & 0x0F),0x80 | ((x >>> 6 ) & 0x3F),0x80 | ( x & 0x3F));else if(x <= 0x1FFFFF)output += String.fromCharCode(0xF0 | ((x >>> 18) & 0x07),0x80 | ((x >>> 12) & 0x3F),0x80 | ((x >>> 6 ) & 0x3F),0x80 | ( x & 0x3F));}return output;}/** Encode a string as utf-16*/function str2rstr_utf16le(input){var output = "";for(var i = 0; i < input.length; i++)output += String.fromCharCode( input.charCodeAt(i) & 0xFF,(input.charCodeAt(i) >>> 8) & 0xFF);return output;}function str2rstr_utf16be(input){var output = "";for(var i = 0; i < input.length; i++)output += String.fromCharCode((input.charCodeAt(i) >>> 8) & 0xFF, input.charCodeAt(i) & 0xFF);return output;}/** Convert a raw string to an array of big-endian words* Characters >255 have their high-byte silently ignored.*/function rstr2binb(input){var output = Array(input.length >> 2);for(var i = 0; i < output.length; i++)output[i] = 0;for(var i = 0; i < input.length * 8; i += 8)output[i>>5] |= (input.charCodeAt(i / 8) & 0xFF) << (24 - i % 32);return output;}/** Convert an array of big-endian words to a string*/function binb2rstr(input){var output = "";for(var i = 0; i < input.length * 32; i += 8)output += String.fromCharCode((input[i>>5] >>> (24 - i % 32)) & 0xFF);return output;}/** Main sha256 function, with its support functions*/function sha256_S (X, n) {return ( X >>> n ) | (X << (32 - n));}function sha256_R (X, n) {return ( X >>> n );}function sha256_Ch(x, y, z) {return ((x & y) ^ ((~x) & z));}function sha256_Maj(x, y, z) {return ((x & y) ^ (x & z) ^ (y & z));}function sha256_Sigma0256(x) {return (sha256_S(x, 2) ^ sha256_S(x, 13) ^ sha256_S(x, 22));} function sha256_Sigma1256(x) {return (sha256_S(x, 6) ^ sha256_S(x, 11) ^ sha256_S(x, 25));} function sha256_Gamma0256(x) {return (sha256_S(x, 7) ^ sha256_S(x, 18) ^ sha256_R(x, 3));} function sha256_Gamma1256(x) {return (sha256_S(x, 17) ^ sha256_S(x, 19) ^ sha256_R(x, 10));} function sha256_Sigma0512(x) {return (sha256_S(x, 28) ^ sha256_S(x, 34) ^ sha256_S(x, 39));} function sha256_Sigma1512(x) {return (sha256_S(x, 14) ^ sha256_S(x, 18) ^ sha256_S(x, 41));} function sha256_Gamma0512(x) {return (sha256_S(x, 1) ^ sha256_S(x, 8) ^ sha256_R(x, 7));} function sha256_Gamma1512(x) {return (sha256_S(x, 19) ^ sha256_S(x, 61) ^ sha256_R(x, 6));} var sha256_K = new Array(1116352408, 1899447441, -1245643825, -373957723, 961987163, 1508970993,-1841331548, -1424204075, -670586216, 310598401, 607225278, 1426881987,1925078388, -2132889090, -1680079193, -1046744716, -459576895, -272742522,264347078, 604807628, 770255983, 1249150122, 1555081692, 1996064986,-1740746414, -1473132947, -1341970488, -1084653625, -958395405, -710438585,113926993, 338241895, 666307205, 773529912, 1294757372, 1396182291,1695183700, 1986661051, -2117940946, -1838011259, -1564481375, -1474664885,-1035236496, -949202525, -778901479, -694614492, -200395387, 275423344,430227734, 506948616, 659060556, 883997877, 958139571, 1322822218,1537002063, 1747873779, 1955562222, 2024104815, -2067236844, -1933114872,-1866530822, -1538233109, -1090935817, -965641998);function binb_sha256(m, l){var HASH = new Array(1779033703, -1150833019, 1013904242, -1521486534,1359893119, -1694144372, 528734635, 1541459225);var W = new Array(64);var a, b, c, d, e, f, g, h;var i, j, T1, T2;/* append padding */m[l >> 5] |= 0x80 << (24 - l % 32);m[((l + 64 >> 9) << 4) + 15] = l;for(i = 0; i < m.length; i += 16){a = HASH[0];b = HASH[1];c = HASH[2];d = HASH[3];e = HASH[4];f = HASH[5];g = HASH[6];h = HASH[7];for(j = 0; j < 64; j++){if (j < 16) W[j] = m[j + i];else W[j] = safe_add(safe_add(safe_add(sha256_Gamma1256(W[j - 2]), W[j - 7]),sha256_Gamma0256(W[j - 15])), W[j - 16]);T1 = safe_add(safe_add(safe_add(safe_add(h, sha256_Sigma1256(e)), sha256_Ch(e, f, g)),sha256_K[j]), W[j]);T2 = safe_add(sha256_Sigma0256(a), sha256_Maj(a, b, c));h = g;g = f;f = e;e = safe_add(d, T1);d = c;c = b;b = a;a = safe_add(T1, T2);}HASH[0] = safe_add(a, HASH[0]);HASH[1] = safe_add(b, HASH[1]);HASH[2] = safe_add(c, HASH[2]);HASH[3] = safe_add(d, HASH[3]);HASH[4] = safe_add(e, HASH[4]);HASH[5] = safe_add(f, HASH[5]);HASH[6] = safe_add(g, HASH[6]);HASH[7] = safe_add(h, HASH[7]);}return HASH;}function safe_add (x, y){var lsw = (x & 0xFFFF) + (y & 0xFFFF);var msw = (x >> 16) + (y >> 16) + (lsw >> 16);return (msw << 16) | (lsw & 0xFFFF);}以上就是本⽂的全部内容,希望对⼤家有所帮助,希望⼤家继续关注的最新内容。
【JavaAES】对称加密算法AES256加密解密例程本⽂例程下载:代码:package ufo;import java.security.SecureRandom;import javax.crypto.Cipher;import javax.crypto.KeyGenerator;import javax.crypto.SecretKey;import javax.crypto.spec.SecretKeySpec;import mons.codec.binary.Base64;public class AES_Test {public static void main(String... args) {String original="Let’s Build a Giant Airship 青海长云暗雪⼭";System.out.println("原⽂=\t"+original);try {// ⽣产密钥KeyGenerator kgen = KeyGenerator.getInstance("AES");kgen.init(256, new SecureRandom("RND SEED".getBytes()));SecretKey secretKey = kgen.generateKey();byte[] enCodeFormat = secretKey.getEncoded();SecretKeySpec key = new SecretKeySpec(enCodeFormat, "AES");// 密钥,下⾯加密解密都要⽤到System.out.println("密钥=\t"+Base64.encodeBase64String(key.getEncoded()));// 加密Cipher cipherEncode = Cipher.getInstance("AES");byte[] byteContent = original.getBytes();cipherEncode.init(Cipher.ENCRYPT_MODE, key);byte[] EncodeResults = cipherEncode.doFinal(byteContent);System.out.println("密⽂=\t"+Base64.encodeBase64String(EncodeResults));// 解密Cipher cipherDecode = Cipher.getInstance("AES");// 创建密码器cipherDecode.init(Cipher.DECRYPT_MODE, key);// 初始化为解密模式的密码器byte[] DecodeResults = cipherDecode.doFinal(EncodeResults);System.out.println("解密后=\t"+new String(DecodeResults));} catch (Exception e) {// TODO Auto-generated catch blocke.printStackTrace();}}}输出:原⽂= Let’s Build a Giant Airship 青海长云暗雪⼭密钥= ehduBRkCK/qc2h02PT0UDprNGdi8H2bLLmAvUIC+7n8=密⽂= cfA39gplPGSSIVCVRuWyaVY9Gfq2HPxvFEOfxD7n/F6b/CG8R3rERXrg70WrQ1nW解密后= Let’s Build a Giant Airship 青海长云暗雪⼭pom.xml中需要引⼊的依赖:<dependency><groupId>commons-codec</groupId><artifactId>commons-codec</artifactId><version>1.15</version></dependency>END。
java中sha256加解密方法
SHA256是一种常用的加密算法,它可以对数据进行加密和解密操作。
在Java中,我们可以使用Java的安全库提供的功能来实现SHA256的加解密。
我们需要导入Java的安全库,这可以通过在代码中添加以下语句来实现:
```
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
```
接下来,我们需要定义一个方法来实现SHA256的加密功能,可以命名为sha256Encrypt。
该方法接受一个字符串作为参数,并返回一个加密后的字符串。
具体代码如下:
```
public static String sha256Encrypt(String input) {
try {
MessageDigest digest = MessageDigest.getInstance("SHA-256");
byte[] hash = digest.digest(input.getBytes("UTF-8"));
StringBuilder hexString = new StringBuilder();
for (byte b : hash) {
String hex = Integer.toHexString(0xff & b);
if (hex.length() == 1) hexString.append('0');
hexString.append(hex);
}
return hexString.toString();
} catch (NoSuchAlgorithmException | UnsupportedEncodingException e) {
e.printStackTrace();
}
return null;
}
```
在这个方法中,我们首先通过调用MessageDigest.getInstance("SHA-256")来获取SHA-256算法的实例。
然后,我们使用digest方法对输入字符串进行加密,并得到一个字节数组。
接下来,我们将字节数组转换成十六进制字符串,并返回加密后的字符串。
当需要对数据进行加密时,我们可以调用上述的sha256Encrypt方法,传入需要加密的字符串作为参数。
例如:
```
String encryptedString = sha256Encrypt("Hello, world!");
System.out.println("加密后的字符串:" + encryptedString);
```
除了加密,我们还可以实现SHA256的解密功能。
虽然SHA256是一种单向加密算法,不可逆,但我们可以通过暴力破解的方式来尝试解密。
具体代码如下:
```
public static String sha256Decrypt(String encryptedString) { // 暴力破解,遍历所有可能的字符串
for (int i = 0; i < 999999; i++) {
String candidate = String.format("%06d", i);
if (sha256Encrypt(candidate).equals(encryptedString)) { return candidate;
}
}
return null;
}
```
在这个方法中,我们通过遍历所有可能的字符串,并将其加密后与目标字符串进行比较。
如果加密结果匹配,即找到了解密后的字符串。
需要注意的是,由于SHA256是一种强大的加密算法,暴力破解的方式并不可行。
因此,实际应用中很少需要对SHA256进行解密操作。
在实际应用中,我们通常使用SHA256来对用户的密码进行加密存储。
当用户登录时,我们将用户输入的密码进行加密,然后与存储的加密密码进行比较,从而验证用户身份的合法性。
总结来说,SHA256是一种常用的加密算法,可以对数据进行加密和解密操作。
在Java中,我们可以使用Java的安全库提供的功能来实现SHA256的加解密。
通过对用户密码进行加密存储,我们可以提高系统的安全性。