天天看點

.NET中的加密類(非對稱加密)

using system;

using system.io;

using system.text;

using system.security.cryptography;

namespace apress.proaspnet.utility

{

public static class asymmetricencryptionutility

//生成并儲存密鑰;

public static string generatekey(string targetfile)

rsacryptoserviceprovider algorithm = new rsacryptoserviceprovider();

//儲存私鑰;

string completekey = algorithm.toxmlstring(true);

byte[] keybytes = encoding.utf8.getbytes(completekey);

keybytes = protecteddata.protect(keybytes,

null, dataprotectionscope.localmachine);

using (filestream fs = new filestream(targetfile, filemode.create))

fs.write(keybytes, 0, keybytes.length);

}

//傳回公鑰;

return algorithm.toxmlstring(false);

//讀取密鑰;

private static void readkey(rsacryptoserviceprovider algorithm, string keyfile)

byte[] keybytes;

using(filestream fs = new filestream(keyfile, filemode.open))

keybytes = new byte[fs.length];

fs.read(keybytes, 0, (int)fs.length);

keybytes = protecteddata.unprotect(keybytes, null, dataprotectionscope.localmachine);

algorithm.fromxmlstring(encoding.utf8.getstring(keybytes));

//【加密資料】

public static byte[] encryptdata(string data, string publickey)

// 基于公鑰建立加密算法;

algorithm.fromxmlstring(publickey);

// 加密目前資料;

return algorithm.encrypt(encoding.utf8.getbytes(data), true);

//【解密資料】

public static string decryptdata(byte[] data, string keyfile)

readkey(algorithm, keyfile);

byte[] cleardata = algorithm.decrypt(data, true);

return convert.tostring(encoding.utf8.getstring(cleardata));

繼續閱讀